Ten numbers per row using a pair of nested while loops - python

I was trying to do an exercise, but have a hard time doing it. I need to write a program containing a pair of nested while loops that displays the integer values 1-100, ten per row. I'm not sure how I should use while loops in such a task, I was trying something like this, but it seems like it only gives me first line to 10 and then all other numbers in second line:
i = 1
while i <=100:
print(i, end=' ')
i = i + 1
Any advice?

Hope This will help
#python 2.7.6
for i in range(1, 101):
print(i),
if i%10==0:
print
another solution with nested while loop:
loop1 = 10
loop2 = 10
num = 1
while(loop1>0):
while(loop2>0):
print num,
num = num+1
loop2=loop2-1
print
loop2=10
loop1=loop1-1

Seems like I did the job right, thanks guys for helping me out.
i = 1
per_row = 10
while i <=100:
while(per_row > 0):
print(i, end=' ')
i = i + 1
per_row = per_row - 1
print()
per_row = 10

Here is a bit cleaner one:
i = 1
column = 10
while i <= 100:
if column > 0:
if i < 10:
print(format('', '1') + str(i), end = ' ')
else:
print(i, end = ' ')
i = i + 1
column = column - 1
else:
print()
column = 10

Related

I'm new in codewars and i don't understand why my solution is not correct

I wrote a working code without any bugs, and the result is the same as it is shown in the sample, but codewars is not accepting my solution, and i did not get why it is not correct.
Here is the kata from codewars: https://www.codewars.com/kata/5842df8ccbd22792a4000245
Here is my code:
def expanded_form(num):
lenght = list(str(num))
num_list = []
ten = 10
final = ''
for i in lenght:
result = num % ten
num -= result
ten = ten * 10
if result > 0:
num_list.append(str(result))
num_list.reverse()
for j in range(len(num_list)):
if j == len(num_list) - 1:
final += num_list[j]
else:
final += num_list[j] + ' + '
print(final)
I have no clue what's wrong, so i can't move forward.
Your method is cluttered a lot, I can not truly understand your intentions so I have majorly refactored your code.
def expanded_form(num):
numsplitted = list(map(int, str(num))) # Convert the input to separate int digits
ten = 1 # 10 to the power 0
for i in range(len(numsplitted)-1, -1, -1): # We reverse it to start from the ones place.
numsplitted[i] = numsplitted[i] * ten
ten *= 10 # Increase 10's power by multiplying by 10
while 0 in numsplitted: # There are 0 in our list
numsplitted.remove(0)
return ' + '.join(map(str, numsplitted)) # Finally convert all values to a string and join them with ' + '

Looping a function that changes it's output every iteration

I'm new to python and I'm trying to create something that if the number is odd for example 7 it does this (7 * 3+1) and if it is even for example 6 it does this (6/2) but the problem is that I want to loop this but it updates the number every output from the example earlier 7 I want this to turn to (22/2) and so on and if the number 1 is reached it stops.
output = []
number = 7
def mat(self):
if (self % 2) == 0:
even = self / 2
return even
else:
odd = self * 3 + 1
return odd
while mat(number) != 1:
output.append(mat(number))
output.append(mat(mat(number))
print(output)
this part doesn't work because it will never reach 1 and it only has 1 output (22) starting from the number 7 :
while mat(number) != 1:
output.append(mat(number))
output.append(mat(mat(number))
To update number, you need to assign it:
number = mat(number)
The best place to do this is in the while loop:
while number != 1:
number = mat(number)
For an exercise like this, it makes sense to just print the value on each iteration rather than trying to create an array of results:
while number != 1:
print(number)
number = mat(number)
Just update the value
For while loop:
a = 0
while a<10:
print("Hello World")
a = a + 1
For for loop:
a = 0
for i in range(10):
print("Hello World")
a = a + 1
if a >= 10:
break

Counting the most amount of zeros in a row in a number | Python

I want to create a function that asks for a number and then sees the most amount of zeros in a row and returns its value (ex: 5400687000360045 -> 3 | 03500400004605605600 -> 4).
So far this is all I got but it isn't working:
def zeros():
num = input('Write a number: ')
row = 0
result = 0
for i in num:
if i == '0':
while i == '0':
row += 1
if row > result:
result = row
return result
What's wrong?
EDIT:
This is what the desired output should be:
zeros()
Write a number: 03500400004605605600
4
My current output is nothing, meaning it's not returning anything
This should do it.
def zeros():
num = input('Write a number: ')
row = 0
count = 0
for i in num:
if i == '0':
count += 1
else:
row = max(row, count)
count = 0
row = max(row, count)
return row
Your code is getting stuck in an infinite loop in inner while
To do it your way, you just need to keep track of whether the number is a 0 or not (i.e. to know if it is a row of zeros or if you need to restart the count). Something like this would work:
def zeros():
num = input('Write a number: ')
row = 0
result = 0
for i in num:
if i != '0':
row = 0
else:
row += 1
if row > result:
result = row
return result
Output is as you would expect.
If you know regex, you could achieve this with much less code using:
import re
def zeros():
num = input('Write a number: ')
result = max(map(len, re.findall(r'0+', num)))
return result
Is this helpful to you..? regex (Regular expression operations) is a very handy tool which could make your life easier. Please have look at Regular expression operations
import re
def zeros():
num = input('Write a number: ')
return max(re.findall("(0+0)*", (num)))
output : 000
def zeros():
num = input('Write a number: ')
return len(max(re.findall("(0+0)*", (num))))
output : 3
I think this might work
num = input()
countOfZeros = 0
for i in range(len(num)-1):
curr = 0
if num[i] == num[i+1]:
curr = 0
if curr > countOfZeros:
countOfZeros = curr
else:
countOfZeros += 1
print(countOfZeros - 1 )

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

Beginners python program

Decided to help out with doing a lab for my buddy, first time ever doing this so please don't make fun of my code lol. I have to get a number "num" of how many numbers to add to array, then a total number. Then from that I want to add user defined numbers from the size of the array. Then if any of those numbers adds up to the total then print them out, else print sorry. Can't understand why it doesn't work :(
EXTRA EDIT: Problem is, my script does not show the numbers that add up to the total value, only the print('sorry')
edit: I learned prior to this java and C, couldn't figure out the foor loops or how variable types are instantiated.
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
As I got it, your current script is looking for two consequent numbers where sum equal to total, but should search for any pair in array, right? So if we have
ar = [1, 2, 3]
and
total = 5
program should display 2, 3 pair. But it will not find 1+3 for total=4.
Here are some general advices:
There is error in print invocation, where pair is printed (string should go first in str+int concatenation). Use format
print('%d, %d'.format(ar[k], ar[k])
or print result as tuple
print(ar[k], ar[l])
Use for k in range(num) instead of while
hasValue is better to be boolean value
Well, here is my solution (python2.7)
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."
This is how to do for-loops in python:
for x in range(10):
# code for the for loop goes here
This is equivalent to:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
... in C++
(Notice how there is no initializing the variable 'x'. When you do a for loop, python automatically initializes it.
Here is what I think you wish to do:
def main():
num = int(input("Enter the amount of numbers: "))
total = int(input("Enter the total: "))
array = []
counter, elem = 0, 0
for user_numbers in range(num):
array.append(int(input("Please enter number: ")))
for each_element in array:
counter += each_element
elem += 1
if counter == total:
print(array[:elem])
break
if counter != total:
print("sorry...")
main()
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
Apart from the fact that the loops are not "pythonic", you need to initialize l = 0 within the k loop.
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
or slightly more python way:
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1

Categories

Resources