Issue with pattern program using loops - python

I'm writing a program that takes two inputs, number of lines and number of cheers as input. The number of lines is how many lines the user wants to print out and the number of cheers are in the format that 1 cheer is the word "GO" and two cheers are two "GO" s ...and their is the word "BUDDY" within two neighboring GO's. And each new line has to be indented 3 spaces more then the one before. And this is the program I've come up with:
lines = input("Lines= ")
cheers = input("Cheers= ")
if cheers == 1:
i = 1
space = 0
S = ""
while i<=lines:
S=S+(" "*space)+"GO \n"
i += 1
space+=3
print S
else:
n = 1
cheer1 = "GO BUDDY "
cheer2 = "GO"
space = 0
while n<= cheers:
print (" "*space)+(cheer1*cheers)+cheer2
space+=3
n += 1
But the problem with this is that it doesn't print out the right number of GO's in the number of cheers. How can I modify my code to fix this problem? This is the output format I want to get :

Often in Python you don't need any loops
lines = int(input('Lines= '))
cheers = int(input('Cheers= '))
line = ' BUDDY '.join(['GO']*cheers)
for i in range(cheers):
print(' '*(i*3) + line)

def greet(lines, cheers):
i = 0
line_str = ""
while i < cheers: # Build the line string
i += 1
line_str += "GO" if i == cheers else "GO BUDDY "
i = 0
while i < lines: #Print each line
print(" "*(i*3) + line_str)
i += 1
greet(2,1)
greet(4,3)
greet(2,4)

Try this.
def greet(lines, cheers):
for i in range (lines):
output = (" ") * i + "Go"
for j in range (cheers):
if cheers == 1:
print output
break
output += "Budddy Go"
print output
Hope this helps.

Related

How to add new line after number of word

i find a code to seperate line, but it cut hafl of word "A very very long str" \n "ing from user input". so i want to ask how to keep the original word. its mean add \n after a number of word?
# inp = "A very very long string from user input"
# new_input = ""
# for i, letter in enumerate(inp):
# if i % 20 == 0:
# new_input += '\n'
# new_input += letter
#
# # this is just because at the beginning too a `\n` character gets added
# new_input = new_input[1:]
# print(new_input)
Using a simple loop on a list of the words:
inp = "A very very long string from user input"
start = 0
N = 3
l = inp.split()
for stop in range(N, len(l)+N, N):
print(' '.join(l[start:stop]))
start = stop
output:
A very very
long string from
user input
update: splitting with a max number of characters
If you need this, don't reinvent the wheel, use textwrap.wrap:
inp = "A very very long string from user input"
from textwrap import wrap
print('\n'.join(wrap(inp, width=20)))
output:
A very very long
string from user
input
I see that there is already an accepted answer, but I'm not sure that it completely answers the original question. The accepted answer will only split the string provided into lines with 3 words each. However, what I understand the question to be is for the string to be split into lines of a certain length (20 being the length provided). This function should work:
def split_str_into_lines(input_str: str, line_length: int):
words = input_str.split(" ")
line_count = 0
split_input = ""
for word in words:
line_count += 1
line_count += len(word)
if line_count > line_length:
split_input += "\n"
line_count = len(word) + 1
split_input += word
split_input += " "
else:
split_input += word
split_input += " "
return split_input
inp = "A very very long string from user input"
length = 20
new_input = split_str_into_lines(inp,length)
print(new_input)
new_input
Giving result:
"""
A very very long
string from user
input
"""
or
'A very very long \nstring from user \ninput '
Try using str.split() 1 and give it space as a delimiter:
words = inp.split(' ')
That should return a list of words

Issue with Caesar Cipher and while loops

I'm making this Caesar Cipher decoder and I want the program to print every single option (the 26 ways it could be shifted). However, when I run my code nothing shows, what was my error. If you know please tell me, I'm new to coding and in need of help.
import sys
import time
L2I = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26)))
I2L = dict(zip(range(26),"ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
msg = ("What is the intercepted message \n")
for character in msg:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.1)
msg_ans = input("> ")
msg_ans = msg_ans.strip()
shift = 0
def decipher(msg_ans,shift):
while shift < 26:
for i in msg_ans.upper():
if i.isalpha() == True :
msg_ans += I2L[ (L2I[i]+ shift)%26 ]
shift += 1
else:
msg_ans += i
shift += 1
print (msg_ans)
decipher(msg_ans,shift)
I expect it to output the 26 ways it can be shifted. However when I put the word 'Hello' I get 'HelloHFNOSMKSTXRQZBGWUCDHBAJLQLKTVAVVFIO' instead of 'IFMMP JGNNQ ...'
There are a couple of issues. First, you're incrementing shift every time you check a single character. In reality, you only want to increment it after each time you cycle completely through the message. You should also move the initialization into the function. There's no reason to pass shift in, since you're just trying all 26 possibilities in order.
def decipher(msg_ans):
shift = 0
while shift < 26:
for i in msg_ans.upper():
if i.isalpha() == True :
msg_ans += I2L[ (L2I[i]+ shift)%26 ]
else:
msg_ans += i
shift += 1
print (msg_ans)
At this point, though, there's no reason to use a while loop instead of a for:
def decipher(msg_ans):
for shift in range(26):
for i in msg_ans.upper():
if i.isalpha() == True :
msg_ans += I2L[ (L2I[i]+ shift)%26 ]
else:
msg_ans += i
print (msg_ans)
The other issue is that you're just appending the new characters to the end of your input string. You don't specify what form you actually want it in, so let's say you want it in a list of strings. You'll need to initialize the list, build a temporary string on each iteration, and then append the temporary string to the list:
def decipher(msg_ans):
possible_messages = []
for shift in range(26):
decoded_msg = ''
for i in msg_ans.upper():
if i.isalpha() == True :
decoded_msg += I2L[ (L2I[i]+ shift)%26 ]
else:
decoded_msg += i
possible_messages.append(decoded_msg)
return possible_messages
Then just print the result of your invocation of the function:
print(decipher(msg_ans))
msg should be like this
msg = "What is the intercepted message \n"
Also you probably want to print instead of return here
return msg_ans

If-else statement not functioning properly in for loop

I'm trying to count the different characters in two individual strings using an if-else statement in a for-loop. However, it never counts the different characters.
for char in range(len(f1CurrentLine)): # Compare line by line
if f1CurrentLine[char] != f2CurrentLine[char]: # If the lines have different characters
print("Unmatched characters: ", count, ":", char)
diffCharCount = diffCharCount + 1 # add 1 to the difference counter
count = count + 1
text1Count = text1Count + len(f1CurrentLine)
text2Count = text2Count + len(f2CurrentLine)
return CharByChar(count=count, text2Count=text2Count, text1Count=text1Count,
diffCharCount=diffCharCount) # return difference count
else:
print("Characters matched in line:", count, ". Moving to next line.")
text1Count = text1Count + len(f1CurrentLine)
text2Count = text2Count + len(f2CurrentLine)
count = count + 1
return CharByChar(count, diffCharCount=diffCharCount, text1Count=text1Count,
text2Count=text2Count,
diffLineCount=diffLineCount)
I have two files with the following in them
File 1:
1 Hello World
2 bazzle
3 foobar
File 2:
1 Hello world
2 bazzle
3 fooBar
It should return 2 different characters, but it does not. If you want to take a look at the entire function I have linked it here: Pastebin. Hopefully you can see something I have missed.
Your code is too complicated for this sort of application. I've tried my best to understand the code and I've come up with a better solution.
text1 = open("file1.txt")
text2 = open("file2.txt")
# Difference variables
diffLineCount = diffCharCount = line_num = 0
# Iterate through both files line by line
for line1, line2 in zip(text1.readlines(), text2.readlines()):
if line1 == "\n" or line2 == "\n": continue # If newline, go to next line
if len(line1) != len(line2): # If lines are of different length
diffLineCount += 1
continue # Go to next line
for c1, c2 in zip(list(line1.strip()), list(line2.strip())): # Iterate through both lines character by character
if c1 != c2: # If they do not match
print("Unmatched characters: ", line_num, ":", c1)
diffCharCount += 1
line_num += 1
# Goes back to the beginning of each file
text1.seek(0)
text2.seek(0)
# Prints the stats
print("Number of characters in the first file: ", len(text1.read()))
print("number of characters in the second file: ", len(text2.read()))
print("Number of characters that do not match in lines of the same length: ", diffCharCount)
print("Number of lines that are not the same length: ", diffLineCount)
# Closes the files
text1.close()
text2.close()
I hope you understand how this works and are able to make it fit your needs specifically. Good luck!
Unlike the other solution I edited your code, so that you can understand what was going wrong. I agree with him that you should anyway organize better your code because it is complex
text1 = open("file1.txt")
text2 = open("file2.txt")
def CharByChar(count, diffCharCount, text1Count, text2Count, diffLineCount):
"""
This function compares two files character by character and prints the number of characters that are different
:param count: What line of the file the program is comparing
:param diffCharCount: The sum of different characters
:param text1Count: Sum of characters in file 1
:param text2Count: Sum of characters in file 2
:param diffLineCount: Sum of different lines
"""
# see comment below for strip removal
f1CurrentLine = text1.readline()
f2CurrentLine = text2.readline()
while f1CurrentLine != '' or f2CurrentLine != '':
count = count + 1
print(f1CurrentLine)
print(f2CurrentLine)
#if f1CurrentLine != '' or f2CurrentLine != '':
if len(f1CurrentLine) != len(f2CurrentLine): # If the line lengths are not equal return the line number
print("Lines are a different length. The line number is: ", count)
diffLineCount = diffLineCount + 1
count = count + 1
#text1Count = text1Count + len(f1CurrentLine)
#text2Count = text2Count + len(f2CurrentLine)
# return CharByChar(count)
elif len(f1CurrentLine) == len(f2CurrentLine): # If the lines lengths are equal
for char in range(len(f1CurrentLine)): # Compare line by line
print(char)
if f1CurrentLine[char] != f2CurrentLine[char]: # If the lines have different characters
print("Unmatched characters: ", count, ":", char)
diffCharCount = diffCharCount + 1 # add 1 to the difference counter
#count = count + 1
text1Count = text1Count + len(f1CurrentLine)
text2Count = text2Count + len(f2CurrentLine)
# return CharByChar(count=count, text2Count=text2Count, text1Count=text1Count,diffCharCount=diffCharCount) # return difference count
else:
print("Characters matched in line:", count, ". Moving to next char.")
#text1Count = text1Count + len(f1CurrentLine)
#text2Count = text2Count + len(f2CurrentLine)
#count = count + 1
#return CharByChar(count, diffCharCount=diffCharCount, text1Count=text1Count,text2Count=text2Count,diffLineCount=diffLineCount)
#elif len(f1CurrentLine) == 0 or len(f2CurrentLine) == 0:
#print(count, "lines are not matching")
#diffLineCount = diffLineCount + 1
#return CharByChar(diffLineCount=diffLineCount)
else:
print("Something else happened!")
f1CurrentLine = text1.readline()
f2CurrentLine = text2.readline()
print("Number of characters in the first file: ", text1Count)
print("number of characters in the second file: ", text2Count)
print("Number of characters that do not match in lines of the same length: ", diffCharCount)
print("Number of lines that are not the same length: ", diffLineCount)
def main():
"Calls the primary function"
CharByChar(count=0, diffCharCount=0, text1Count=0, text2Count=0, diffLineCount=0)
input("Hit enter to close the program...")
main() #Runs this bad boi
I think the general trouble is organizing your CharByChar() function to scan all the lines in the file [which is something we maintain in this solution] but then asking to call the same function at then end of every character check
some parts have no reasons to be there: for example you set count in the main when calling CharByChar() and then you create a branch with if(count == 0). You can cut this out, the code will look cleaner
some variables as well should be removed to keep the code as clean as possible: you never use text1Count and text2Count
you enter with a condition on the while and the next if has the same condition: if you entered the while you will enter also the if [or none of them] so you can cut one of them out
I suggest you to remove the branch with if len(f1CurrentLine) == 0 or len(f2CurrentLine) == 0 because both the files can have length 0 for the same line and then the lines would be equal [see the very next example below]
I suggest you to remove the strip() to avoid troubles to interrupt the check earlier for files where you have newlines in the middle, e.g.
1 Hello
3 foobar

Split lines into words task - linear search method

I've been given a task to split lines into words and then split the lines up based on spaces and newlines. I've came up with an incomplete solution as it will not print the last word. I can only use linear search hence the basic approach.
line = raw_input()
while line != "end":
i = 0
while i < len(line):
i = 0
while i < len(line) and line[i] == " ":
i = i + 1
j = i
while line[j] != " ":
j = j + 1
print line[i:j]
line = line[j:]
line = raw_input()
I understand your problem this is somewhat similar to the Hackerearth problem
See this example to clarify your concept
y=list()
1). y=map(int,raw_input().split()) # for storing integer in list
2). y=map(str,raw_input().split()) # for storing characters of string in list
#then use this to print the value
for i in y:
print i #this loop will print one by one value
#working example of this code is #for Second part
>>baby is cute #input
>>['baby','is','cute'] #output
>> #now according to your problem line is breaks into words
If you find it useful Thumbs up

How to compare sentence character by character in python?

I want to write a code to count number of words in a given sentence by using character comparison and below is the code I have written as I am not allowed to use some fancy utilities like split(), etc. So, could you please guide me where am I making mistakes' I am a novice in python and currently trying to fiigure out how to do charactery by character comparison so as to find out simple counts of words, lines, strings withous using built in utitilites. So, kindly guide me about it.
Input Sentence : I am XYZ
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
while(Input_Sentence[i] != "\n"):
if(Input_Sentence[i] == ' '):
count=count+1
i+=1
else:
i+=1
print ('Number of Words in a given sentence is :' +str(count))
At first I wouldn't use a while loop in this context. Why not using a for loop?
for char in Input_sentence:
With this you iterate over every letter.
Then you can use the rest of you code and check:
if char == ' ':
# initialize the counter
word_count = 0
last_space_index = 0
# loop through each character in the sentence (assuming Input_Sentence is a string)
for i, x in enumerate(Input_Sentence): # enumerate to get the index of the character
# if a space is found (or newline character for end of sentence)
if x in (' ', '\n'):
word_count += 1 # increment the counter
last_space_index = i # set the index of the last space found
if len(Input_Sentence) > (last_space_index + 1): # check if we are at the end of the sentence (this is in case the word does not end with a newline character or a space)
word_count += 1
# print the total number of words
print 'Number of words:', word_count
The following will avoid errors if there's an space at the beginning or the end of the sentence.
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
sentence_length = len(Input_Sentence)
for i in range(sentence_length):
if Input_Sentence[i] == " ":
if i not in (0, sentence_length - 1):
count += 1
count += 1
print "There are %s words in the sentence \"%s\"." % (count, Input_Sentence)
You may use try-except syntax.
In your code you used while(Input_Sentence[i] != "\n") to find when the sentence comes to an end. If you just print the output at every step before i+ = 1 like this:
...
while(Input_Sentence[i] != "\n"):
...
print i,Input_Sentence[i]
i+=1
else:
print i,Input_Sentence[i],'*'
i+=1
...
you can see for yourself that the output is something like this:
Enter your sentence: Python is good
Python is good
0 P *
1 y *
2 t *
3 h *
4 o *
5 n *
6
7 i *
8 s *
9
10 g *
11 o *
12 o *
13 d *
Traceback (most recent call last):
File "prog8.py", line 19, in <module>
while(Input_Sentence[i] != "\n"):
IndexError: string index out of range
which means that the code that you have written works fine upto the length of the input sentence. After that when i is increased by 1 and it is demanded of the code to check if Input_Sentence[i] == "\n" it gives IndexError. This problem can be overcome by using exception handling tools of Python. Which leaves the option to neglect the block inside try if it is an exception and execute the block within except instead.
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
try:
while (Input_Sentence[i] != "\n"):
if (Input_Sentence[i] == ' '):
count=count+1
i+=1
else:
i+=1
except:
count = count+1
print ('Number of Words in a given sentence is :' +str(count))

Categories

Resources