Python打卡Day3
Question 10
Question
Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program:
1hello world and practice makes perfect and hello world again
Then, the output should be:
1again and hello makes perfect practice world
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.We use set container to remove duplicated data automatically and then use sorted() to sort the data.
Main author's Solution: Python 2
1s = raw_input()
2words = [word for word in s.split(" ")]
3print " ".join(sorted(list(set(words))))
My Solution: Python 3
1word = input().split()
2
3for i in word:
4 if word.count(i) > 1: #count function returns total repeatation of an element that is send as argument
5 word.remove(i) # removes exactly one element per call
6
7word.sort()
8print(" ".join(word))
OR
1word = input().split()
2[word.remove(i) for i in word if word.count(i) > 1 ] # removal operation with comprehension method
3word.sort()
4print(" ".join(word))
OR
1word = sorted(list(set(input().split()))) # input string splits -> converting into set() to store unique
2 # element -> converting into list to be able to apply sort
3print(" ".join(word))
1'''Solution by: Sukanya-Mahapatra
2'''
3inp_string = input("Enter string: ").split()
4out_string = []
5for words in inp_string:
6 if words not in out_string:
7 out_string.append(words)
8print(" ".join(sorted(out_string)))
Question 11
Question
Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
10100,0011,1010,1001
Then the output should be:
11010
Notes: Assume the data is input by console.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Main author's Solution: Python 2
1value = []
2items=[x for x in raw_input().split(',')]
3for p in items:
4 intp = int(p,2)
5 if not intp % 5:
6 value.append(p)
7
8print ','.join(value)
My Solution: Python 3
1def check(x): # converts binary to integer & returns zero if divisible by 5
2 total,pw = 0,1
3 reversed(x)
4
5 for i in x:
6 total+=pw * (ord(i) - 48) # ord() function returns ASCII value
7 pw*=2
8 return total % 5
9
10data = input().split(",") # inputs taken here and splited in ',' position
11lst = []
12
13for i in data:
14 if check(i) == 0: # if zero found it means divisible by zero and added to the list
15 lst.append(i)
16
17print(",".join(lst))
OR
1def check(x): # check function returns true if divisible by 5
2 return int(x,2)%5 == 0 # int(x,b) takes x as string and b as base from which
3 # it will be converted to decimal
4data = input().split(',')
5
6data = list(filter(check,data)) # in filter(func,object) function, elements are picked from 'data' if found True by 'check' function
7print(",".join(data))
OR
1data = input().split(',')
2data = list(filter(lambda i:int(i,2)%5==0,data)) # lambda is an operator that helps to write function of one line
3print(",".join(data))
1'''Solution by: nikitaMogilev
2'''
3data = input().split(',')
4data = [num for num in data if int(num, 2) % 5 == 0]
5print(','.join(data))
Question 12
Question:
Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.The numbers obtained should be printed in a comma-separated sequence on a single line.
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Main author's Solution: Python 2
1values = []
2for i in range(1000, 3001):
3 s = str(i)
4 if (int(s[0])%2 == 0) and (int(s[1])%2 == 0) and (int(s[2])%2 == 0) and (int(s[3])%2 == 0):
5 values.append(s)
6print ",".join(values)
My Solution: Python 3
1lst = []
2
3for i in range(1000,3001):
4 flag = 1
5 for j in str(i): # every integer number i is converted into string
6 if ord(j)%2 != 0: # ord returns ASCII value and j is every digit of i
7 flag = 0 # flag becomes zero if any odd digit found
8 if flag == 1:
9 lst.append(str(i)) # i is stored in list as string
10
11print(",".join(lst))
OR
1def check(element):
2 return all(ord(i)%2 == 0 for i in element) # all returns True if all digits i is even in element
3
4lst = [str(i) for i in range(1000,3001)] # creates list of all given numbers with string data type
5lst = list(filter(check,lst)) # filter removes element from list if check condition fails
6print(",".join(lst))
OR
1lst = [str(i) for i in range(1000,3001)]
2lst = list(filter(lambda i:all(ord(j)%2 == 0 for j in i), lst)) # using lambda to define function inside filter function
3print(",".join(lst))
1'''Solution by: nikitaMogilev
2'''
3# map() digits of each number with lambda function and check if all() of them even
4# str(num) gives us opportunity to iterate through number by map() and join()
5print(','.join([str(num) for num in range(1000, 3001) if all(map(lambda num: int(num) % 2 == 0, str(num)))]))
Question 13
Question:
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
1hello world! 123
Then, the output should be:
1LETTERS 10
2DIGITS 3
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Main author's Solution: Python 2
1s = raw_input()
2d = {"DIGITS":0, "LETTERS":0}
3for c in s:
4 if c.isdigit():
5 d["DIGITS"]+=1
6 elif c.isalpha():
7 d["LETTERS"]+=1
8 else:
9 pass
10print "LETTERS", d["LETTERS"]
11print "DIGITS", d["DIGITS"]
My Solution: Python 3
1word = input()
2letter,digit = 0,0
3
4for i in word:
5 if ('a'<=i and i<='z') or ('A'<=i and i<='Z'):
6 letter+=1
7 if '0'<=i and i<='9':
8 digit+=1
9
10print("LETTERS {0}\nDIGITS {1}".format(letter,digit))
OR
1word = input()
2letter, digit = 0,0
3
4for i in word:
5 if i.isalpha(): # returns True if alphabet
6 letter += 1
7 elif i.isnumeric(): # returns True if numeric
8 digit += 1
9print(f"LETTERS {letter}\n{digits}") # two different types of formating method is shown in both solution
1''' Solution by: popomaticbubble
2'''
3import re
4
5input_string = input('> ')
6print()
7counter = {"LETTERS":len(re.findall("[a-zA-Z]", input_string)), "NUMBERS":len(re.findall("[0-9]", input_string))}
8
9print(counter)
Conclusion
All the above problems are mostly string related problems. Major parts of the solution includes string releted functions and comprehension method to write down the code in more shorter form.