printing the same line without repeating - python-3.x

I know that this topic was discussed here in many variations but I didn't find the solution to my problem. for example sample code like this
ages = {}
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45
for key in ages:
if ages[key] >30:
print("names",key, end = " ")
Output is : names Andrew names Karren,
how to do: names Andrew Karren

Your snippet:
for key in ages:
if ages[key] >30:
print("names",key, end = " ")
will print "names <the-name>" for all names such that ages[key] > 30. So, if you have more than one name, "names" will be printed more than once. That's what for loops are for and what they do: they execute code repeatedly.
Therefore, it stands to reason that if you don't want the literal "names" to be printed repeatedly, then you should likely move the code that prints "names" outside of the loop.

ages = {}
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45
print("names", end=" ") # Take this line out of the loop
for key in ages:
if ages[key] > 30:
print(key, end = " ")
Output:
names Andrew Karren

Related

Horizotal print of a complex string block

Once again I'm asking for you advice. I'm trying to print a complex string block, it should look like this:
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
I wrote the function arrange_printer() for the characters arrangement in the correct format that could be reutilized for printing the list. This is how my code looks by now:
import operator
import sys
def arithmetic_arranger(problems, boolean: bool):
arranged_problems = []
if len(problems) <= 5:
for num in range(len(problems)):
arranged_problems += arrange_printer(problems[num], boolean)
else:
sys.exit("Error: Too many problems")
return print(*arranged_problems, end=' ')
def arrange_printer(oper: str, boolean: bool):
oper = oper.split()
ops = {"+": operator.add, "-": operator.sub}
a = int(oper[0])
b = int(oper[2])
if len(oper[0]) > len(oper[2]):
size = len(oper[0])
elif len(oper[0]) < len(oper[2]):
size = len(oper[2])
else:
size = len(oper[0])
line = '------'
ope = ' %*i\n%s %*i\n%s' % (size,a,oper[1],size,b,'------'[0:size+2])
try:
res = ops[oper[1]](a,b)
except:
sys.exit("Error: Operator must be '+' or '-'.")
if boolean == True:
ope = '%s\n%*i' % (ope,size+2, res)
return ope
arithmetic_arranger(['20 + 300', '1563 - 465 '], True)
#arrange_printer(' 20 + 334 ', True)
Sadly, I'm getting this format:
2 0
+ 3 0 0
- - - - -
3 2 0 1 5 6 3
- 4 6 5
- - - - - -
1 0 9 8
If you try printing the return of arrange_printer() as in the last commented line the format is the desired.
Any suggestion for improving my code or adopt good coding practices are well received, I'm starting to get a feel for programming in Python.
Thank you by your help!
The first problem I see is that you use += to add an item to the arranged_problems list. Strings are iterable. somelist += someiterable iterates over the someiterable, and appends each element to somelist. To append, use somelist.append()
Now once you fix this, it still won't work like you expect it to, because print() works by printing what you give it at the location of the cursor. Once you're on a new line, you can't go back to a previous line, because your cursor is already on the new line. Anything you print after that will go to the new line at the location of the cursor, so you need to arrange multiple problems such that their first lines all print first, then their second lines, and so on. Just fixing append(), you'd get this output:
20
+ 300
-----
320 1563
- 465
------
1098
You get a string with \n denoting the start of the new line from each call to arrange_printer(). You can split this output into lines, and then process each row separately.
For example:
def arithmetic_arranger(problems, boolean:bool):
arranged_problems = []
if len(problems) > 5:
print("Too many problems")
return
for problem in problems:
# Arrange and split into individual lines
lines = arrange_printer(problem, boolean).split('\n')
# Append the list of lines to our main list
arranged_problems.append(lines)
# Now, arranged_problems contains one list for each problem.
# Each list contains individual lines we want to print
# Use zip() to iterate over all the lists inside arranged_problems simultaneously
for problems_lines in zip(*arranged_problems):
# problems_lines is e.g.
# (' 20', ' 1563')
# ('+ 300', '- 465') etc
# Unpack this tuple and print it, separated by spaces.
print(*problems_lines, sep=" ")
Which gives the output:
20 1563
+ 300 - 465
----- ------
320 1098
If you expect each problem to have a different number of lines, then you can use the itertools.zip_longest() function instead of zip()
To collect all my other comments in one place:
return print(...) is pretty useless. print() doesn't return anything. return print(...) will always cause your function to return None.
Instead of iterating over range(len(problems)) and accessing problems[num], just do for problem in problems and then use problem instead of problems[num]
Debugging is an important skill, and the sooner into your programming career you learn it, the better off you will be.
Stepping through your program with a debugger allows you to see how each statement affects your program and is an invaluable debugging tool

Difference resulting from position of print in loops

First question here.
I am picking up Python and have a question that may be quite basic.
I am trying to create this pattern with a nested loop:
x
x
x
xxx
With the code:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output +=x
print(output)
My question is - why does my output change when I move the position of print(output).
The code above works but when I align print(output) with the for count_x in numbers:, I only get "xxx", when I align print(output) to output +=x, I get the following:
x
x
x
x
xx
xxx
which is very odd because there are only 4 items in the list and it shows me 6 lines of output.
Could someone please help? Really puzzled. Thank yall very much.
There's a difference between these two bits of code (fixing the x/"x" problem along the way - your code won't actually work as is unless you have a variable x):
# First:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output += "x"
print(output)
# Second:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output += "x"
print(output)
In the second, the print is done inside the loop that creates the string, meaning you print it out multiple times while building it. That's where your final three lines come from: *, ** and ***. This doesn't matter for all the previous lines since there's no functional difference. Printing a one character string at the end or after adding each of the one characters has the same effect.
In the first, you only print the string after fully constructing it.
You can see this effect by using a slightly modified version that outputs different things for each outer loop:
numbers = [1,1,1,3]
x = 1
for count_x in numbers:
output = ""
for count in range(count_x):
output += str(x)
print(output)
x += 1
This shows that the final three lines are part of a single string construction (comments added):
1 \
2 >- | Each is one outer/inner loop.
3 /
4 \ | A single outer loop, printing
44 >- | string under construction for
444 / | each inner loop.
In any case, there are better ways to do what you want, such as:
numbers = [1,1,1,3]
for count_x in numbers:
print('x' * count_x)
You could probably also do it on one line with a list comprehension but that's probably overkill.

couting a set of word in python

Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2
This is my answer, but i dont know what's wrong with my code. Please help
s = "azcbobobegghakl"
coutBob=0
i=0
for char in range (len(s)):
if char[i:i+3]=="bob":
coutBob+=1
else:
i=i+1
print ("Number of times bob occurs is: " + str(coutBob))
You need to subscript the string s, not the index:
for i in range(len(s)):
if s[i:i+3]=="bob":
coutBob+=1
I think this will help you.
b = list(s)
i = 0
j = 0
for i in range(0,len(b)-2):
if b[i]=='b' and b[i+1]=='o' and b[i+2]=='b':
j = j + 1
print ("Number of times bob occurs is: %d"%j)

Multiple Arguments in an Input?

Beginner Programmer here. I'm trying to write a program that will ask a user for a quiz grade until they enter a blank input. Also, I'm trying to get the input to go from displaying "quiz1: " to "quiz2: ", "quiz3: ", and so on each time the user enters a new quiz grade. Like so:
quiz1: 10
quiz2: 11
quiz3: 12
Here's what I've written so far:
grade = input ("quiz1: ")
count = 0
while grade != "" :
count += 1
grade = input ("quiz ", count, ": ")
I've successfully managed to make my program end when a blank value is entered into the input, but when I try to enter an integer for a quiz grade I receive the following error:
Traceback (most recent call last):
File "C:\Users\Kyle\Desktop\test script.py", line 5, in <module>
grade = input ("quiz ", count, ": ")
TypeError: input expected at most 1 arguments, got 3
How do I include more than one argument inside the parenthesis associated with the grade input?
The input function only accepts one argument, being the message. However to get around it, one option would be to use a print statement before with an empty ending character like so:
.
.
.
while grade != "":
count += 1
print("quiz ", count,": ", end="")
grade = input()
Use .format, e.g.:
count = 0
while grade != "" :
count += 1
grade = input('quiz {}:'.format(count))
Of course, it is easy to make the variable within the str () function to convert it from a number to a string and to separate all the arguments using "+" and do not use "-" where programmatically when using "+" Python will be considered as one string
grade = input ("quiz 1: ")
count = 1
while grade != "" :
count += 1
grade = input ("quiz "+ str(count) + ": ")

Binary search code not working

Good afternoon everyone,
I'm trying to sort out names which are already sorted in alphabetical order. I can't figure out why my program isn't working. Any tips or pointers would be nice. Thanks.
def main():
names = ['Ava Fiscer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
input('Please enter the name to be searched: ', )
binarySearch
main()
def binarySearch(names):
first = 0
last = len(names) - 1
position = -1
found = False
while not found and first <= last:
middle = (first + last) / 2
if names[middle] == value:
found = True
position = middle
elif arr[middle] > value:
last = middle -1
else:
first = middle + 1
return position
What does it mean that the program isn't working? Is it a syntax error or is the problem in the wrong results?
With the code you pasted, there are several indentation problems, but besides that, lines:
input('Please enter the name to be searched: ', )
binarySearch
are also syntactically incorrect, the comma is redundant and only the function name appearing just like that is plain wrong. If you are interested in the correctness of your algorithm, it seems alright, but the boundaries can always be tricky. My code below is working and syntactically correct, if you find it helpful. (names are numbers, but that is irrelevant in this case)
names = [1,2,4,5,6,8,9]
def bs(n):
start = 0
end = len(names)
while end - start > 0:
m = (start+end)/2
if names[m] == n:
return m
elif n < names[m]:
end = m
else:
start = m + 1
return -1
print (bs(1))
print (bs(6))
print (bs(9))
print (bs(3))
print (bs(10))
print (bs(-8))
Another thing I would like to point out is that this kind of binary search is already in the python standard library, the bisect module. However, if you are writing your own for practice or for any other reason that is just fine.
if you are using python 3.* then you are going to want to change
m = (start+end)/2
to
m = (start+end)//2
When you do /2 it outputs a float in 3.*

Resources