codewars python 学习

1.Sum of Digits / Digital Root

def digital_root(n):
    # ...
    while n>9:
        n = sum(int(digit) for digit in str(n))
    return n

2.Replace With Alphabet Position

def alphabet_position(text):

    testlist = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    indexlist = []
    for i in text:
        for j in testlist:
            if i.lower()==j:
                indexlist.append(testlist.index(j)+1)
                
    newlist = " ".join(str(i) for i in indexlist)
    return (newlist)

3.Printer Errors

def printer_error(s):
    # your code
    listb = ['n','o','p','q','r','s','t','u','v','w','x','y','z']
    num = 0
    for i in s:
        for j in listb:
            if i==j:
                num += 1
    return str(num)+"/"+str(len(s))

4.Get the Middle Character

def get_middle(s):

    if len(s)==1 or len(s)==2:
        return s
    elif len(s)%2 == 0:
        halfs = int((len(s)/2)+1)
        halfsp = int((len(s)/2)-1)
        newone = s[halfsp:halfs]
        return newone
    else:
        middleindex = int((len(s)-1)/2)
        return s[middleindex]
        

5.Vowel Count

def get_count(sentence):
    vowels = ['a','o','e','i','u']
    countt = 0
    for i in sentence:
        for j in vowels:
            if i==j:
                countt += 1
    return countt

6.Mumbling

def accum(s):
    # your code
    newss = list(s)
    aa = []
    bb = []
    for i in newss:
        j=len(aa)+1
        ss = str(i)*j
        ss2 = ss.capitalize()
        bb.append(ss2)
        aa.append(i)
    cc = "-".join(bb)
    return cc

            

7.Ones and Zeros

def binary_array_to_number(arr):
  # your code
    ssum = 0
    empp = []
    arr.reverse()
    print(arr)
    for i in arr:
        if i == 1:
            ssum +=  2**(len(empp))
            
        empp.append(i)
    return ssum
        

8.Find the missing letter

def find_missing_letter(chars):
    lowerletter = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    upperletter = [x.upper() for x in lowerletter]
    aa = []
#     print(upperletter)
    if (chars[0].isupper()):
        a = upperletter.index(chars[0])
        b = upperletter.index(chars[-1])
        newlist = upperletter[a:(b+1)]
        aa = [i for i in newlist if i not in chars] 
        bb = ','.join(aa)
        return bb
    else:
        a = lowerletter.index(chars[0])
        b = lowerletter.index(chars[-1])
        newlist = lowerletter[a:(b+1)]
        aa = [i for i in newlist if i not in chars] 
        bb = ','.join(aa)
        return bb

9.Odd or Even?

def odd_or_even(arr):
    sum = 0
    for i in arr:
        sum += i
    if(sum%2==0):
        return "even"
    else:
        return "odd"

10.Multiples of 3 or 5

def solution(number):
    listt = []
    listf = []
    lists = []
    for i in range(1,number):
        if(i*3

11.Create Phone Number

def create_phone_number(n):
#     pp = " ".join(n)
#     print(pp)
    a = n[0:3]
    aa = "".join(str(a) for a in n[0:3])
    bb = "".join(str(b) for b in n[3:6])
    cc = "".join(str(c) for c in n[6:10])
    newone = ("("+aa+")"+" "+bb+"-"+cc)
    return newone

   

12.Persistent Bugger.

def persistence(n):
    # your code
    count = 0
    multilples = 1
    newone = n
    if n<10:
        return 0
    else:
        while(newone>=10):
            for i in str(newone):
                multilples = multilples * int(i)
            count += 1
            newone = multilples
            multilples = 1
        return count

13.Your order, please

def order(sentence):
    newsen = sentence.split(" ")
    emptydict = {}
    for i in newsen:
        for j in i:
            if j.isdigit():
                j = int(j)
                emptydict[j] = i

    testnewdicts =sorted(emptydict.items(),key=lambda x:x[0])
    testnewdict = dict(testnewdicts)
    newsenlist = [k for k in testnewdict.values()]
    newsenstr = " ".join(newsenlist) 
    return newsenstr


14.Who likes it?

def likes(names):
    # your code here
    othernum = str(len(names)-2)
    if(len(names)==0):
        return "no one likes this"
    elif(len(names)==1):
        return names[0]+" likes this"
    elif(len(names)==2):
        return names[0]+" and "+names[1]+" like this"
    elif(len(names)==3):
        return names[0]+", "+names[1]+" and "+names[2]+" like this"
    else:
        return names[0]+", "+names[1]+" and "+othernum+" others like this"

15.First non-repeating character

def first_non_repeating_letter(s):
    news = s.lower()
    counts = {}
    for i in news:
        counts[i] = news.count(i)

    for k in counts.keys():
        if(counts[k]==1):
            if(k.upper() in s):
                return k.upper()
            else:
                return k
            break
    return ""

16.String incrementer

def increment_string(strng):
    if(strng.isdigit()):
        newstr = str(int(strng)+1)
        lendiffzero = (len(strng)-len(newstr))*"0"
        return lendiffzero+newstr
    else:
        newrev = strng[::-1]
        striindex=0
        for i in newrev:
            if not(i.isdigit()):
                striindex = newrev.index(i)
                break
        strindex = (striindex)*(-1)
        numindex = (striindex)*(-1)
        if(strindex==0):
            return strng+"1"
        elif(strng.isdigit()):
            return int(strng)+1
        else:
            strstr = strng[:strindex]
            intstr = strng[numindex:]
            newint = int(intstr)+1
            newstr = strstr+str(newint)
            lendiffzero = (len(strng)-len(newstr))*"0"
            laststr = strstr +lendiffzero+str(newint)
            return laststr

17.Extract the domain name from a URL

def domain_name(url):
    if("//" in url and "www" not in url):
        newurl = url.split("//")
        domain = newurl[1].split(".")
        return domain[0]
    elif("www" in url and "//" in url):
        newurl = url.split("//")
        domain = newurl[1].split(".")
        return domain[1]
    elif("www" in url and "//" not in url):
        domain = url.split(".")
        return domain[1]
    else:
        domain = url.split(".")
        return domain[0]

        

18.Sum of Intervals

def sum_of_intervals(intervals):
    sortedinterval= sorted(intervals,key = lambda x:x[0])
    total_sum = 0
    prev_end = float("-inf")
    for start,end in sortedinterval:
        if start > prev_end:
            total_sum += end-start
            prev_end = end
        elif end > prev_end:
            total_sum += end-prev_end
            prev_end = end
    return total_sum

17.Number of trailing zeros of N!

def zeros(n):
    count = 0
    divisor = 5
    while n>= divisor:
        count += n // divisor
        divisor *= 5
    return count

18.The Hashtag Generator

def generate_hashtag(s):
    if 0

19.Memoized Fibonacci

def fibonacci(n, cache={}):
    if n <= 1:
        return n
    if n not in cache:
        cache[n] = fibonacci(n-1,cache)+fibonacci(n-2,cache)
        
    return cache[n]

20.Snail

def snail(snail_map):
    result = []
    while snail_map:
        #the first row
        result += snail_map.pop(0)
        #the right side elements
        for row in snail_map:
            result.append(row.pop())
        #the bottom elements:
        if snail_map:
            result += snail_map.pop()[::-1]   
        #the left elements
        for row in reversed(snail_map):
            result.append(row.pop(0))
    return result
        
        

你可能感兴趣的:(学习,算法)