I'm trying to solve a problem at codewars using python - python

So the problem I have is I think that the code is good, but it doesn't work as I would like it to.
Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...
Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"]
The code I wrote:
def friend(x):
for x in friend:
split_words = x.split( )
word_count = len(split_words):
if word_count = 4:
print(x)
Thanks in advance!

Iterate over the list of names.
Check each name's length: Using the helper function is_friend.
Collect the name if it is a friend in a list.
Print the resulting list.
Input = ["Ryan", "Kieran", "Jason", "Yous"]
def is_friend(name):
return len(name) == 4
friends = []
for name in Input:
if is_friend(name):
friends.append(name)
print(friends)
Or a shorter version using list comprehension:
friends = [name for name in Input if len(name) == 4]
print(friends)

Related

Why isn't my alternate string replacement method working?

I got a working solution to this question with my second attempt. But I'm wondering why the first option doesn't work as well.
The question is:
Complete the function to replace the word test with cat and print the new string
my code (working solution):
def replaceTest(mystring):
answer = mystring.replace("test", "cat")
print(answer)
replaceTest('This is a test')
# output:
# This is a cat
my code (solution that doesn't work):
def replaceTest(mystring):
stringSplit = mystring.split()
for i in stringSplit:
if i == 'test':
i = 'cat'
answer = " ".join(stringSplit)
print(answer)
print(replaceTest('This is a test'))
# output:
# This is a test
# None
I can't see why it doesn't work. I think I'm iterating over each item in the list and saying if that item is test, make it cat instead. And then making the list into a string. Where did i go wrong?
With i = 'cat' you are just assigning to the loop variable, which is then discarded. You need to assign to the original strinSplit list (stringSplit[i] = 'cat') where by i is the index of stringSplit, obtained from enumerate:
def replaceTest(mystring):
stringSplit = mystring.split()
for i, word in enumerate(stringSplit):
if word == 'test':
stringSplit[i] = 'cat'
answer = " ".join(stringSplit)
print(answer)
replaceTest('This is a test')
Some improvements while still using your original logic: Having an index in a loop used to access list elements is awkward and error-prone. In this case (and many others) you can avoid it using a list comprehension instead. Also, I assume you wouldn't really want to print inside the function but instead return the modified string so you can use it further:
def replaceTest(mystring):
string_split_replace = ["cat" if word == "test" else word
for word in mystring.split()]
return " ".join(string_split_replace)
print(replaceTest('This is a test'))

Python for loop with input using append( )

beatles = []
print(beatles)
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print(beatles)'
for i in range(len(beatles):
beatles.append("Stu Sutcliffe")
beatles.append("Pete Best")
Need help with the for loop using append()
I'm Honestly not too sure what your asking for but to my understanding your looking for a way to add to a list using input then try this out for size.
You can replace list() with [] if you desire
beatles = list()
while True:
inp = input("Add Name to list ")
if inp == 'done' : break
beatles.append(inp)
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print(beatles)

Best method to match words between a list and a dictionary, returning only the ones that are unique for a key without the use of modules

I'm writing this script where archive contains the words that a person has said and their age, and clues are sentences where some words are extracted to match with the most likely person that said them. Words that work as a clue are marked with a * and all clues should be uniquely used by a person.
from typing import List, Dict, TextIO, Tuple
def who_did_it(archive: Dict[str, List[tuple]], clues: str) -> str:
word_list = []
#contains person and a list of its words in a list
clean_clue = get_words(clues)
#get_words: extract the clues clean into a list without the `*`
suspect = []
#a list for the most likely person that did it
dict_list = {}
#person as key, a list of words as values
for people in archive:
clues = archive.get(people)
word_list.append([people, get_words(clues[0])])
clean_clue.sort()
for person, words in word_list:
dict_list.setdefault(person, words)
numb = 0
for names in dict_list:
for clues in clean_clue:
if clues in dict_list.get(names):
numb = numb + 1
elif tags not in dict_list.get(names):
numb = numb - 1
if numb == 1:
suspect.append(names)
counter = 0
if len(suspect) == 1:
print(suspect[0])
else:
print('need more evidence')
The problem comes when I use my test cases, some of them doesn't seem to work because of the way I'm doing it, is there any other way to compare this values? How can I compare this values in an efficient way without using modules?
You are better off using a dict with keys that are your clues/weapons and sets of names as values:
def who(things,clues):
""" Returns a sorted list of (name, [clues,...]) tuples, sorted by longest len first"""
result = {}
for t in things:
for name in clues[t]:
result.setdefault(name,[])
result[name].append(t)
return sorted(result.items(), key=lambda x:-len(x[1]))
clues = { "knife":{"Joe","Phil"}, "club":{"Jane","John"}, "ice":{"Joe","Neffe"}}
print(who({"knife","ice"}, clues))
Output:
[('Joe', ['knife', 'ice']), ('Phil', ['knife']), ('Neffe', ['ice'])]
The reason the other way round is better: you are looking for the clues - which should be the keys.
Your logic is mixed up with the parsing which is not a very good thing. If you separate them things are much easier to understand.
from typing import List, Dict
def get_words(sentence: str) -> List:
return [word[1:] for word in sentence.split() if word.startswith('*')]
def who_did_it(archive: Dict[str, List[str]], clues: List[str]) -> str:
suspect = []
#a list for the most likely person that did it
for name, belongings in archive.items():
if all(clue in belongings for clue in clues):
suspect.append(name)
if len(suspect) == 1:
print(suspect[0])
else:
print('need more evidence')
facts = {
'martin': ('I had a knife and a *broom', 22),
'jose': ('I had a *knife', 21),
}
archive = { name : get_words(fact[0]) for name, fact in facts.items()}
who_did_it(archive, get_words('he had a *knife'))

Recursively generate combinations with Python

I am trying to provide a recursive method that provides a list of all the possible combinations when given a list of courses. E.g course = [Entree, Dessert]
This is what I have so far:
Entree = ["pumkinsoup","antipasto"]
Dessert = ["cheesecake", "icecream", "tiramisu", "cheeseplatter"]
courses = [Entree, Dessert]
def make_orders(courses):
dishes_so_far = []
recursive_make_orders(dishes_so_far, courses)
def recursive_make_orders(dishes_so_far, courses):
n = len(courses)
if n==0 :
print(dishes_so_far)
else:
current_courses = courses[0]
for D in current_courses:
dishes_so_far.append(D)
recursive_make_orders(dishes_so_far , courses[1:len(courses)])
\I am trying to make it so that it prints out the combination like [[pumkinsoup,cheesecake],[punkinsoup, icecream]] and etc but its actually giving me [pumkinsoup, cheesecake, icecream] and so on.
Tried adding it with addition instead of append and it gave me an error.
This is homework, so a recursive method is required.
You're not too far off - use itertools.product and *courses to unpack to it:
from itertools import product
for course in product(*courses):
print course
('pumkinsoup', 'cheesecake')
('pumkinsoup', 'icecream')
('pumkinsoup', 'tiramisu')
('pumkinsoup', 'cheeseplatter')
('antipasto', 'cheesecake')
('antipasto', 'icecream')
('antipasto', 'tiramisu')
('antipasto', 'cheeseplatter')
If you want recursive version, you can do something like this:
def worker(entree, dessert):
d = []
if not entree or not dessert: return d
d.append((entree[0], dessert[0]))
d += worker(entree[1:], dessert)
d += worker(entree, dessert[1:])
return d
Your version is not working as you said because courses now a list of lists, and courses[0] is just Entree, so you recursively constructiong new list from Entree.

Python print parameter inside []

can you help me with python parameters. i have problem with string #4. thank you
output is list[2]
but i need BMW
list = ["Ford", "Volvo", "BMW"]
x = len(list)
a = x - 1
car = 'list[%s]' % a
print car
It's simple. you have to do only car = list[a] which will give you 'BMW'.
myList = ["Ford", "Volvo", "BMW"]
x = len(myList)
a = x - 1
car = myList[a]
print(car) # 'BMW'
I have renamed the variable name. While you are giving variable name just careful about the predefined/built in keywords because its not good approach to give variable/function name same as built in types as it masks the builtin type name.
At first, don't use list as a variable, list is a keyword in python. Try some other name. And you are now printing the value of a which is an index not an element of the list. You have to use list[a] to print an element of a list positioned at index a.

Categories