How to draw numbers from a new line? - python

there is a code with prime numbers (which are displayed in the desired range)
Make simple numbers appear on the new line.
Here is the code:
a, b = map(int, input().split())
ls = []
for i in range(a, b + 1):
if all(i % n != 0 for n in range(2, i)):
ls.append(str(i))
if len(ls):
print(' '.join(ls))
else:
print(0)

I think you need a loop for print the result
print('= Enter the range (a,b) =')
a, b = map(int, input().split())
ls = []
for i in range(a, b + 1):
if all(i % n != 0 for n in range(2, i)): # check the numbers
ls.append(str(i))
print('========= Result ========')
#print the result
for number in ls:
print(number)
print('========== End ==========')

Related

Adding the highest odd and even in a list

I have a list and I'm trying to write a program that finds the highest odd and even number and add them together then print the number.
numbers = [2,3,4,5,6,1,0,7]
def solution(numbers):
lodd = -1
leven = -1
for n in numbers:
n = int(n)
if n % 2 == 0 and n > leven:
leven = n
print(n)
for n in numbers:
n = int(n)
if n % 2 != 0 and n > lodd:
lodd = n
print(n)
solution(numbers)
You could do something like :
odds = [element for element in numbers if element % 2 != 0]
evens = [element for element in numbers if element % 2 == 0]
print(max(odds) + max(evens))
Why use two loops where you could just iterate once?
Iterate and save the max per condition (odd or even), then sum the result.
positive numbers only
numbers = [2,3,4,5,6,1,0,7]
out = {0: 0, 1: 0}
for n in numbers:
if n>out[n%2]:
out[n%2] = n
sum(out.values())
# 13
more generic code to handle negative numbers as well and missing odd/even values
This handles possible missing evens or odds:
numbers = [1,3,1,5,1,-7]
out = {0: None, 1: None}
for n in numbers:
k = n%2
if out[k] is None or n>out[k]:
out[k] = n
sum(v for v in out.values() if v)
# 5

Trouble with making python rearrange code to my wanted format. (Python 3.6)

So basically I want python to first wait and let me input stuff and then do whatever it has to for every pair of inputs.
t = int(input())
E = 0
for i in range(0, t):
M, N = [int(M) for M in input(" ").split()]
if E in range(0, t):
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
i += 1
The terminal looks somewhat like this,
13 100
X
2 0
Y
I want the 2 0 to be before X but at the same time I want the code to calculate for 13 100 and output X but just after I input the 2nd pair of X, Y.
I also want to know how to remove the spaces before the '2 0' and the 'Y'.
Thanks.
Firstly, the reason you have spaces before 2 0 is because in the line:
M, N = [int(M) for M in input(" ").split()]
your input function has a space within the quotes, so you must remove it and just have an empty string:
M, N = [int(M) for M in input("").split()]
Next, the reason your code is asking for input then generating an output and so on is because the logical operators are within the for loop you have. To fix this you should have your loop to first gather the inputs then, have another loop to perform the logical operators on those inputs as so:
t = 2
E = 0
numList = []
for i in range(0, t):
M, N = [int(M) for M in input("").split()]
numList.append([M, N])
for val in numList:
if E in range(0, t):
if val[0] > 0 and val[1] > 0:
print("X")
if val[0] > 0 and val[1] == 0:
print("Y")
if val[0] == 0 and val[1] > 0:
print("Z")
To simplify things I set t = 2 since we are only talking about 2 pairs of numbers. Furthermore, I created a list to hold each pair of inputs (numList), in which the first for loop appends the values to it as an list. The next for loop looks at each item in numList and since numList is a list of lists I changed M and N to val[0] and val[1] which refer to the first number you inputed (M) and the second one you inputed (N).
Finally,
for i in range(0, t):
should look like:
for i in range(t):
Since the range function automatically just counts from 0 to t and "i += 1" at the end of the loop is also unnecessary and redundant.
My final output:
[1]: https://i.stack.imgur.com/1Bo9U.png
Put all the inputs in a 2-dimensional list before the loop that processes them.
t = int(input())
E = 0
all_inputs = [[int(M) for M in input(" ").split()] for _ in range(t)]
for M, N in all_inputs:
if E in range(0, t):
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
i += 1
The space before the 2 0 is the prompt " " in your input(" ") call. If you don't want that, use input() with no prompt.
I don't see any reason for the space before Y.
Hope this help. Its a little cleaned up:
iterations = int(input("How many times? "))
values = []
for i in range(iterations):
values.append([int(M) for M in input(f"{i+1}. Enter two numbers: ").split()])
for M, N in values:
print(M, N, end=' -> ')
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")

REMOVING REPEATED NUMBER FROM LIST, not working

I have written this code to remove repeating numbers from the list and output the max number. However, it is not removing the number which is repeated on the 4th index value. please help.
array = input()
nums = (array.split())
num = [int(i) for i in nums]
n = 0
for j in num:
for q in num:
if q == j:
n += 1
if n > 1:
while j in num:
num.remove(j)
n = 0
print(num)
print(max(num))
pythons build in function set() does this for you.
_list = [1,2,3,4,5,6,7,8,9,1,2]
print(set(_list))
outputs:
[1,2,3,4,5,6,7,8,9]

Python: What is wrong with the indexing logic in my code?

"You are given an array of n integers and an integer k. Find and print the number of (i,j) pairs where i<j and a[i] + a[j] is evenly divisible by k."
Sample input would be:
6 3
1 3 2 6 1 2
where 6 is n, 3 is k and the second line is the array of integers. The output for this input would be 5.
Here is my code, but i am not passing the test cases and am almost positive it has to do with how i am indexing it.
import sys
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
count=0;
for i in range(n):
curr = n-i
for j in range(curr):
if i < i + j:
if k % (a[i] + a[i+j]) ==0:
count = count + 1
print(count)
Also, followup question: Is this method i am approaching an efficient way of going about it?
you can try this ...
import sys
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
print(sum([1 for i in range(n) for j in range(i) if (a[i]+a[j])%k==0]))
k % ... means "k is divisible by ...", not "... is divisible by k".
if i < i + j is not very useful; you're better off doing what furas recommends in comments.
What you need is to make use of itertools.combinations:
from itertools import combinations
count = 0
for i, j in combinations(range(n), 2):
if i < j and (a[i] + a[j]) % k == 0:
print i, j
count += 1
Discussion
range(n) returns a list of indices 0 .. n-1
combinations(range(n), 2) will yield a list of two indices (without duplications)
(a[i] + a[j]) % k == 0 is the test that your asked
Note that combinations will yield pairs of i, j where i is always less than j, but the test i < j is there as a paranoid measure

Creating Python Factorial

Evening,
I'm an intro to python student having some trouble.
I'm trying to make a python factorial program. It should prompt the user for n and then calculate the factorial of n UNLESS the user enters -1. I'm so stuck, and the prof suggested we use the while loop. I know I didn't even get to the 'if -1' case yet. Don't know how to get python to calc a factorial with out just blatantly using the math.factorial function.
import math
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
print(num)
The 'classic' factorial function in school is a recursive definition:
def fact(n):
rtr=1 if n<=1 else n*fact(n-1)
return rtr
n = int(input("Enter n: "))
print fact(n)
If you just want a way to fix yours:
num = 1
n = int(input("Enter n: "))
while n > 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
If you want a test for numbers less than 1:
num = 1
n = int(input("Enter n: "))
n=1 if n<1 else n # n will be 1 or more...
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
Or, test n after input:
num = 1
while True:
n = int(input("Enter n: "))
if n>0: break
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
Here is a functional way using reduce:
>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800
You are actually very close. Just update the value of n with each iteration:
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
# Update n
n -= 1
print(num)
I am new to python and this is my factorial program.
def factorial(n):
x = []
for i in range(n):
x.append(n)
n = n-1
print(x)
y = len(x)
j = 0
m = 1
while j != y:
m = m *(x[j])
j = j+1
print(m)
factorial(5)
You could do something like this.
def Factorial(y):
x = len(y)
number = 1
for i in range(x):
number = number * (i + 1)
print(number)
#Factorial using list
fact=list()
fact1=input("Enter Factorial Number:")
for i in range(1,int(fact1)+1):
fact.append(i)
print(fact)
sum=fact[0]
for j in range(0,len(fact)):
sum*=fact[j]
print(sum)
i=1
f = 1
n = int(input("Enter n: "))
if n>=0:
while n >= i:
f=i*f
i+=1
print(f)
I am using this code in order to calculate factorial and it works.(Python 3.8)

Categories

Resources