Here is the code I have:
def generate(x)
two = {}
for x in range(1,7315):
two.update({vowels[random.randint(0,4)] + alpha[random.randint(0,21)]:0})
return two
generate(x)
this only returns a single value, how could I make it return multiple values?
return a tuple with your values
def returnTwoNumbers():
return (1, 0)
print(returnTwoNumbers()[0])
print(returnTwoNumbers()[1])
#output:
#1
#0
It also looks like you're trying to get a random vowel from your list of vowels. Using random.choice is a much more readable way to get a random item from a list:
import random
vowelList = ['a', 'e', 'i', 'o', 'u']
print (random.choice(vowelList))
You can use a tuple to return multiple values from a function e.g.:
return (one, two, three)
You have wrong indentation
def generate():
two = {}
for x in range(1,7315):
two.update({vowels[random.randint(0,4)] + alpha[random.randint(0,21)]:0})
return two
twos = generate()
Related
I am making a program that has two lists (in Python), and each list contains 5 different letters. How do I make it so that any index number I choose for both lists gets compared and uppercase a letter if the condition is true? If the first two values in the list are the same (in my case a lowercase letter), then I want the letter in the second list to become uppercase.
example/attempt (I don't know what I'm doing):
if list1[0] = list2[0]:
upper(list2[0])
Without an example of you input and output, it's difficult to understand what your goal is, but if your goal is to use .upper() on any string in list2 where list1[i] and list2[i] are equal, you can use a combination of zip and enumerate to compare, and then assign the value of list2[i] to the uppercase string like so:
list1 = ['a', 'b', 'c']
list2 = ['a', 'p', 'q']
for i, (x, y) in enumerate(zip(list1, list2)):
if x == y:
list2[i] = y.upper()
print(list2)
Output:
['A', 'p', 'q']
I think you could use something like this:
def compare_and_upper(lst1, lst2):
for i in range(len(lst1)):
if lst1[i].upper() == lst2[i].upper():
return lst1[i].upper()
return None
This is not a full solution of your problem, more of a representation of how to do the comparisons, which you can then reuse / modify to do the solution you want in the end.
import string
from random import choices
def create_random_string(str_len=10):
# k = the number of letters that we want it to return.
return "".join(choices(string.ascii_lowercase, k=str_len))
def compare(str_len=10):
# Create the two strings that we want to compare
first_string = create_random_string(str_len)
second_string = create_random_string(str_len)
# comp_string will hold the final string that we want to return.
comp_string = ""
# Because the length of the strings are based on the variable str_len,
# we can use the range of that number to iterate over our comparisions.
for i in range(str_len):
# Compares the i'th position of the strings
# If they match, then add the uppercase version to comp_string
if first_string[i] == second_string[i]:
comp_string += first_string[i].upper()
else:
comp_string += "-"
return comp_string
for _ in range(10):
print(compare(20))
Sample output:
--------------------
---AS---D---------D-
----W--Q--------E---
--------------------
-----------------E--
------T-------------
--------------------
-------------P------
-----S--------------
--B-----------------
How would you make a list of all the possible substrings in a string using recursion? (no loops) I know that you can recurse using s[1:] to cut off the first position and s[:-1] to cut off the last position. So far I have come up with this:
def lst_substrings(s):
lst = []
if s == "":
return lst
else:
lst.append(s)
return lst_substrings(s[1:])
but this would only make a list of all the substrings that are sliced by the first position if it worked
Fun problem, here's my solution - feedback appreciated.
Output
In [73]: lstSubStrings("Hey")
Out[73]: ['', 'y', 'H', 'Hey', 'He', 'e', 'ey']
Solution
def lstSubStrings(s):
# BASE CASE: when s is empty return the empty string
if(len(s) is 0):
return [s]
substrs = []
# a string is a substring of itself - by the definition of subset in math
substrs.append(s)
# extend the list of substrings by all substrings with the first
# character cut out
substrs.extend(lstSubStrings(s[1:]))
# extend the list of substrings by all substrings with the last
# character cut out
substrs.extend(lstSubStrings(s[:-1]))
# convert the list to `set`, removing all duplicates, and convert
# back to a list
substrs = list(set(substrs))
return substrs
EDIT: Duh. Just realized now that practically the same solution has been posted by someone who was quicker than me. Vote for his answer. I'll leave this as it is a bit more concise and in case you want to sort the resulting list by substring length. Use len(item, item), i.e. leave the - sign, to sort in ascending order.
This will do:
def lst_substrings(s):
lst = [s]
if len(s) > 0:
lst.extend(lst_substrings(s[1:]))
lst.extend(lst_substrings(s[:-1]))
return list(set(lst))
sub = lst_substrings("boby")
sub.sort(key=lambda item: (-len(item), item))
print(sub)
Output is:
['boby', 'bob', 'oby', 'bo', 'by', 'ob', 'b', 'o', 'y', '']
I have to make a program that calls a function and searches for all the anagrams of the string from a file, returning a list of the words.
I made everything and it should work, but when I start it it gives me None. I even tried words that are in the file and it is the same.
def find_anagrams_in_wordlist(str, str_list):
str_list = get_dictionary_wordlist()
for int in range (0, len(str)):
anagram(str, str_list[int])
if anagram(str, str_list[int]):
return(str_list[int])
def find_anagrams(str):
str_list = get_dictionary_wordlist()
return find_anagrams_in_wordlist(str, str_list)
def test_find_anagrams():
print(find_anagrams("tenato"))
And this is my anagram() function:
def anagram(str1, str2):
str1_list = list(str1)
str1_list.sort()
str2_list = list(str2)
str2_list.sort()
return (str1_list == str2_list)
And this is my get_dictionary_wordlist() function:
def get_dictionary_wordlist():
text_file = open("dictionary.txt", "r")
return text_file.read().splitlines()
What should I change to make it work?
OK, first guess; this code:
def find_anagrams_in_wordlist(str, str_list):
str_list = get_dictionary_wordlist()
for int in range (0, len(str)):
anagram(str, str_list[int])
if anagram(str, str_list[int]):
return(str_list[int])
is working with range(0, len(str)) - the number of characters in 'tenato' - instead of range(0, len(str_list)) - the number of words in the dictionary.
This means you only test the first few dictionary words, and ignore the rest. Try it as:
def find_anagrams_in_wordlist(str, str_list):
str_list = get_dictionary_wordlist()
for word in str_list:
if anagram(str, word):
return word
(there's no need to count through lists in Python using range(), you can for item in mylist: directly).
NB. if this works, your design will still only return the first word which matches, not a list of words which match. You would need to build up a list of matches, and then return the list after the loop completes.
Lets examine what you have:
def find_anagrams_in_wordlist(str, str_list): # You shouldn't name something 'str' because it's a type.
str_list = get_dictionary_wordlist() # You are overwriting your incoming list with the same function call.
for int in range (0, len(str)): # You're executing your for loop once per letter in the candidate word.
anagram(str, str_list[int]) # This function executes but isn't doing anything
if anagram(str, str_list[int]):
return(str_list[int]) # If you find something you are exiting your for loop AND your function
def anagram(str1, str2):
str1_list = list(str1)
str1_list.sort() # The result of this is the same every time... and it's None
str2_list = list(str2)
str2_list.sort() # Always returns None
return (str1_list == str2_list) # This is the only real work being done here.
Finally, you are not actually accumulating your results:
def find_anagrams_in_wordlist(candidate, word_list): # Name your variables clearly
results = list() # For accumulating your results
sorted_candidate = sorted(candidate) # You only need to sort your candidate once
for word in word_list: # This is the cleanest way to loop through an iterable
sorted_word = sorted(word) # Sort the word once
if sorted_candidate == sorted_word: # Now check for equality: an additional function can obfuscate things
results.append(word) # If it's equal, add it to your results
return results # Send back your results
We can test it like so, in the REPL:
>>> lst = {"cat", "dog", "fish", "god"}
>>> find_anagrams_in_wordlist("odg", lst)
['god', 'dog']
>>> find_anagrams_in_wordlist("cat", lst)
['cat']
>>> find_anagrams_in_wordlist("shif", lst)
['fish']
>>> find_anagrams_in_wordlist("birds", lst)
[]
Note that in my solution I am using sorted not sort(). sort() won't accomplish the correct thing:
>>> x = "moonshot"
>>> y = list(x)
>>> y
['m', 'o', 'o', 'n', 's', 'h', 'o', 't']
>>> z = y.sort()
>>> z
>>> type(z)
<type 'NoneType'>
>>> sorted(x)
['h', 'm', 'n', 'o', 'o', 'o', 's', 't']
Given a list
a=['g','d','r','x','s','g','d','r']
I want to count for example the occurrence of gdr, so I would apply some function
a.function('g','d','r') and return 2 to me (because gdr occurred 2 times).
If they are only strings in the list, you can join them in a long string and use its count method:
>>> a=['g','d','r','x','s','g','d','r']
>>> ''.join(a).count('gdr')
2
If you have a mix of strings and numbers for example, you may use map(str,a) before joining and the method would still work:
>>> a=[1,13,4,2,1,13,4]
>>> ''.join(map(str,a)).count('1134')
2
If you need all this packed in a function, you can have something like this:
def count_pattern(lst, *pattern):
return ''.join(l).count(''.join(pattern))
And will be able to call it: count_pattern(a, 'g', 'd', 'r') or count_pattern(a, 'gdr') or even count_pattern(a, 'gd', 'r').
You can do that as:
def get_occur(list, seq):
return ''.join(list).count(''.join(seq))
>>> get_occur(['a', 's', 'a', 's'], ['a', 's'])
2
If you are passing in strings, you can do:
return your_string.count(pattern)
What about:
>>> a=['g','d','r','x','s','g','d','r']
>>> print "".join(a).count("gdr")
2
Question: DO NOT USE SETS IN YOUR FUNCTION: Uses lists to return a list of the common letters in the first and last names (the intersection) Prompt user for first and last name and call the function with the first and last names as arguments and print the returned list.
I can't figure out why my program is just printing "No matches" even if there are letter matches. Anything helps! Thanks a bunch!
Code so far:
import string
def getCommonLetters(text1, text2):
""" Take two strings and return a list of letters common to
both strings."""
text1List = text1.split()
text2List = text2.split()
for i in range(0, len(text1List)):
text1List[i] = getCleanText(text1List[i])
for i in range(0, len(text2List)):
text2List[i] = getCleanText(text2List[i])
outList = []
for letter in text1List:
if letter in text2List and letter not in outList:
outList.append(letter)
return outList
def getCleanText(text):
"""Return letter in lower case stripped of whitespace and
punctuation characters"""
text = text.lower()
badCharacters = string.whitespace + string.punctuation
for character in badCharacters:
text = text.replace(character, "")
return text
userText1 = raw_input("Enter your first name: ")
userText2 = raw_input("Enter your last name: ")
result = getCommonLetters(userText1, userText2)
numMatches = len(result)
if numMatches == 0:
print "No matches."
else:
print "Number of matches:", numMatches
for letter in result:
print letter
Try this:
def CommonLetters(s1, s2):
l1=list(''.join(s1.split()))
l2=list(''.join(s2.split()))
return [x for x in l1 if x in l2]
print CommonLetters('Tom','Dom de Tommaso')
Output:
>>> ['T', 'o', 'm']
for letter in text1List:
Here's your problem. text1List is a list, not a string. You iterate on a list of strings (['Bobby', 'Tables'] for instance) and you check if 'Bobby' is in the list text2List.
You want to iterate on every character of your string text1 and check if it is present in the string text2.
There's a few non-pythonic idioms in your code, but you'll learn that in time.
Follow-up: What happens if I type my first name in lowercase and my last name in uppercase? Will your code find any match?
Prior to set() being the common idiom for duplicate removal in Python 2.5, you could use the conversion of a list to a dictionary to remove duplicates.
Here is an example:
def CommonLetters(s1, s2):
d={}
for l in s1:
if l in s2 and l.isalpha():
d[l]=d.get(l,0)+1
return d
print CommonLetters('matteo', 'dom de tommaso')
This prints the count of the common letters like so:
{'a': 1, 'e': 1, 'm': 1, 't': 2, 'o': 1}
If you want to have a list of those common letters, just use the keys() method of the dictionary:
print CommonLetters('matteo', 'dom de tommaso').keys()
Which prints just the keys:
['a', 'e', 'm', 't', 'o']
If you want upper and lower case letters to match, add the logic to this line:
if l in s2 and l.isalpha():