Removing data structure - python

The goal here is to take an amount of int values indicated by the first int and create a list, in order of even numbers to odd numbers (value order of the numbers doesn't matter).
My code so far deals with most of the problem. However, how would I go about ignoring the first int value?
Example input:
example=[7,1, 0, 1, 0, 0, 1, 1]
example=[3,3, 3, 2]
example=[3,2, 2, 2]
My code:
even=[]
odd=[]
while True:
try:
n = int(input())
except:
break
if n % 2 ==0:
even.append(n)
else:
odd.append(n)
print(even+odd)

Before going in while loop, pop out first value. You can also save this as the total numbers.
Also, there is an error in your code. If try fails in while loop, for the first time loop running there will be an exception. And next on previous value will be used, so a single value will be repeated. I corrected it by adding n=0.
even=[]
odd=[]
n=0
NumCount= int(input())
while True:
try:
n = int(input())
except:
break
if n % 2 ==0:
even.append(n)
else:
odd.append(n)
print ("Total numbers (even+odd)", NumCount)
print(even+odd)

Related

While loop keeps going back to end condition

I'm just going over some python basics, and wrote some code that I thought would print every even element inside of a list:
def print_evens(numbers):
"""Prints all even numbers in the list
"""
length = len(numbers)
i = 0
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i])
i += 1
print_evens([1, 2, 3, 4, 5, 6])
I'm not sure why but the loop doesn't go past the end condition and just keeps cycling back and forth. I feel I'm missing something very simple.
If I had to guess where the problem lies, I'd say it's with the if statement, though I'm not sure what would be wrong about it.
The problem is that when you start with 1 the variable i never get updated, because it's not even. So the solution is to increment the i every time without a condition:
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i])
i += 1
If you don't want to bother with indexes you can loop directly on the list items.
def print_evens(numbers):
"""Prints all even numbers in the list
"""
for n in numbers:
if n % 2 == 0:
print(n)

Python code to extend a list of prime numbers

I want to write code that extends a list of prime numbers using Python, but something does not work:
list = [2,3,5,7]
for num in range(15,30):
for i in range(0,len(list)-1):
if num%list[i] != 0:
if i + 1 == len(list):
list.append(num)
else:
continue
else:
break
print(list)
The incorrect output is: [2, 3, 5, 7]
Your issue is that
for i in range(0,len(list)-1):
should be
for i in range(0,len(list)):
The range function in python will stop on the number before the number you specify in the stop argument, so you don't need to minus 1 yourself. From the documentation:
For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.
Because your code doesn´t work.
If you run your code, you will see that the program jumps in the else part of your first if condition and there you will break the for loop. So your program does nothing other than deklaring a list and print that list, because the true part of the if condition isn´t processed.
Another way to fix the issue #RobStreeting pointed out (+1) is to get rid of the range(len()) idiom and use enumerate(). We can fix the missing 11 & 13 that #ThierryLathuille points out by starting our loop just afer the last collected prime. Finally, you shouldn't have a variable named list as that's a reserved Python keyword. Putting this all together, your code looks something like:
primes = [2, 3, 5, 7]
for number in range(primes[-1] + 1, 50):
for i, prime in enumerate(primes, start=1):
if number % prime:
if i == len(primes):
primes.append(number)
else:
continue
else:
break
print(*primes, sep=", ")

Appending an array and storing values

import array
a=[]
count = 0
while True:
i=int(input("A number "))
count = count + 1
for j in range (0, count):
a.append(i)
if (count==3):
break
Output:
[1, 2, 2, 3, 3, 3]
This appears when I prompt the program to print 'a' variable where I want 'a' to store values like
[1, 2, 3]
Can someone point out what's wrong with my code
you can use append but in a different way:
a = []
count = 0
while True:
a.append(input("A number "))
count += 1
if count == 3:
break
in your code you're appending the user's number 'count' times to a[], the way i did it, it will append one time for loop.
You can also use
for x in range(0,3)
a.append(input('A number'))
it work's as well.
The problem with your code, is that you add input number to the a one more time in each while iteration. It's the fault of for loop there.
Also, you don't have to import array.
Also, the if/break combo is redundant, just set iterations in the while loop.
Try this code:
a = []
count = 0
while count < 3:
i = int(input("A number: "))
a.append(i)
count += 1
print(a)
Variable A prints:
[1, 2, 3]
Lose the for loop:
a=[]
count = 0
while count < 3:
count += 1
a.append(int(input("A number ")))
The reason for duplicate values in your list, a, is the inner for loop. To illustrate with an example, consider what happens when you have already entered 1 as the input and now enter 2 as the input. At this moment, before your code begins executing the for loop, count has the value 2. The inner for loop will thus insert your input value, stored in variable i (in this case, 2), twice. Similarly, when you input 3, count has the value 3 and hence the inner for loop will execute three times.
The correct code should be as follows :
import array
a=[]
count = 0
while True:
i=int(input("A number "))
count = count + 1
if (count==3):
break
Remove the for-loop or simply do
a=[]
count=3
for i in range(count):
a.append(int(input("new number: ")))
Importing array isn't needed here.
And a little hint (if you don't allready know): i+=1 is the same as i=i+1
By playing the answer from deshu, you might also consider to use try and except so that the user could continue to type a number and prompt him if ever he enter non-numeric character.
a = []
count = 0
while count < 3:
try:
i = int(input("A number: "))
a.append(i)
count += 1
except:
print('Enter only a whole number.')
print(a)

Code is in Infinite Loop and I don't know Why

My code is stuck in an infinite loop on the following lines:
while i <= len(mylist):
if mylist[i][j] == number:
I've stepped through the code but still do not know how to fix it. The problem I'm trying to solve is as follows:
Define a procedure, check_sudoku,
that takes as input a square list
of lists representing an n x n
sudoku puzzle solution and returns the boolean
True if the input is a valid
sudoku square and returns the boolean False
otherwise.
A valid sudoku square satisfies these
two properties:
Each column of the square contains
each of the whole numbers from 1 to n exactly once.
Each row of the square contains each
of the whole numbers from 1 to n exactly once.
You may assume that the input is square and contains at
least one row and column.
The below code I've written should check for just the row, not the column. Any advice on how to fix it and what I've done wrong would be greatly appreciate, so I'll understand and not make the mistake again.
def check_sudoku(mylist):
i = 0
j = 0
number = len(mylist)
while i <= len(mylist):
if mylist[i][j] == number:
number = number - 1
j = 0
if number == 0:
i = i + 1
number = len(mylist)
else:
j = j + 1
if number not in list:
break
return False
return True
check_sudoku([[1, 2, 3, 4],
[1, 3, 1, 4],
[3, 1, 2, 3],
[4, 4, 4, 4]])
I'm going to explain the function with the list you supplied as an example.
What's happening is:
number = len(mylist)
number = 4
while 0 <= 4
if 1 == 4: // This condition will never be true and therefore doesn't run the code below it
The while will run again and the same will happen.
If you put this line
print("i: " + str(i) + " j: " + str(j))
Just under where the While Loop starts, you realise that i and j never increment and it stays on the first spot.
You have to increment i and j after your bigger if statement

Finding all numbers that evenly divide a number

So I'm trying to make a program that when I input a number it will give me all the factors(12->1,2,3,4,6,12). I only started programming very recently so there may be some very obvious things. But here's my code
numbers = [1]
newnum = 1
chosen = int(input("Enter what you want the factors of: "))
def factors(numbers,newnum,chosen):
lastnum = numbers[-1]
if (chosen == lastnum):
for number in numbers:
if (number % 1 != 0):
numbers.remove(number)
print (numbers)
else:
factors(numbers,newnum,chosen)
else:
newnum = numbers[-1] + 1
numbers.append(newnum)
print (numbers)
factors(numbers,newnum,chosen)
factors(numbers,newnum,chosen)
Ok, so I don't really need the redundancies addressed but if you see something that would completely stop the program from working please point it out. Sorry I bothered you all with this but I don't know what else to do.
There are lots of problems:
Every integer number modulo 1 is zero because each integer is divisible by one without remainder.
You remove items from the list you're iterating over, that will definetly give wrong results if you don't do it carefully!
You try to do recursion but you don't return the result of the recursive call. That's possible because you operate on a mutable list but it's generally not really good style
You don't have any inline comments explaining what that line is supposed to do, so it's hard to give any reasonable guidance on how to improve the code.
If you want a code that finds all factors, consider something like this:
chosen = int(input("Enter what you want the factors of: "))
def factors(chosen, currentnum=None, numbers=None):
# Recursion start, always append 1 and start with 2
if numbers is None:
numbers = [1]
currentnum = 2
# We're at the last value, it's always divisible by itself so
# append it and return
if currentnum == chosen:
numbers.append(currentnum)
return numbers
else:
# Check if the chosen item is divisible by the current number
if chosen % currentnum == 0:
numbers.append(currentnum)
# Always continue with the next number:
currentnum += 1
return factors(chosen, currentnum, numbers)
>>> factors(chosen)
Enter what you want the factors of: 12
[1, 2, 3, 4, 6, 12]
That's not the optimal solution but it uses recursion and gives a proper result. Just don't enter negative values or catch that case in the function at the beginning!
# Two Pointer Approach
ans = []
def divisor(val):
result = []
for i in range(1, val + 1):
ans.append(i)
i = 0
j = len(ans) - 1
while i < j:
if ans[i] * ans[j] == ans[-1]:
result.append(ans[i])
result.append(ans[j])
i += 1
else:
j -= 1
return sorted(result)
print(divisor(12))
# Output
>>> [1, 2, 3, 4, 6, 12]

Categories