My code works but sometimes gets into an infinite loop - python

So i got an assignment from school that the code should pick a string, remove the first and the last index, then randomize the middle letters and give back the string with the first and the last index again attached. The word should be at least 4 characters long and schould not give back the original string. It is warking and all, but it after a few attempts at giving a 4 letter word gets into an infinite loop and I can't figure out why. It's a python code. Thank you for your help. Also some variables are in my laguage which shouldn't be a problem...just to clarify the weird variable names.
import random
n=0
while n<4:
slovo=input('Zadajte vase slovo: ')
n=len(slovo)
l=[]
def shufle(slovo,l):
for i in range(len(slovo)):
if i==0:
continue
if i==len(slovo)-1:
continue
else:
l.append(slovo[i])
random.shuffle(l)
while True:
shufle(slovo,l)
s=slovo[0]
for i in l:
s+=i
s+=slovo[-1]
if s==slovo:
continue
elif len(s)!=len(slovo):
continue
else:
print(s)
break

Here's a tip: if your function is always expecting the same input for one of its parameters, than that parameter is probably not necessary. This is the case with passing empty lists or similar objects to functions. There was also a check if s and slovo are the same size which is not needed so I removed it. Try this:
import random
n=0
while n<4:
slovo=input('Zadajte vase slovo: ')
n=len(slovo)
def shufle(slovo):
l = []
for i in range(len(slovo)):
if i == 0:
continue
if i == len(slovo)-1:
continue
else:
l.append(slovo[i])
random.shuffle(l)
return l
while True:
l = shufle(slovo)
s = slovo[0]
for i in l:
s += i
s += slovo[-1]
if s == slovo:
continue
else:
print(s)
break

Related

Take some inputs until 0 encountered, print each word in lowercase and break the loop

Write a program to input the lines of text, print them to the screen after converting them to lowercase. The last line prints the number of input lines.
The program stops when it encounters a line with only zero.
Requirements: use infinite loop and break . statement
here's my code but it's saying Input 9 is empty
a = 1
l = 0
while a != 0:
a = input()
a.lower()
print(a)
l+=1
example inputs
TbH
Rn
ngL
bRb
0
I'd suggest this, it's a combination of these 2 comments, sorry
count = 0
while True:
a = input()
if a == '0':
break
else:
print(a.lower())
count += 1
print(count)
This may accomplish what you are trying to achieve:
def infinite_loop():
while True:
user_input = input('enter a value:\n> ')
if user_input == '0':
break
else:
print(user_input.lower())
if __name__ == '__main__':
infinite_loop()
There a few errors in your original code, here is some suggestions and fixes. This post is try to follow your code as much as it can, and point the changes needed.
Please see the comments and ask if you have any questions.
count = 0 # to count the lines
while w != '0': # input's string
w = input().strip() # get rid of \n space
word = w.lower() # convert to lower case
print(word)
count += 1
# while-loop stops once see '0'
Outputs: (while running)
ABBA
abba
Misssissippi
misssissippi
To-Do
to-do
0
0

Skipping iterations in a for loop when working with strings (in Python)

I'm trying to write a program that works with a string as input (a sentence or word). With a for loop, I iterate through each character in turn. When I come across the letter p, the program should skip a couple of iterations. I have found a lot of tips regarding skipping iterations when working with integers. However, in my code, I'm working with strings. Does anyone have any helpful tips for this? Thanks in advance!
Here is an adapted piece of my code (what I have so far):
language_input = input()
for character in language_input:
if character == "p":
# Now, I have to skip a few iterations (e.g. skip 3 characters)
It rather depends on what you need to do with the characters in your string. Here's an idea:
language_input = input()
i = 0
while i < len(language_input):
if language_input[i] == 'p':
i += 3
else:
i += 1
# do something else
You can use an extra variable and do nothing if it is set
language_input = input()
check = 0
for character in language_input:
if check:
check -= 1
continue
if character == "p":
check = 3 #set to number of iterations you want to skip
You could use an iterator:
language_input = 'abcdefghij'
s = iter(language_input)
while True:
try:
character = next(s)
if character == 'd':
print('…', end='')
next(s)
next(s)
next(s)
print(character, end='')
except StopIteration:
break
output: abc…dhij
To be more efficient in skipping many items, you could use itertools.islice:
from itertools import islice
# … only showing changed part of code
if character == 'd':
print('…', end='')
list(islice(s, 3)) # get 3 elements at once
# …

Why do these two pieces of code have different complexities?

Both of these pieces of code do the same thing, which is they check if the words in the list magazine_words are sufficient to make up the message dictated by the words in the list note_words . However the first piece of code takes a lot more time to execute, which doesn't let it run for large inputs. Why is that? Since both solutions use single for-loops, shouldn't they have the same complexity, i.e. take about the same time to run?
First solution:
lengths = input().split ()
m = int(lengths[0])
n = int(lengths [1])
magazine_words = input ().split()
note_words = input ().split()
def checkMagazine(m,n,magazine_words,note_words):
flag = "Yes"
for ind in range (n):
if not (note_words[ind] in magazine_words):
flag = "No"
break
else:
magazine_words.remove(note_words[ind])
return flag
print (checkMagazine(m,n,magazine_words,note_words))
Second solution:
def ransom_note(magazine, ransom):
rc = {} # dict of word: count of that word in the note
for word in ransom:
if word not in rc:
rc[word] = 0
rc[word] += 1
for word in magazine:
if word in rc:
rc[word] -= 1
if rc[word] == 0:
del rc[word]
if not rc:
return True
return False
m, n = map(int, input().strip().split(' '))
magazine = input().strip().split(' ')
ransom = input().strip().split(' ')
answer = ransom_note(magazine, ransom)
if(answer):
print("Yes")
else:
print("No")```
magazine_words.remove(note_words[ind]) is secretly another loop - this has to loop through all of magazine_words until it finds note_words[ind], each time you call it.

I wished to check if an input is in the string and then print the output

I intended to let the program check if the input matches with any character in a str and then print out the result, the player input and the underscores in the correct places. This is my test code so far:
astring = "apple"
bstring = "_ " * 5
print(bstring)
my_input = input("enter a letter")
for i, n in enumerate(astring):
if my_input == i:
bstring[n] = my_input
else:
i = i + 1
print(bstring)
However, only the underscores are being printed out. Can anyone help me?
In your loop, you should be checking to see if the letter at your current index of your string is the same as the letter at the current index of your input string, to do this you can use:
if i < len(my_input) and my_input[i] == n:
Also, strings in Python are immutable, and so you can't change them via index. Instead, use an array of _, so that you can change what is at a particular index. Then, at the end, join each element in your list by a space.
Lastly, there is no need to increment i, as this is done for you by your for loop:
astring='apple'
bstring=['_']*len(astring)
print(bstring)
my_input = input('enter a letter')
for i,n in enumerate(astring):
if i < len(my_input) and my_input[i] == n:
bstring[i] = n
print(' '.join(bstring))
for i,n in enumerate(astring):
'i' is the index, 'n' is the character. You have it the other way around in 'if'.
hope it will help you
astring='apple'
bstring=["_" for i in range(len(astring))]
print(bstring)
my_input=input('enter a letter')
for i,n in enumerate(astring):
if my_input==n:
bstring[i]=my_input
else:
i=i+1
print(*bstring)

Loop Issue with Local Variable

I'm using Python (3.x) to create a simple program for an assignment. It takes a multiline input, and if there is more than one consecutive whitespace it strips them out and replaces it with one whitespace. [That's the easy part.] It must also print the value of the most consecutive whitespaces in the entire input.
Example:
input = ("This is the input.")
Should print:
This is the input.
3
My code is below:
def blanks():
#this function works wonderfully!
all_line_max= []
while True:
try:
strline= input()
if len(strline)>0:
z= (maxspaces(strline))
all_line_max.append(z)
y= ' '.join(strline.split())
print(y)
print(z)
if strline =='END':
break
except:
break
print(all_line_max)
def maxspaces(x):
y= list(x)
count = 0
#this is the number of consecutive spaces we've found so far
counts=[]
for character in y:
count_max= 0
if character == ' ':
count= count + 1
if count > count_max:
count_max = count
counts.append(count_max)
else:
count = 0
return(max(counts))
blanks()
I understand that this is probably horribly inefficient, but it seems to almost work. My issue is this: I would like to, once the loop is finished appending to all_lines_max, print the largest value of that list. However, there doesn't seem to be a way to print the max of that list without doing it on every line, if that makes sense. Any ideas on my convoluted code?
Just print the max of all_line_max, right where you currently print the whole list:
print(max(all_line_max))
but leave it at the top level (so dedent once):
def blanks():
all_line_max = []
while True:
try:
strline = input()
if strline:
z = maxspaces(strline)
all_line_max.append(z)
y = ' '.join(strline.split())
print(y)
if strline == 'END':
break
except Exception:
break
print(max(all_line_max))
and remove the print(z) call, which prints the maximum whitespace count per line.
Your maxspaces() function adds count_max to your counts list each time a space is found; not the most efficient method. You don't even need to keep a list there; count_max needs to be moved out of the loop and will then correctly reflect the maximum space count. You also don't have to turn the sentence into a list, you can directly loop over a string:
def maxspaces(x):
max_count = count = 0
for character in x:
if character == ' ':
count += 1
if count > max_count:
max_count = count
else:
count = 0
return max_count

Categories