series of numbers separated by odd and even numbers using python [duplicate] - python-3.x

This question already has an answer here:
Code to produce a sequence with repeating pattern
(1 answer)
Closed 10 months ago.
a series of numbers each number is separated by odd and even numbers for example: separated by odd numbers(1,3,7,9...) - 1 2 5 10 17 26 37..... and separated by even numbers(2,4,6,8...) - 1 3 7 13 21 31 43.....
i want a python program for these series of numbers, thank you.

You could utilize a couple of generators:
def separated_by_odd_sequence() -> int:
num = 1
odd_increment = 1
while True:
yield num
num += odd_increment
odd_increment += 2
def separated_by_even_sequence() -> int:
num = 1
even_increment = 0
while True:
num += even_increment
even_increment += 2
yield num
def main() -> None:
separated_by_odd_sequence_gen = separated_by_odd_sequence()
first_10_separated_by_odd = [
next(separated_by_odd_sequence_gen) for _ in range(10)
]
print(f'{first_10_separated_by_odd = }')
separated_by_even_sequence_gen = separated_by_even_sequence()
first_10_separated_by_even = [
next(separated_by_even_sequence_gen) for _ in range(10)
]
print(f'{first_10_separated_by_even = }')
if __name__ == '__main__':
main()
Output:
first_10_separated_by_odd = [1, 2, 5, 10, 17, 26, 37, 50, 65, 82]
first_10_separated_by_even = [1, 3, 7, 13, 21, 31, 43, 57, 73, 91]

Related

Append to an empty list using while loop

I've tried running this python script but it returns an empty list, I don't see what I'm missing but it seems I'm failing to append anything to the list. (The goal is to return a list of n numbers of prime numbers starting from 2, there are restrictions such as using only the while loop.) Appreciate any insights!!
def primes_list(n):
primes = []
count = 0
while count < n:
num = 1
divisor = 2
while num % divisor != 0 and num > divisor:
divisor += 1
if divisor == num:
primes.append(num)
count += 1
return primes
count is not used in the algorithm. Do you mean to use count everywhere num currently appears? Since you reset num to 1 on every iteration, every time around, the two boolean conditions are both false and the outer while effectively just counts up to n.
You don't need count as a counter. You just need to move num outside the while loop and increase num till n.
def primes_list(n):
primes = []
num = 1
while num < n:
divisor = 2
while num % divisor != 0 and num > divisor:
divisor += 1
if divisor == num:
primes.append(num)
num += 1
return primes
def primes_list(n):
num = 1
while num <= n:
div = 2
while num % div and num > div: div += 1
if div == num: yield num
num += 1
print(list(primes_list(100)))
This will simplify the code and alternative using yield generator.
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

FIND THE PERFECT NUMBER IN PYTHON

I do have an answer already but I'm curious if there's a better method on coding this problem through python. Thank you.
A number is called a perfect number if it is equal to the sum of all of its divisors, not including
the number itself. For instance, 6 is a perfect number because the divisors of 6 are 1, 2, 3, 6
and 6 = 1 + 2 + 3. As another example, 28 is a perfect number because its divisors are 1, 2, 4,
7, 14, 28 and 28 = 1 + 2 + 4 + 7 + 14. However, 15 is not a perfect number because its divisors
are 1, 3, 5, 15 and 15 6= 1 + 3 + 5. Write a program that finds all four of the perfect numbers
that are less than 10000.
Here is my answer.
for i in range(1,10000):
summ = 0
for m in range(i):
if i % (m+1) == 0:
summ = summ + (m+1)
g = summ - i
if g == i :
print(g)
Here is perfect number algorithm that checks for perfect numbers using the Lucas Lehmer Test:
def ffs(x):
return (x&-x).bit_length()-1
def levelx(N, withstats=False):
if N <= 1: return False
temp = N
newlevel = temp.bit_length()
primetest = temp//(2**(ffs(temp)))
offset = temp//primetest
s = 4
nextlevel = newlevel // 2
check = temp // (2**nextlevel)
prevtemp = 2**nextlevel
if withstats == True:
print (newlevel, newlevel, temp)
print (newlevel, nextlevel+one, prevtemp)
if (prevtemp & (prevtemp-1) == 0) and prevtemp != 0:
if offset.bit_length() == primetest.bit_length():
if ((primetest+1) & ((primetest+1)-1) == 0):
for x in range(primetest.bit_length()-1):
s = (s * s - 2) % primetest
if withstats == True:
print(s)
if s in [0,2]: return True
return False
else: return False
else: return False
else: return False
Here is the output:
In [645]: for x in range(2,100):
...: if levelx((2**(x-1))*(2**x-1)) == True:
...: print(x, (2**(x-1))*(2**x-1))
...:
...:
2 6
3 28
5 496
7 8128
13 33550336
17 8589869056
19 137438691328
31 2305843008139952128
61 2658455991569831744654692615953842176
89 191561942608236107294793378084303638130997321548169216
You can use gmpy2 to speed these up by about 10x.
for j in range(1,10000):
sum=0
for I in range(1,J):
if J%I==0:
sum= sum + I
if j==sum:
print(J," is a perfect square")

tribonacci sequence python code skips for loop within while loop

I wanted to use a for loop within a while loop to add up the last 3 numbers of the list and generate a new number to append into the existing list. However, the code would not enter the for loop within the while loop and I have no clue why.
What the function is supposed to do:
Take in a list of numbers (as signature)
Total up the LAST 3 numbers in the list and produce the next number to be appended
Continue step 2 until length of list == n
#my code
def tribonacci(signature, n):
total = 0
for i in range(len(signature)):
num = signature[i]
total += num
signature.append(total)
while len(signature) < n:
for j in range(-1,-4):
num = signature[j]
total += num
signature.append(num)
return signature
#Some sample test code:
print(tribonacci([1, 1, 1], 10))
print("Correct output: " + "[1, 1, 1, 3, 5, 9, 17, 31, 57, 105]")
print(tribonacci([0, 0, 1], 10))
print("Correct output: " + "[0, 0, 1, 1, 2, 4, 7, 13, 24, 44]")
print(tribonacci([300, 200, 100], 0))
print("Correct output: " + "[]")
UPDATE!
As suggested, I resetted the total count in the while loop by creating a total_2 = 0. I've also added the -1 to the range and changed .append(num) in the while loop block to .append(total_2).
def tribonacci(signature, n):
total = 0
for i in range(len(signature)):
num = signature[i]
total += num
signature.append(total)
while len(signature) < n:
total_2 = 0
for j in range(-1,-4, -1):
num = signature[j]
total_2 += num
signature.append(total_2)
return signature
However, this code doesnt work the 3rd print test code where n = 0. One of the users shared a much shorter code which works for ALL of the test code.
Try range(-1,-4,-1). You need to tell python to go backwards.
Just for the reference, I've implemented your function with a few improvements:
def tribonacci(signature, n):
signature = signature[:n]
while len(signature) < n:
signature.append(sum(signature[-3:]))
return signature

Finding subset List of Python List based on an input integer

I want a subset list from input List based on input integer value.
For Example:
Input List: [3,7,9,11,12]
Input Value: 2
Output List: [1,7,9,11,12]
# 2 is subtracted from first element of list
Input List: [3,7,9,11,12]
Input Value: 5
Output List: [5,9,11,12]
#5 is subtracted from list in sequence manner, first 3 is subtracted then remaining 2 is subtracted from 7 hence output is [5,9,11,12]
Use numpy.cumsum() if modules are allowed:
import numpy as np
input_list = np.asarray([3, 7, 9, 11, 12])
input_integer = 5
output_list = input_list[input_list.cumsum() > input_integer]
output_list[0] -= input_integer - input_list[input_list.cumsum() <= input_integer].sum()
print(output_list)
Output:
[ 5 9 11 12]
What i did there:
Since total sum is to be subtracted from starting, using cumulated sum will tell you where to crop the list from.
Then set the first element = first elem - (input_integer - cropped list's sum)
Recursive solution:
def subfrom( lst, n ):
if n<=0 or lst == []:
# No change necessary
return lst
if lst[0] <= n:
# First element gets removed
# Return the list you get by removing the leftover from the rest of the list
return subfrom( lst[1:], n-lst[0] )
# Reducde first element
return [lst[0]-n] + lst[1:]
Another solution:
# First set of test variables
list1 = [3,7,9,11,12]
input1 = 2
# Second set of test variables
list2 = [3,7,9,11,12]
input2 = 5
def eval_list(input_value, iterable, output = None):
if output is None:
output = []
for i, v in enumerate(iterable):
current = iterable[i]
if input_value > 0:
if v <= input_value:
input_value -= current
else:
current -= input_value
input_value = 0
output.append(current)
else:
output.append(current)
return output
Run for each data set and output results:
res1 = eval_list(input1, list1)
res2 = eval_list(input2, list2)
print(f"Set 1: {res1}")
print(f"Set 2: {res2}")
Output:
Set 1: [1, 7, 9, 11, 12]
Set 2: [5, 9, 11, 12]

Select a number randomly with probability proportional to its magnitude from the given array of n elements

Ex 1: A = [0 5 27 6 13 28 100 45 10 79]
let f(x) denote the number of times x getting selected in 100 experiments.
f(100) > f(79) > f(45) > f(28) > f(27) > f(13) > f(10) > f(6) > f(5) > f(0)
My code:
def pick_a_number_from_list(A,l):
Sum = 0
#l = len(A)
for i in range(l):
Sum+=A[i]
A_dash = []
for i in range(l):
b=A[i]/Sum
A_dash.append(b)
#print(A_dash)
series = pd.Series(A_dash)
cumsum = series.cumsum(skipna=False)
#print(cumsum[9])
sample_value = uniform(0.0,1.0)
r = sample_value
print(r)
#for i in range(l):
if r<cumsum[1]:
return 1
elif r>cumsum[1] and r <cumsum[2]:
return 2
elif r<cumsum[3]:
return 3
elif r<cumsum[4]:
return 4
elif r<cumsum[5]:
return 5
elif r<cumsum[6]:
return 6
elif r<cumsum[7]:
return 7
elif r<cumsum[8]:
return 8
elif r<cumsum[9]:
return 9
def sampling_based_on_magnitued():
A = [0,5,27,6,13,28,100,45,10,79]
n = len(A)
#for i in range(1,10):
num = pick_a_number_from_list(A,n)
print(A[num])
sampling_based_on_magnitued()
In mu code i am using multiple if else statement and because it is hardcoded
i can make by o/p right till 10 element in the list.
I want to make my code dynamic for any value in the list.
Here in my code i have restricted it to n=10
Pls tell me how can i right generic code which can replace all if - elseif statement with for loop
sum1=0;
for i in A:
sum1+=i;
x=0
list1=[]
for i in A:
list1.append(x+i/sum1)
x=x+i/sum1;
#list1 contsins cumulative sum
bit=uniform(0,1)
for i in range (0,len(list1)):
if bit<list1[i]:
return A[i]
you may use this
you can use random.choices
A = [0,5, 27, 6, 13, 28, 100, 45, 10, 79]
let no of random values want to pick it be 100 s0 k=100
w = [0.0, 0.01597444089456869, 0.08626198083067092, 0.019169329073482427, 0.04153354632587859, 0.08945686900958466, 0.3194888178913738, 0.14376996805111822, 0.03194888178913738, 0.2523961661341853]
weights is calculsted by using A[i]/(total sum of all the values of A)
x = random.choices(A,w,k=100)
print(x)
it displays the values from list A according to there weights
Some changes in Bitan Guha Roy's code to return just one value
import numpy as np
sum1=0;
for i in A:
sum1+=i;
x=0
list1=[]
for i in A:
list1.append(x+i/sum1)
x=x+i/sum1;
# list1 contains cumulative sum
bit=np.random.uniform(0.0,1.0,1)
for i in range (0,len(list1)):
if bit>=list1[i] and bit<list1[i+1]:
print(A[i+1]) # or return if under a function
import random
lst=[0, 5 ,27, 6, 13, 28, 100, 45, 10,79]
def pick_a_number_from_list(A):
weights1=[]
for i in A:
weights1.append(i/sum(lst))
selected_random_number = random.choices(A,weights=weights1,k=1)
return selected_random_number
def sampling_based_on_magnitued():
for i in range(1,100):
number=pick_a_number_from_list(lst)
print(number)
sampling_based_on_magnitued()
# used random.choices which gives option to choose random number according respective weights. Please suggest any modification if you've any

Resources