How to convert this C++ for loop to Python? - python

Here is a for loop in C++. How would you convert this to Python?
for(j=1, k=x; j<=x; j++, k--)

j = 1
k = x
while j <= x:
j = j + 1
k = k - 1

j = 1
k = x
while j <= x:
j += 1
k -= 1
same as previous small changed

I just think so:
x = 5
k = x
for j in range(1, x+1, 1):
# do something
print(j, k)
k -= 1
And it output:
(1, 5)
(2, 4)
(3, 3)
(4, 2)
(5, 1)

Related

How can I count number of looping cycles in number factorization

I want to factor a number and count the number of times each prime number is multiplied to get the desired one. For example 200=2*2*2*5*5 which would give me [[2,3],[5,2].
This is what I wrote:
def factor(N):
f = []
k = 2
c = 0
while k <= N:
if N % k == 0:
while N % k == 0:
b = N / k
N = b
c += 1
f.append([k, c])
else:
k += 1
return f
n = factor(200)
print(n)
output:
[[2, 3], [5, 5]]
expected output:
[[2, 3], [5, 2]] # come from 200 = 2x2x2x5x5
Move the counter on the first loop, like on the code below.
def factor(N):
f = []
k = 2
while k <= N:
c = 0
if N % k == 0:
while N % k == 0:
b = N/k
N = b
c += 1
f.append([k, c])
else:
k += 1
return f
n = factor(200)
print(n)
You need to reset your count (c) after adding to the resulting array.
You should also stop the loop when your factor reaches the square root of the number (or the square of the factor is higher than the number):
Here's a generator version of the prime factor function that does not need to store the prime factors in memory:
def primeFactors(N):
prime = 2
while N >= prime * prime:
power = 0
while N % prime == 0:
power += 1
N //= prime
if power: yield (prime,power)
prime += 1 + (prime&1)
if N>1: yield (N,1)
print(*primeFactors(200)) # (2, 3) (25, 1)
print(*primeFactors(360324)) # (2, 2) (3, 2) (10009, 1)
print(*primeFactors(2485335125)) # (5, 3) (7, 6) (13, 2)
print(*primeFactors(882635521699397)) # (149, 2) (3413, 3)
print(*primeFactors(5196703574764221304787)) # (4733, 1) (101611, 1) (119923, 1) (90104863, 1)
print(*primeFactors(13059300506111507933977974861361)) # (17, 4) (5521, 7)
def factor(N):
f = []
k = 2
while k <= N:
c = 0
if N%k == 0:
while N%k == 0:
b = N/k
N = b
c += 1
f.append([k, c])
else:
k += 1
c = 0 **#You have to reset the counter here..**
return f
n = factor(200)
print(n)

Merge sort in python issue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
def mergeSort(A, l, r):
if l < r:
mid = (l + r) // 2
mergeSort(A, l, mid)
mergeSort(A, mid + 1, r)
merge(A, l, mid, r)
def merge(arr, l, mid, r):
arr1 = []
arr2 = []
for i in range(mid):
arr1.append(arr[i])
for j in range(mid, r):
arr2.append(arr[j])
i = 0
j = 0
k = 0
while (i < len(arr1) and j < len(arr2)):
if arr1[i] < arr2[j]:
arr[k] = arr1[i]
i += 1
else:
arr[k] = arr2[j]
j += 1
k += 1
while i < len(arr1):
arr[k] = arr1[i]
i += 1
k += 1
while j < len(arr2):
arr[k] = arr2[j]
j += 1
k += 1
arr = [2, 9, 7, 6, 1, 8, 4, 3]
mergeSort(arr, 0, 8)
print(arr)
There's a slight mistake somewhere in the code that I'm not able to find
Please try to run this code on your machine with different test cases.
And Let me know what I'm doing wrong here.
I don't know why I'm getting an incorrect answer: [1, 2, 3, 4, 6, 8, 9, 7]
You have problems with indexes. You wrote code in C style.
Just use slices to fix your problem
Change definition (delete for loops for arr1 and arr2) for arr1 and arr2 to :
arr1 = arr[:mid]
arr2 = arr[mid:]
else:
arr[k] = arr2[j]
j += 1
k += 1
Change the place of
k += 1
To this:
else:
arr[k] = arr2[j]
j += 1
k += 1
Or this:
else:
arr[k] = arr2[j]
j += 1
k += 1
There are multiple problems in your code:
you pass the index of the first element to sort and the index once past the last element of the slice, but you wrote the function mergeSort with different semantics as you assume r to be the index to the last element of the slice.
similarly, merge expects the mid argument to be the start of the right half and you pass mid, which would be the index to the last element of the first half in your approach.
in the merge function, arr1 should be initialized with i varying from l to mid, with for i in range(l:mid):
furthermore, k must be initialized to l, not 0.
note that arr1 and arr2 could be initialized from simple slices of arr.
Here is a modified version:
def mergeSort(A, l, r):
if r - l > 1:
mid = (l + r) // 2
mergeSort(A, l, mid)
mergeSort(A, mid, r)
merge(A, l, mid, r)
def merge(arr, l, mid, r):
arr1 = arr[l : mid]
arr2 = arr[mid : r]
i = 0
j = 0
k = l
while (i < len(arr1) and j < len(arr2)):
if arr1[i] <= arr2[j]:
arr[k] = arr1[i]
i += 1
else:
arr[k] = arr2[j]
j += 1
k += 1
while i < len(arr1):
arr[k] = arr1[i]
i += 1
k += 1
while j < len(arr2):
arr[k] = arr2[j]
j += 1
k += 1
arr = [2, 9, 7, 6, 1, 8, 4, 3]
mergeSort(arr, 0, 8)
print(arr)
Output:
[1, 2, 3, 4, 6, 7, 8, 9]

QuickSort User Input Ten or Eight Integers Python

Trying to create a double pivot with user inputs, through recursion, although the recursion can be left out, how would a person get the inputs/ints into the list and then let it sort according to the quicksort formula shown.
def swap(lst, i, j):
if min(i,j) >= 0 and max(i,j) < len(lst) and i != j:
lst[i], lst[j] = lst[j], lst[i]
def dpquicksort(lst, left=0, right=None):
if right is None:
right = len(lst) - 1
if right - left >= 1:
p = min(lst[left], lst[right])
q = max(lst[left], lst[right])
l = left + 1
g = right - 1
k = l
while k <= g:
if lst[k] < p:
swap(lst, k, l)
l += 1
elif lst[k] >= q:
while lst[g] > q and k < g:
g -= 1
swap(lst, k, g)
g -= 1
if lst[k] < p:
swap(lst, k, l)
l += 1
k += 1
l -= 1
g += 1
swap(lst, left, l)
swap(lst, right, g)
dpquicksort(lst, left, l-1)
dpquicksort(lst, l+1, g-1)
dpquicksort(lst, g+1, right)
return right
def quickSortHelper(alist, first, last):
if first<last:
splitpoint= partition(alist, first, last)
quickSortHelper(alist, first, splitpoint-1)
quickSortHelper(alist, splitpoint+1, last)
def quicksort(lst):
dpquicksort(lst, 0, len(lst)-1)
print(lst)
lst = [54,26,93,17,77,31,44,55,20]
#lst = int(input("enter integers: "))
quicksort(lst)
lst = [54,6,93,17,7,1,44,55,20]
#lst = [2, 4, 6, 8, 10, 12, 14, 16, 18]
quicksort(lst)
You can utilise map and int built-in,
>>> lst = list(map(int,input("enter integers: ").split()))
enter integers: 2 3 8 1 3 4 1 8 9 2
>>> lst
[2, 3, 8, 1, 3, 4, 1, 8, 9, 2]
Or list comprehension,
[int(num) for num in input("enter integers: ").split()]
It is up to you, put it top or bottom are both fine. Your code become,
def swap(lst, i, j):
if min(i,j) >= 0 and max(i,j) < len(lst) and i != j:
lst[i], lst[j] = lst[j], lst[i]
def dpquicksort(lst, left=0, right=None):
if right is None:
right = len(lst) - 1
if right - left >= 1:
p = min(lst[left], lst[right])
q = max(lst[left], lst[right])
l = left + 1
g = right - 1
k = l
while k <= g:
if lst[k] < p:
swap(lst, k, l)
l += 1
elif lst[k] >= q:
while lst[g] > q and k < g:
g -= 1
swap(lst, k, g)
g -= 1
if lst[k] < p:
swap(lst, k, l)
l += 1
k += 1
l -= 1
g += 1
swap(lst, left, l)
swap(lst, right, g)
dpquicksort(lst, left, l-1)
dpquicksort(lst, l+1, g-1)
dpquicksort(lst, g+1, right)
return right
def quickSortHelper(alist, first, last):
if first<last:
splitpoint= partition(alist, first, last)
quickSortHelper(alist, first, splitpoint-1)
quickSortHelper(alist, splitpoint+1, last)
def quicksort(lst):
dpquicksort(lst, 0, len(lst)-1)
print(lst)
lst = list(map(int,input("enter integers: ").split()))
quicksort(lst)

finding kth smallest element

I followed the algorithm in the book for this problem. when I print result it is not correct. the algorithm is exactly as in the book
my code
import math
def quickSelect(A, k):
m = A[math.floor(len(A)/2)]
L = [i for i in A if i < m]
E = [i for i in A if i == m]
G = [i for i in A if i > m]
print(L)
print(E)
print(G)
if k <= len(L):
return quickSelect(L, k)
elif k <= (len(E) + len(G)):
return m
else:
return quickSelect(G, k- len(L) - len(E))
result = quickSelect([7, 14, 10, 12, 2, 11, 29, 3, 4], 4)
print(result)
These statements:
L = [i for i in A if i < m] # less than m
E = [i for i in A if i == m] # equal to m
G = [i for i in A if i > m] # greater than m
partition the array into three ranges:
| L1 L2 L3 L4 | E1 | G1 G2 G3
| | |
0 | |
len(L) |
len(L) + len(E)
Your condition for the second range,
elif k <= (len(L) + len(G)):
return m
is wrong. It should be:
elif k <= (len(L) + len(E)):
return m
Node: Instead of using floating-point math, you can just calculate m with Python's integer division: m = A[len(A) // 2]

Magic Squares - Siamese Method

Is it possible to do magic squares with the Siamese/De La Loubere method without using modulo?
I would like to make odd n x n magic squares using it.
Yes, it's possible. Written on Python 3.5:
def siamese_method(n):
assert(n % 2 != 0), 'Square side size should be odd!'
square = [[0 for x in range(n)] for x in range(n)]
x = 0
y = int((n + 1) / 2 - 1)
square[x][y] = 1
for i in range(2, n * n + 1):
x_old = x
y_old = y
if x == 0:
x = n - 1
else:
x -= 1
if y == n - 1:
y = 0
else:
y += 1
while square[x][y] != 0:
if x == n - 1:
x = 0
else:
x = x_old + 1
y = y_old
square[x][y] = i
for j in square:
print(j)
siamese_method(3)
I've got following on output:
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]

Categories

Resources