I did this code:
import itertools
black = "Ellie"
s = "E111e"
messagelist = list(s)
a = s.count("1")
dicta = {}
for x in messagelist:
if not x == "1":
dicta[x] = messagelist.index(x)
print(dicta)
listo = ['l', 'i', 'j',]
result = itertools.combinations_with_replacement(listo, a)
lista2 = []
for each in result:
a =str(each).replace("(", "")
a = a.replace(")", "")
a = a.replace(",", "")
a = a.replace("'", "")
a = a.replace(" ", "")
lista2.append(a)
lista3 = []
for x in lista2:
listexa = list(x)
for item in dicta:
listexa.insert(dicta[item], item)
listexa = "".join(listexa)
lista3.append(listexa)
print(lista3)
if black in lista3:
print("DELETE")
else:
print("IT'S OKAY")
black = blacklisted word
s = user writing it with numbers
The problem is with words that contains more than one egual character like "finishing" that has 2 "n" characters, so in the dict, only 1 "n" will be added how can I solve this?
This will do the trick for you:
(I also tweaked the for loop, where you were iterating over combinations - just to keep it pythonish ;) )
import itertools
def repl(txt, pat):
if(len(pat)==0):
return txt
return repl(txt.replace("1", pat[0], 1), pat[1:])
black = "Ellie"
s = "E111e"
messagelist = list(s)
a = s.count("1")
dicta = {}
listo = ['l', 'i', 'j',]
result = itertools.combinations_with_replacement(listo, a)
lista2 = []
for each in result:
lista2.append("".join(each))
lista3 = []
for x in lista2:
listexa = repl(s, x)
lista3.append(listexa)
print(lista3)
if black in lista3:
print("DELETE")
else:
print("IT'S OKAY")
Consider function repl - the most important improvement. It essentially leverages the fact that python str.replace() can also take 3rd argument, which in essence defines number of replacements to be done - just to replace 1 one at a time.
Related
How to compare the value in a string list with another value in a string list and if I do succeed in comparing with 2 of the lists, how can I store a new value in a new list if the value in the string lists is matches?
def start_game():
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
random_food_list = [random.choices (food_list, k = 4)]
player_guess_list = []
correct_guess_list = []
for i in range(1,5):
player_guess = input("food" + str(i) + ":").lower()
if player_guess not in food_list:
print("Invalid foods, Restart Again")
start_game()
else:
player_guess_list.append(player_guess)
print(player_guess_list) # For review
print(random_food_list) # For review
For example:
User input list = [salad, steak, noodles, rice]
randomized list = [salad, rice, salad, rice]
correct_guess_list = [O,X,X,O]
Output
Correct food in correct place: 2
Correct food in wrong place: 2
You can do what you by using a single list comprehension of the values in the two list zipped together.
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
#random_food_list = random.choices(food_list, k = 4)
random_food_list = ['salad', 'rice', 'salad', 'rice'] # Hardcode for testing.
correct_guess_list = ['O' if f1.lower() == f2.lower() else 'X'
for f1, f2 in zip(food_list, random_food_list)]
print(correct_guess_list) # -> ['O', 'X', 'X', 'O']
correct_food_in_correct_place = correct_guess_list.count('O')
correct_food_in_wrong_place = correct_guess_list.count('X')
print(f'Correct food in correct place: {correct_food_in_correct_place}') # -> 2
print(f'Correct food in wrong place: {correct_food_in_wrong_place}') # -> 2
The question is quite unclear. The example looks like you want to compare two lists and create a third list that stores where the first two lists are identical.
This can be done this way:
user_input_list = ["salad", "steak", "noodles", "rice"]
randomized_list = ["salad", "rice", "salad", "rice"]
new_list = list(map(lambda x, y : 'O' if x == y else 'X', \
user_input_list, \
randomized_list))
correct_food_in_correct_place = new_list.count('O')
correct_food_in_wrong_place = new_list.count('X')
print(new_list)
print(correct_food_in_correct_place)
print(correct_food_in_wrong_place)
Sorry, that is already quite heavy Python code. Not really easy for beginners. Try it out and you will see what it does. If this does not answer your question, please ask ask more concretely and try to isolate your problem a bit.
I made the correct guesses list using a list comprehension:
correct_guess_list = ["O " if random_food_list[player_guess_list.index(food)] == food else "X" for food in
player_guess_list]
Full code:
import random
def start_game():
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
random_food_list = random.choices(food_list, k=4)
player_guess_list = []
correct_guess_list = []
correct_guesses = 0
for i in range(1, 5):
player_guess = input("food" + str(i) + ":").lower()
if player_guess not in food_list:
print("Invalid foods, Restart Again")
start_game()
else:
player_guess_list.append(player_guess)
if player_guess_list[i-1] == random_food_list[i-1]:
correct_guesses += 1
print(player_guess_list) # For review
print(random_food_list) # For review
correct_guess_list = ["O " if random_food_list[player_guess_list.index(food)] == food else "X" for food in
player_guess_list]
print(correct_guess_list)
print(f"Food in correct place: {correct_guesses}")
print(f"Food in incorrect place: {4 - correct_guesses}")
start_game()
One problem I see in your anser is you are creating a list of list rather than list to compare with in the first place random.choices (food_list, k = 4) returns a list so no need to enclose it in square brackets. Now both the types will be list and you can use indexing to compare values from both list.
import random
def start_game():
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
random_food_list = random.choices (food_list, k = 4)
player_guess_list = []
correct_guess_list = []
for i in range(1,5):
player_guess = input("food" + str(i) + ":").lower()
if player_guess not in food_list:
print("Invadlid foods, Restart Again")
start_game()
else:
player_guess_list.append(player_guess)
print(player_guess_list) # For review
print(random_food_list) # For review
for i in range(0 , len(random_food_list)):
if random_food_list[i] == player_guess_list[i]:
correct_guess_list.append(random_food_list[i])
print(correct_guess_list)
start_game()
My Code:
alphabet = "abcdefghijklmnopqrstuvwxyz"
def sort3():
string = input("please enter a 3 character string: ")
string1 = string[0]
string2 = string[1]
string3 = string[2]
stringpos1 = alphabet.index(string1)
stringpos2 = alphabet.index(string2)
stringpos3 = alphabet.index(string3)
if stringpos3 > stringpos2 > stringpos1: # 123
print(string1 + string2 + string3)
elif stringpos2 > stringpos3 + stringpos1: # 132
print(string1 + string3 + string2)
elif stringpos3 > stringpos1 > stringpos2: # 213
print(string2 + string1 + string3)
elif stringpos1 > stringpos3 > stringpos2: # 231
print(string2 + string3 + string1)
elif stringpos2 > stringpos1 > stringpos3: # 312
print(string3 + string1 + string2)
elif stringpos1 > stringpos2 > stringpos3: # 321
print(string3 + string2 + string1)
sort3()
This is the way i did, i want to know how i can do this for any string (meaning any lengthen string)
Try this algorithm:
def sort(lst):
if not lst:
return []
return (sort([x for x in lst[1:] if x < lst[0]])
+ [lst[0]] +
sort([x for x in lst[1:] if x >= lst[0]]))
word=input('enter a word: ')
print(''.join(sort(word)))
Example Output:
enter a word: xzy
xyz
Works for any length, even:
enter a word: rcrfr sefre erg ergergerg r
ceeeeeeffggggrrrrrrrrrs
It will be hard to implement your code to any lengthen string
Btw, slow way:
from random import shuffle
l=list(input('enter a word: '))
def is_sorted(iterable):
for a1,a2 in zip(iterable, iterable[1:]):
if a1 > a2: return False
return True
sorted_list = l
while True:
shuffle(sorted_list)
if is_sorted(sorted_list): break
print(''.join(sorted_list))
First idea is to use a bubble sort implementation:
def bubbleSortStr(astr):
my_list = [x for x in my_str]
bubbleSort(my_list)
return ''.join(my_list)
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
my_str = "BubbleSort is cool"
print bubbleSortStr(my_str)
# BSbbceillooorstu
I took the code for the actual bubble sort from here: http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html This is a nice tutorial which explains one of the most basic sorting algorithms.
Since the bubble sort example only sorts lists, I had to convert the string into a list which is done in bubbleSortStr().
If we compare the ascii value, then sorting is easy.
Ex:
s = 'apple'
q = list(s)
['a', 'p', 'p', 'l', 'e']
Code will be :
for i in range(len(q)):
for j in range(i+1,len(q)):
if ord(q[i])>ord(q[j]):
q[i],q[j] = q[j],q[i]
print(q)
''.join(q)
I'm very new to Python and I have a question.
I have a List that looks like this:
List = ["B-Guild","I-Guild","I-Guild","L-Guild","B-Gene","L-Gene","U-Car"]
All of the words with B-(I)-L belong to each other and I want to use a function to show that.
def combine(x):
foo = []
regexp_B = ("B-" + r'.*')
regexp_I = ("I-" + r'.*')
regexp_L = ("L-" + r'.*')
regexp_U = ("U-" + r'.*')
for i in range(0,len(x),1):
if re.match(regexp_B, x[i]):
print("Found B")
foo.append[i+x[i]]
if re.match(regexp_I, x[i+1]):
print("Found I")
foo.append[i+1+x[i+1]]
if re.match(regexp_I, x[i+1]):
print("Found I")
foo.append[i+1+x[i+1]]
else:
print("Found L")
foo.append[i+1+x[i+1]]
else:
print("Found L")
foo.append[i1+x[i1]]
elif re.match(regexp_L, x[i]):
print("L")
foo.append[i1+x[i1]]
elif re.match(regexp_U, x[i]):
print("Found U")
foo.append[i1+x[i1]]
return foo
List_New = combine(List)
Desired Output:
foo = ["0B-Guild","0I-Guild","0I-Guild","OL-Guild","1B-Gene","1L-Gene","2U-Car"]
Edit:
The output follows this logic: Every time a "B-" prefix appears, the words to follow are part of one "theme" until a "L-" prefix appears. These words got to have the same number before them so they can be grouped for further functions. "U-" prefixes don't follow that logic and just need a number before them to distinguish them from the other words. Think of it as a Counter that groups these word into a cluster.
def combine(some_list):
current_group = 0 # starts with 0
g_size = 0 # current group size
for elem in some_list:
g_size += 1
if elem.startswith('U-') and g_size > 1:
g_size = 1
current_group += 1
yield '{}{}'.format(current_group, elem)
if elem.startswith(('L-', 'U-')): # each L- or U- also finishes a group
g_size = 0
current_group += 1
>>> List = ["B-Guild","I-Guild","I-Guild","L-Guild","B-Gene","L-Gene","U-Car"]
>>> print(list(combine(List)))
>>> List = ["B-Guild","I-Guild","I-Guild","L-Guild","B-Guild","L-Guild","U-Guild"]
>>> print(list(combine(List)))
I'm trying to insert delimiters into a string that was created by a previous function (ifw(in_list)). I'm not having any issues with \n or \t but once my code gets to "," join it breaks down. I've tried a few different solutions and looked through similar questions/answers on the site but I keep getting the TypeError: can only join an iterable. Any help you can provide me would be very apprciated.
#! /usr/bin/env python
import os
import sys
import re
delim = os.getenv("QWIKIFWLISTMGR_DELIMITER")
in_list = sys.argv
def delim(in_list):
x = "screw python"
x = os.getenv('QWIKIFWLISTMGR_DELIMITER')
if 'BLANK' in x:
x = ' '.join(ifw(in_list))
return x
elif 'TAB' in x:
x = ifw(in_list)
x = '\t'.join(x)
return x
elif 'NL' in x:
x = ifw(in_list)
x = '\n'.join(x)
return x
elif 'COMMA' in x:
x = ','.join(str(x) for x in (ifw(in_list)))
return
elif 'COLON' in x:
x = ifw(in_list)
x = ':'.join(x)
return x
elif 'SEMICOLON' in x:
x = ifw(in_list)
x = ';'.join(x)
return x
elif 'SLASH' in x:
x = ifw(in_list)
x = '/'.join(x)
return x
else:
x = ifw(in_list)
return
def ifw(in_list):
usr_choice = (in_list)[1]
if usr_choice == 'i':
print(int_sort(in_list))
elif usr_choice =='f':
print(float_sort(in_list))
elif usr_choice == 'w':
print(word_sort(in_list))
def float_sort(in_list):
float_sort = "test"
sorted_float = "test"
float_sort = in_list[2:]
float_sort = ''.join(float_sort)
#float_sort1 = " ".join(list((re.findall(r"((?<!\S)\d+(?!\S))", float_sort))))
#float_sort2 = ' '.join(list(re.findall(r"(\d+\.\d+)", float_sort)
float_sort = " ".join(re.findall(r"\d*\.\d+|\d+", float_sort))
sorted_float = sorted(float_sort, key=len)
return float_sort
#print (float_sort(in_list))
def word_sort(in_list):
word_sort = " 1a "
word_sort = sorted(in_list[2:], key=len) #in_list must be 2 because the program will view usr input as a word
for i in word_sort:
punctuation = '.',',',';','!',' / ','"','?' #strips punctuation from words
if i in punctuation: #removes punctuation
word_sort = word_sort.replace(i," ")
#word_sort= sorted(word_sort, key=lambda L: (L.lower(), L))
word_sort= " ".join(sorted(word_sort, key=lambda L: (L.lower(), L))) #takes string and sorts by length giving priority to upper over lower when tied
sorted_word = " 1a " #left for testing
sorted_word = re.sub("\S+\d\S+", "", word_sort).strip() #removes any word with a number in it
sorted_word = "".join(sorted_word) #joins the results back into a string
return sorted_word
def int_sort(in_list):
in_list = " ".join(in_list[1:]) # takes information from argv and creates a string with it
int_sort = " ".join(list(reversed(re.findall(r"(?<!\S)\d+(?!\S)", in_list))))
# find all looks for a pattern of anything but a space... any number. anything besides a space in the in_list and returns it
#reveresd flips that return backwards
# list turns that into a list and join makes it a string again
return int_sort
#print int_sort(in_list)
#print (delim(in_list))
Your ifw function has no return statement, so it returns None.
So the line:
x = ','.join(str(x) for x in (ifw(in_list)))
becomes
x = ','.join(str(x) for x in None)
and python can't iterate over None.
The following script is supposed to fetch a specific line number and parse it from a live website. It works for like 30 loops but then it seems like enumerate(f) stops working correctly... the "i" in the for loop seems to stop at line 130 instead of like 200 something. Could this be due to the website I'm trying to fetch data from or something else? Thanks!!
import sgmllib
class MyParser(sgmllib.SGMLParser):
"A simple parser class."
def parse(self, s):
"Parse the given string 's'."
self.feed(s)
self.close()
def __init__(self, verbose=0):
"Initialise an object, passing 'verbose' to the superclass."
sgmllib.SGMLParser.__init__(self, verbose)
self.divs = []
self.descriptions = []
self.inside_div_element = 0
def start_div(self, attributes):
"Process a hyperlink and its 'attributes'."
for name, value in attributes:
if name == "id":
self.divs.append(value)
self.inside_div_element = 1
def end_div(self):
"Record the end of a hyperlink."
self.inside_div_element = 0
def handle_data(self, data):
"Handle the textual 'data'."
if self.inside_div_element:
self.descriptions.append(data)
def get_div(self):
"Return the list of hyperlinks."
return self.divs
def get_descriptions(self, check):
"Return a list of descriptions."
if check == 1:
self.descriptions.pop(0)
return self.descriptions
def rm_descriptions(self):
"Remove all descriptions."
self.descriptions.pop()
import urllib
import linecache
import sgmllib
tempLine = ""
tempStr = " "
tempStr2 = ""
myparser = MyParser()
count = 0
user = ['']
oldUser = ['none']
oldoldUser = [' ']
array = [" ", 0]
index = 0
found = 0
k = 0
j = 0
posIndex = 0
a = 0
firstCheck = 0
fCheck = 0
while a < 1000:
print a
f = urllib.urlopen("SITE")
a = a+1
for i, line in enumerate(f):
if i == 187:
print i
tempLine = line
print line
myparser.parse(line)
if fCheck == 1:
result = oldUser[0] is oldUser[1]
u1 = oldUser[0]
u2 = oldUser[1]
tempStr = oldUser[1]
if u1 == u2:
result = 1
else:
result = user is oldUser
fCheck = 1
user = myparser.get_descriptions(firstCheck)
tempStr = user[0]
firstCheck = 1
if result:
array[index+1] = array[index+1] +0
else:
j = 0
for z in array:
k = j+2
tempStr2 = user[0]
if k < len(array) and tempStr2 == array[k]:
array[j+3] = array[j+3] + 1
index = j+2
found = 1
break
j = j+1
if found == 0:
array.append(tempStr)
array.append(0)
oldUser = user
found = 0
print array
elif i > 200:
print "HERE"
break
print array
f.close()
Perhaps the number of lines on that web page are fewer than you think? What does this give you?:
print max(i for i, _ in enumerate(urllib.urlopen("SITE")))
Aside: Your indentation is stuffed after the while a < 1000: line. Excessive empty lines and one-letter names don't assist the understanding of your code.
enumerate is not broken. Instead of such speculation, inspect your data. Suggestion: replace
for i, line in enumerate(f):
by
lines = list(f)
print "=== a=%d linecount=%d === % (a, len(lines))
for i, line in enumerate(lines):
print " a=%d i=%d line=%r" % (a, i, line)
Examine the output carefully.