While n > 1. Decrease n by 1 on each iteration - python

I'm working on some hackerrank problems and I've looked at a couple of ways to take this input and loop through it.
What is be best alternative to trying to decrease n on each iteration as below (as this doesn't seem to be possible).
first_n = int(raw_input())
def findPercentage(n):
if n > 1:
studentinfo = raw_input()
return studentinfo
n = n - 1
result = findPercentage(first_n)
print result
As I'm knew to this, I understand that my logic might be flawed.
The input is passed as stdin with the first line listing the total number of lines to follow. I will want to perform a single operation on every line after the first line with the exception of the last line where I'd look to perform a different operation.

n= int(input())
studentinfo= {}
for i in range(n):
inputs= raw_input().split(" ")
studentinfo[inputs[0]]= inputs[1:];
This will create a dictionary studentinfo with names as key and list of marks as value.

The first line gives you the number of students N:
n = int(raw_input())
Then you want to loop through your function N number of times:
for i in range(n):
studentinfo = raw_input().split(" ")
print(studentinfo[0])
This will create a list called studentinfo, and this will print the student's name. See where you can go from there.

Related

Happy Numbers doesn't update variable

I've been coding for about 3 months. Could someone help me understand why my code isn't working? I could look up the answer, but I'd really like to figure out what is going wrong. It runs perfectly the first time through the code, but while it is While-Looping, x always stays as the number inserted into the function. Thanks for your help! The assignment and code is below (for an Udemy class).
Happy Numbers -
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here. Find first 8 happy numbers.
def find_happy_number(x):
#we need a bunch of lists
digit_list = []
squared_list = []
result_list = []
happy_numbers = []
unhappy_numbers = []
while True:
#break our number into digits
x = str(x)
for digit in x:
digit_list.append(int(digit))
#square each digit and store in list
for digit in digit_list:
squared_digit = digit**2
squared_list.append(squared_digit)
#adds all numbers on that list
result = sum(squared_list)
print(result)
#check to see if it is a happy number
if result == 1:
print(f'{x} is a happy number!')
break
#check to see if it is an un-happy number
if result in result_list:
print(f'{x} is an UN-happy number!')
break
#if it isn't we continue the churning.
#adds result to result list to see if we are looping infinitally
x = result
result_list.append(result)
`
The PROBLEM is that you are not resetting digit_list and squared_list in every loop, so they just keep getting bigger and bigger. Move their initialization into the while loop, or use a list comprehension instead of a loop.
Consider this for your loop:
while True:
digit_list = [int(digit) for digit in str(x)]
squared_list = [digit**2 for digit in digit_list]
Now you don't need to initialize them. Or, for extra fun, combine it all into one:
while True:
result = sum(int(digit)**2 for digit in str(x))

Python: Loop to check if an input is valid or not line by line

Given the following inputs that simulate a grid with the respective dimensions:
totLines = int(input("Indicate the number os lines: "))
totColunms = int(input("Indicate the number of columns: "))
I want to check whether the input is valid or not (every digit must be between 0 and 20). The code should check each line of the grid and tell the user if the input is valid and if not ask for another input. The problem is that my code only checks the first digit of line1, the second digit of the line2, and so on. For instance, in a 3x3 grid, if I input the following numbers for line1 (separated by spaces) - 21 10 10 - the code is gonna tell me that the input is not valid, but if I put the incorrect digit in position 2 - 10 21 10 - the code is not gonna find any problem. I know the problem must be related to how I´m doing the loop but I can´t understand how to solve this. This is something easy to do but It´s my first time learning a programming language and I still have a lot to learn. Thanks!
for lin in range (1, totLines+1):
print("Line", str(lin))
while True:
sMoves = input("Movement for this line: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
if listMovesINT[lin-1] > 0 and listMovesINT[lin-1] <= 20:
break
else:
print ("Not a valid integer")
continue
I'd suggest putting the logic to get a valid list of moves in its own function, using all() to test all the values in the list (you don't need the current value of lin or anything else in the main loop to figure this out, and putting this task in its own function makes it easier to focus on it without accidentally mixing in other parts of your program):
def get_movement() -> list[int]:
"""Get a list of movement values between 1 and 20."""
while True:
try:
moves = [int(n) for n in input("Movement for this line:").split()]
if not all(1 <= n <= 20 for n in moves):
raise ValueError("all values must be between 1 and 20")
return moves
except ValueError as e:
print("Not a valid integer:", e)
and then in your main loop you can do:
for lin in range (1, totLines+1):
print("Line", lin)
moves = get_movement()
# do whatever thing with moves
As you noticed, you are "binding" the items in your input to your "board" (sort of the "board"... the totLines variable).
But you really just want to verify one input at a time, right? When the user writes the set of movements for any given line, it doesn't really matter whether it's for the first line of the "board" or for the last. Maybe you want the line index to display a nice prompt message, but that's about it. When it comes to ensuring that the input is valid, you really don't need the line for anything, isn't it?
So it all boils down to verifying that the inputs for any given line are valid, and keep pestering the user until they (all) are. Something like:
valid_input = False
while not valid_input:
sMoves = input("Movement for this line: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
valid_input = all((0 < move <= 20) for move in listMovesINT)
if not valid_input:
print("One of the movements is not valid")
If you wanna use the number of total lines (totLines) to show a little bit more human-friendly prompt and then make the code a bit more like what you have it (with a for loop), you can just wrap the while not valid_input like this:
totLines = int(input("Indicate the number os lines: "))
for lineNum in range(1, totLines + 1):
valid_input = False
while not valid_input:
sMoves = input(f"Movement for line {lineNum}: ")
listMoves = sMoves.split()
listMovesINT = list(map(int, listMoves))
valid_input = all((0 < move <= 20) for move in listMovesINT)
if not valid_input:
print("One of the movements is not valid")
First, your code only check one integer per line.
You have an index but it is a line index (lin-1), not a number index.
Was the "while True" supposed to iterate over numbers. If yes, it should be after the "split()".
Here's a working example:
matrix = []
totlines=3
for i in range( totlines):
line = input( "... ")
numbers = [ int( text) for text in line.split()] # convert list of asciiNumbers to list of 3 integers
for number in numbers:
if (number <= 0) or (number>20):
print( "Invalid number in line", i, ":", numbers)
matrix.append( numbers)
print( matrix)

I am stuck at practice python exercise 4

number = int(raw_input("Enter a number :"))
div = range(0, number)
list = []
while div <= number:
if number % div == 0:
list.append(div)
div =+ 1
print list
this is my code which I made for this exercise :
http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
I am new to programming so i dont know what is wrong with my code but its not giving any output.
I guess this answer is simple enough, and looking from the down-votes people think this too. However... one only learns by asking!
There are three essential mistakes in the code that you propose, and a number of ways to make it more Pythonic.
First, and foremost, dividing by zero is not possible! So you'd want to check numbers in the range (1-number).
Based on the indentation list is printed many times, instead of only at the end of completing the while loop.
You want to avoid using list as a variable because it is a Python keyword.
Then, to make it more Pythonic my proposition is the following:
number = int(input("Enter a number :"))
output = []
for i in range(1,number+1):
if not number%i:
output.append(i)
print(output)
Note that raw_input no longer exists in Python 3.x. Also note that this way we avoid the while loop, that from experience, can easily lead to mistakes. In stead it has been replaced by automatically looping through the entries in the list generated by range(1,number).
Finally a note on range but probably also on semantics. I consider number also to be a divisor of number. To do so I have used range(1,number+1). Because, for example range(5) returns a list up to 5: [0,1,2,3,4]. I.e. it does not include 5.
Here is the code you need:
number = int(input("Enter a number :"))
list = []
# theoretically this is the limit you should test for divisors
for div in range(2, int(number/2 + 1)):
if number % div == 0:
# adds the divisor to the list
list.append(div)
div += 1
# prints all divisors in new line
for item in list:
print(item)
If you are using python 2.7, instead of input use raw_input

Finding numbers that are multiples of and divisors of 2 user inputted numbers

I have an assignment for Python to take 2 user inputted numbers (making sure the 1st number is smaller than the second) and to find numbers that are multiples of the first, and divisors of the second.. I'm only allowed to use a while loop (new condition my teacher added today..) I've done it with a for loop:
N_small = int(input("Enter the first number: "))
N_big = int(input("Enter the second number: "))
numbers = ""
if N_small > N_big:
print("The first number should be smaller. Their value will be swapped.")
N_small, N_big = N_big, N_small
for x in range(N_small, N_big+1, N_small):
if N_big % x == 0:
numbers += str(x) + " "
print("The numbers are: ", numbers)
I'm not asking for the answer to how to do this with a while loop - but I just need a hint or two to figure out how to start doing this... Can anyone enlighten me?
Thanks
You can convert any for loop into a while loop trivially. Here's what a for loop means:
for element in iterable:
stuff(element)
iterator = iter(iterable)
while True:
try:
element = next(iterator)
except StopIteration:
break
stuff(element)
Of course that's not what your teacher is asking for here, but think about how it works. It's iterating all of the values in range(N_small, N_big+1, N_small). You need some way to get those values—ideally without iterating them, just with basic math.
So, what are those values? They're N_small, then N_small+N_small, then N_small+N_small+N_small, and so on, up until you reach or exceed N_big+1. So, how could you generate those numbers without an iterable?
Start with this:
element = N_small
while element ???: # until you reach or exceed N_big+1
stuff(element)
element ??? # how do you increase element each time?
Just fill in the ??? parts. Then look out for where you could have an off-by-one error that makes you do one loop too many, or one too few, and how you'd write tests for that. Then write those tests. And then, assuming you passed the tests (possibly after fixing a mistake), you're done.
You don't have to iterate over all the numbers, only the multiples...
small, big = 4, 400
times = 1
while times < big / small:
num = times * small
if big % num == 0: print(num)
times += 1

I am trying to create a program that takes a list of numbers from the user and checks whether or not the first number given in repeated in the list

i know i can use the input function in conjunction with the eval function to input a list of numbers:
numbers = eval(input("enter a list of numbers enclosed in brackets: "))
Also, given a list named items, i can get the list of all the elements of items, except the first one, with
the expression:
items[1:]
im just not sure how to go about getting the program to do what i want it to do
If you have a list and you want to know if the first value appears again later in the list, you can use:
items[0] in items[1:]
That will return True or False depending on whether the first element in items appears again later in items.
Don't use eval, ast.literal_eval is safer
import ast
numbers = ast.literal_eval(raw_input("enter a list of numbers enclosed in brackets: "))
An easier solution will be
x = l[0]
l[0] = None
print x in l
l[0] = x
The advantage is that you don't need to recreate the list
There are two parts to your problem:
get a list of numbers from the user
check if the first number is repeated in this list
There are several ways to get a list of numbers from a user. Since you seem to be new to python, I will show you the easiest way to program this:
n = raw_input("How many numbers in your list?: ")
n = int(n) # assuming the user typed in a valid integer
numbers = []
for i in range(n):
num = raw_input("enter a number: ")
num = int(num)
numbers.append(num)
# now you have a list of numbers that the user inputted. Step 1 is complete
# on to step 2
first_num = numbers[0]
for n in numbers[1:]:
if n == first_num:
print "found duplicate of the first number"
Now, there are more elegant ways to accomplish step 1. For example, you could use a list comprehension:
numbers = [int(n) for n in raw_input("Enter a bunch of space-separated numbers: ").split()]
Further, step 2 can be simplified as follows:
if numbers[0] in numbers[1:]:
print "found duplicates of the first number"
Hope this helps

Categories