This question already has answers here:
How to find elements that are common to all lists in a nested list?
(4 answers)
Closed 8 years ago.
t = input()
stringlist = []
setlist = []
for _ in range(t):
stringlist.append(raw_input())
print stringlist
for h in stringlist:
setlist.append((set(h)))
print setlist
print len((setlist[0] & setlist[1] & setlist[2]))
It's a simple program to find the number of common letters between the words that given as input. Note: This program only works for exactly 3 inputs. Can someone point me towards how I can generalize the last line of this code to allow for as many inputs as is supplied? I would appreciate it if you could just point me towards the answer and not actually give the answer.
So far Ive thought about using a join() to merge the input strings with the seperator being '&' and then put an eval() on the resulting string.
Just put all the input in a list then use map and set.intersection
l = ["foo", "boo", "foobar"]
common = set.intersection(*map(set,l))
print common
set(['o'])
Full code:
t = int(raw_input())
string_list = [raw_input() for _ in range(t)]
common = set.intersection(*map(set,string_list))
print(len(common))
Or cast the raw_input as a set if you don't need the list of words elsewhere:
string_list = [set(raw_input()) for _ in range(t)]
common = set.intersection(*string_list)
Related
This question already has answers here:
Python - Caesar Cipher
(3 answers)
Closed 2 years ago.
This is a codecademy challenge, i am trying to offset the letters in the input string in relation to the english alphabet. lets say if we enter d with an offset of 3 it should return a. What am i doing wrong ?
I am new to python i started 3 days ago because of the quarantine, love it so far.
import string
a = list(string.ascii_lowercase)
word = "assa"
i = ""
j= ""
x = 0
for j in a:
for i in word:
if i == j:
x = (int(a.index(j)) - 10)
z = str(a[x])
sol = word.replace(i,z)
print(sol)
#def cipher(word):
sol = word.replace(i,z)
Every time, this goes back to the original value of word, figures out the result of making the replacement, and gives the name sol to the result. For your general approach to work, you would need to rename the result as word.
When you do this, you should not loop over the characters in word. .replace(i, z) already replaces every appearance of i with z (since i == j, you could equivalently have used j). It is also a bad idea to modify the thing you are looping over.
However, there is a much most straightforward way to implement this entire solution, using str.translate and str.maketrans - see for example.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I am trying to take an input from a "raw_input" function and make it into 3 floats and then sum them up.
user_input = "1.23+2.25+3.25"
is it possible to take the 3 numbers and add them to a list of floats that look like this or something similar?
float_lst = [1.23,2.25,3.25]
Yes.
float_lst = [float(i) for i in user_input.split("+")]
If I only go by your requirement, not the list, you can eval. Trivial code example below
a = raw_input()
print eval(a)
You can use the split function and then cast the elements to float.
user_input = "1.23+2.25+3.25"
lst = user_input.split("+")
lst = [float(i) for i in lst]
Now you have a list of float so you can do
result = sum(lst)
And you will have the result
studying Python as crazy and have many many questions.
This time about function, i need to create 2 functions, first for numbers to sum up everything that user inputs in the list and second function, where user inputs some words in to the list and function without touching word indexes in the list, takes each word and returns reversed words (On the same index)
I can show you my code, i think i don't have problems with numbers and its function, i need your help with reverse function, i tried some ways, even one "for" in another, but i prefer some easy ways.
def sum(numbers):
acc = 0
for numb in numbers:
acc += numb
return acc
def rever(strings):
r = []
for i in strings:
for n in i:
reversed(r[n])
return r
numbers = [int(x) for x in input("Please input at least 5 numbers (Use space): ").split()]
print(sum(numbers))
strings = [str(x) for x in input("Please input at least 5 words (Use Space): ").split()]
print(rever(strings))
For your first function, that already exists as a built-in function of same name (sum()). For the second, you can use a simple list comprehension.
def rever(strings):
return [x[::-1] for x in strings]
Judging by your question it seems you are learning functions in python, you can reverse the list using a function like this:
strings_ = [str(x) for x in input("Please input at least 5 words (Use Space): ").split()]
for index,item in enumerate(strings_):
def recursion_reverse(string_1):
if not string_1:
return ""
else:
front_part=recursion_reverse(string_1[1:])
back_part=string_1[0]
return front_part+back_part[0]
strings_[index]=recursion_reverse(item)
print(strings_)
output:
Please input at least 5 words (Use Space): Hello world this is me
['olleH', 'dlrow', 'siht', 'si', 'em']
This question already has answers here:
Modifying list while iterating [duplicate]
(7 answers)
Closed 5 years ago.
Text = input('please enter your text')
l = [str(x) for x in Text.split()]
count = 0
for item in l:
for i in range(1,len(item)):
if item[i-1] == item[i]:
count +=1
if count <1:
l.remove(item)
count = 0
print (l)
the goal is : if we have a text : 'baaaaah mooh lpo mpoo' to get a list with elements they have 2 successive same characters, in this case ['baaaaah', 'mooh', 'mpoo' ]
the program is working with the mentioned example
if i use this one it's not working : 'hgj kio mpoo'
thank you
(complex)One liner:
>>> def successive_items(s):
return [x for x in s.split() if any(x[i]==x[i-1] for i in range(1,len(x)))]
>>> successive_items('baaaaah mooh lpo mpoo')
['baaaaah', 'mooh', 'mpoo']
>>> successive_items('hgj kio mpoo')
['mpoo']
In case of your code, you should not modify the list you are iterating over. Say, for example, lets have an array:
a = [1,2,3,4,5]
Now, if you iterate and remove elements (inside the loop), you would expect a to be empty. But let's check out:
>>> a = [1,2,3,4,5]
>>> for item in a:
a.remove(item)
>>> a
[2, 4]
See? It is not empty. This is better explained here.
Your program is not working for the second case because of list modification. Here is how:
Initially your list had ['hgj','kio','mpoo'].
After reading the first element you removed hgj. So the list now becomes ['kio','mpoo'].
The loop iterates the 2nd element next, and it gets mpoo (in the modified list);
kio was never read.
This might help:
sentence = input("please enter your text")
words = sentence.split()
answers = []
for each_word in words:
for idx in range(1, len(each_word)):
if each_word[idx] == each_word[idx-1]:
answers.append(each_word)
break
print(answers)
In your code, you are iterating over a list and at the same time you are modifying that very same list(by deleting elements from it), for more explanation see this answer
This question already has answers here:
How can I find all common letters in a set of strings?
(2 answers)
Closed 8 years ago.
I need to make a function that takes two string arguments and returns a string with only the characters that are in both of the argument strings. There should be no duplicate characters in the return value.
this is what I have but I need to make it print things only once if there is more then one
def letter(x,z):
for i in x:
for f in z:
if i == f:
s = str(i)
print(s)
If the order is not important, you can take the intersection & of the set of characters in each word, then join that set into a single string and return it.
def makeString(a, b):
return ''.join(set(a) & set(b))
>>> makeString('sentence', 'santa')
'nts'
Try this
s = set()
def letter(x,z):
for i in x:
for f in z:
if i == f:
s.add(i)
letter("hello","world")
print("".join(s))
It will print 'ol'
If sets aren't your bag for some reason (perhaps you want to maintain the order in one or other of the strings, try:
def common_letters(s1, s2):
unique_letters = []
for letter in s1:
if letter in s2 and letter not in unique_letters:
unique_letters.append(letter)
return ''.join(unique_letters)
print(common_letters('spam', 'arthuprs'))
(Assuming Python 3 for the print()).