Convert c++ code to python,with operators? - python

how would i convert the following code to python?
for (int i = 1; i <= 50; i++)
im not sure the ++ operator exists in python so im having a little bit of a hard time with it.

i = 1
while i <= 50:
# your code here
i += 1
Or
for i in range(1, 51):
pass
range()'s upper bound is exclusive.

that i++ is only a way of displaying i = i + 1.. dont hang around it too much if there is other way..
i = 1
while i <= 50:
print(i)
i += 1 # or i = i + 1 or what ever display that produce the same result

First off, what are you trying to accomplish? Are you trying to write a converter? Or do you need help with Python? In any case, to answer your question, in order to do a for loop in Python, all you have to do is this:
for i in range(6):
print(i)
As per w3schools documentation, the parameters for the range() function are as follows:
range(start, stop, step)
With start being the start number, stop being the number to end at, and step being the number increase/decrease every iteration.
I'm not too experienced with Python. I'm sure that there is a built-in iterator function that allows you to do some enhanced-for-loop trickery.

This loop begins with i = 1 and the last iteration is when i = 50, so you can reproduce this in Python using:
for i in range(1, 51):
print(i)
(if for some reason, you are stuck using Python 2, consider using xrange instead of range)

Related

Python bubble sort breaks with large numbers only

Im trying to create a bubble sort test algorithm that generates x amount of random integers and outputs to console and a text file. The number of numbers created as well as the max value for the random integers is determined by the variable bigsize. The code seems to work up to around when big size is ~2300, sometimes its more and sometimes it's less. I can always get 2000 to work though.
Edit: Also worth noting, it seems that the code breaks during the sorting process, as I get get a file to output unsorted numbers with no issues.
import random
import sys
bigsize = 2000
def main():
sys.setrecursionlimit(7000)
array = create_list()
print_array(array)
bubble_sort(array)
display_out(array)
def create_list():
array = [0] * bigsize
for x in range(bigsize):
array[x] = random.randint(0, bigsize)
return array
def bubble_sort(array):
increment = 0
buffer = 0
for x in range(len(array) - 1):
if (array[increment + 1] <= array[increment]):
buffer = array[increment + 1]
array[increment + 1] = array[increment]
array[increment] = buffer
increment = increment + 1
increment = 0
for x in range(len(array) - 1):
if (array[increment + 1] >= array[increment]):
increment = increment + 1
elif (array[increment + 1] < array[increment]):
bubble_sort(array)
def display_out(array):
for x in range(bigsize):
print(array[x])
main()
You have a dysfunctional sort. First and foremost, there is nothing useful about your recursion: you don't reduce the task -- you simply use recursion in place of the sort's outer loop. At that, you have implemented it incorrectly. I strongly recommend that you get more practice with the more basic skills of programming before you tackle recursion.
The first (non-)problem is a simple inefficiency: your loop has x as the index, but the loop body ignores x, while it maintains increment with the same value. There is no reason to have two separate variables. You can see how this is used in almost any bubble sort on the web:
for pos in range(len(array) - 1):
if array[pos+1] < array[pos]:
# switch the elements
You have a similar inefficiency in the second loop:
increment = 0
for x in range(len(array) - 1):
if (array[increment + 1] >= array[increment]):
increment = increment + 1
Again, you ignore x and maintain increment at the same value ... up until you find elements out of order:
elif (array[increment + 1] < array[increment]):
bubble_sort(array)
When you do so, you recur, but without altering increment. When you return from this recursion, the array must be properly sorted (assuming that the recursion logic is correct), and then you continue with this loop, iterating through the now-sorted array, ensuring up to bigsize times that the array is in order.
This entire loop is silly: if you simply set a flag when you make a switch in the first loop, you'll know whether or not you need to sort again. You'll do one extra iteration, but that doesn't affect the time complexity.
For instance:
done = True
for pos in range(len(array) - 1):
if array[pos+1] < array[pos]:
array[pos], array[pos+1] = array[pos+1], array[pos]
# Replace the second loop entirely
if not done:
bubble_sort(array)
I strongly recommend that you check the operation of your program by properly tracing the results. First, however, clean up the logic. Remove (for now) the superfluous code that writes to files, put in some basic tracing print statements, and study existing bubble sorts to see where you're making this all too "wordy". In fact, remove the recursion and simply repeat the sorting until done.
When I try this with bigsize=5000, it recurs to 3818 levels and quits. I'll leave the tracing up to you, if the problem is still there once you've cleaned up the program. There's not much point to fixing the "silent death" until you tighten the logic and trace the operation, so that you know you're fixing an otherwise working program. The current code does not "Make it easy for others to help you", as the posting guidelines say.

For Loop - Range - Python - Question on the increment logic

I am trying to convert the below for loop to Python.
for (i = 5; i < n; i = i*5):
I am not sure how to make use of the Range function when i want the i value to be set to the multiple of 5. For example, 1st time I want the i to be 5, then followed by 25, then followed by 125 and it should go on.
The following is what i have tried:
i = 5
for i in range (i, n+1, i*5)
The problem with the above being, the value of i getting incremented by 25, making it to 30 whereas i want the i to be 25 in the second iteration. It is pretty easy when using the while loop. But I am seeing if there is a way to implement the same in the for loop. Please help. Thanks in advance.
I am not sure how to make use of the Range function when i want the i value to be set to the multiple of 5
It will not work that way. range can only create arithmetic sequences; multiplying every time creates a geometric sequence.
What you can do is take advantage of the fact that the i values are successive powers of 5; so make a loop over the desired exponent values, and compute i inside the loop:
# Computing the `limit` in terms of `n` is left as an exercise.
# Just in case you were already computing `n` in terms of an existing `limit`,
# in which case you could just use it directly ;)
for j in range(limit):
i = 5**j
There is a theorem in computer science that states that any "C-style" for loop can be transformed into an equivalent while loop. This is one of those cases where the transformation is desirable:
i = 5
while i < n:
# Loop body goes here
i *= 5
You can hide the loop logic behind a generator:
def multrange(start, stop, ratstep):
i = start
while i < stop:
yield i
i *= ratstep
list(multrange(5, 10000, 5))
#[5, 25, 125, 625, 3125]
You can define your own range function using yield!
def range(i, j, k):
while i * k < j:
i *= k
yield i
for i in range(5, 2000, 5):
print(i)
Output:
25
125
625
Most Python programmers would just use a while loop:
i = 5
while i < n:
....
i = i * 5
If you really, really want a for loop:
import itertools
for i in itertools.takewhile(lambda x: x < n, (5 ** i for i in itertools.count(1))):
... whatever ...

Using a For loop in Python to add up all un-even increments between 3-27?

I am trying to use range() to write a for loop that starts at three and adds up all non-even increments of 3 less than 30. It's supposed to print 75. Here is my code:
for i in range(3,30,3):
sumw=0
if (i%2) != 0:
sumw += i
print(sumw)
^^This is what I have, but it only returns the numbers that are supposed to be added.
Also if you could show me how to do the same thing using a while loop, that would be amazing.
The solution is relatively simple once you realise that the indentation of the final line is such that it prints the running sum after every loop, and that the accumulator is reset inside the loop. What you need to do is stop resetting and then print it once the loop is finished:
sumw = 0
for i in range(3,30,3):
if i % 2 != 0:
sumw += i
print(sumw)
As to using a while loop, the following two are equivalent but I would still maintain that the first is better:
for i in range(3,30,3):
doSomethingWith(i)
i = 3
while i < 30:
doSomethingWith(i)
i += 3
A reasonable general rule is to use the former when you know everything about the loop itself beforehand, that latter when things within the loop may affect how the loop terminates.
And, of course, a more pythonic way to get the sum would be by understanding that odd numbers starting at three can be achieved by adding six rather than three, and using the stuff already built in to Python (the sum function in this case):
sumw = sum(range(3, 30, 6)) # 3, 9, 15, 21, 27.
Using the more expressive parts of Python are a good way to avoid problems such as the one in your original code.
You are close. Your problem is you keep resetting sumw to 0 within the for loop. Try this:
sumw = 0
for i in range(3, 30, 3):
if (i%2) != 0:
sumw += i
print(sumw)
This should print
75
Using a while loop is also trivial:
i = 3
sum = 0
while i < 30:
if (i%2) != 0:
sumw += i
i += 3
As a side note, you can omit the != 0 check and simply write
if i % 2:
Because any non-zero numeric value is logically equivalent to True.
Finally, for future reference, you could have solved the problem in a single line using a generator expression:
>>> print(sum(i for i in range(3, 30, 3) if i % 2))
75

SyntaxError: invalid syntax 11, 7, \t\t\tj++\n

I am not so proficient in python. I had this code in a practice coding. Since it is a golf code problem, i thought of trying python as i have some knowledge about it.
This is my program
Hack sequence of IndiaHacks-2014 if given as below
Hi = 2014*Hi-1 + 69*Hi-2 for (i>2)
Hi = 1 for (i<=2)
Given n, you need to find nth term of Hack sequence
I have used the following code
T = input()
for i in range(T):
N = int(input())
if N <= 2:
print 1
else :
a = [1,1]
j=2
while j < N :
a.append((2014 * a[j-1]) + (69 * a[j-2]))
j++
print a[N-1]
But i get the following error
SyntaxError:
invalid syntax
11, 7, \t\t\tj++\n
Can anyone please tell me what is wrong with this code and why am I getting this error?
Use j += 1 instead of j++. There is no ++ operator in python.
OR in this case simply don't use manually incremented loop variable:
T = input()
# I'm not sure about this part of your code:
# (indentation and the expected value of T)
for i in range(T):
N = int(input())
# To solve this problem you don't have to populate an array,
# you always need only the last two items:
prev2, prev1 = 1, 1
# We could omit this "if" check because the range(N-2) expression
# generates nothing when the input parameter is zero or less,
# that is: when N <= 2.
if N > 2:
# Note: in case of python3 use range(), in case of python2 use xrange()
for _ in range(N-2):
new = (2014 * prev1) + (69 * prev2)
prev2, prev1 = prev1, new
print prev1
To solve this problem you don't need an array but even if you needed an array you could run the j loop variable from 2 to N-1 with for j in range(2, N):. Note that in python you could simply use array[-1] and array[-2] to address the last two items of the array instead of calculating the absolute index (like array[N-1]). Python arrays can be indexed with a negative number relative to the end of the array.
There is no j++ in python. Use j += 1.

Writing a function to find a triangular number in python 2.7

I couldn't find an answer by searching and I've been working on this for two days and am stumped. I think I am just confused on the math. I am trying to write a function that finds the first n triangular numbers.
def formula(n):
i = 1
while i <= n:
print i, '\t', n * (n + 1)/ 2
i += 1
print
So for example if I type in formula(5) it would look like this:
1 1
2 3
3 6
4 10
5 15
I got how to make a table going from 1 through whatever number I choose n.. but I can't figure out how to make the second part equal the formula I typed in which would be n*(n+1)/2. What is the logic going through this? Everytime I type in formula(5) for example the loop goes from 1-5 but returns the same exact answer in the right hand column all the way down which would be 15. I can't make it to where it would start at 1, 3, 6 etc on the right hand side.
The comment that observed that you are computing n * (n + 1) / 2 instead of i * (i + 1) / 2 is correct. You can also get rid of having to do a multiplication and division at each step by observing that the i-th triangle number is simply the sum of the integers from 1 to i, so at each step you just have to add i to the previous triangle number. Code below:
def formula(n):
ith_sum = 0
for i in xrange(1, n+1):
ith_sum += i
print i, '\t', ith_sum
I had completely forgotten about triangular numbers, thank you for the question! I am glad you now know the correct solution. I was curious if it could be done a different way:
def triangular(number):
return number + triangular(number-1) if number else 0
print triangular(5)
If you fancy a challenge, you could try and work this out. A print statement here and there would help you spot what is happening.
This is a simple solution that worked for me
def print_triangular_numbers(n):
for i in range(n+1):
print(i, int(i * (i + 1)/ 2))
print_triangular_numbers(5)
This is not the answer to this question. So delete it as soon as you read it.
It is the answer for printing
#
##
###
####
#####
######
on the console.
Follwing is the code for it :
var strng="";
for (var i=1; i<7; i++)
{
for (var j=1; j<=i; j++)
{
strng=strng+"#";
}
strng=strng+"\n";
}
console.log(strng);

Categories

Resources