L=[0,1,4,2,3,4]
L.sort()
if len(L)%2==1:
print L[len(L)//2]
else:
print (L[len(L)/2]+L[len(L)/2-1])/2.0
- read more
7.For the rectangular area
read moreprint a*b,2*(a+b)
6.To solve all the prime Numbers within 100
read moreprimes = [] for i in range(2, 101): for t in range(2, i): if i % t == 0: break else: primes.append(i) print primes print ' '.join(map(str, primes))
5.The output characters of the odd location of the string
read more# method 1 a= "12345" print "".join([a[i] for i in range(len(a)) if i%2==0]) print ( ''.join([ c for i, c in enumerate(a) if i % 2 == 0]) ) # i is list[0, 1, 2, 3, 4], c is ['1', '2', '3', '4', '5'] print ( ''.join([ str(i ...
4.Output the dictionary keys
read morea={1:1,2:2,3:3} # method 1 print ",".join([str(i) for i in a.keys()]) # attention! join string! a.keys() is a list # method 2 print ",".join(map(str, a.keys())) # map(func, list)
3.Reverse a string
read morea="12345" # method 1 print(a[::-1]) # method 2 from functools import reduce print reduce((lambda x, y: y+x), a) # reduce is [ func(func(s1, s2),s3), ... , sn ] # method 3 print "".join(reversed(a)) # reversed(object) return a iterator, type 'reversed', join(iterable)
2.Sort the list
read moreL=[2,8,5,3] L.sort() print L new_list = sorted(L) print new_list
9. Palindrome Number
read moreclass Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ y = str(x) if len(y)==1: return True else: pal=True i=0 while i < len(y) and pal: if y[i]==y[len(y)-1-i]: i+=1 else: pal=False return pal if __name__=="__main__ ...
8. String to Integer (atoi)
read moreclass Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ if len(str) == 0: return 0 lst_str = list(str.strip()) sign = 1 digit = 1 r_lst = [] for i in lst_str: if i is '+': sign *= 1 if i is '-': sign *= -1 if i >= '0' and i <= '9': r_lst.append(i ...
7. Reverse Intege
read moreclass Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if abs(x)!=x: a=-1 else: a=1 x=abs(x) total=0 while x>0: n=x%10 total=total*10+n x=x//10 return total*a if __name__ == "__main__": answer = Solution() print answer.reverse ...