Creating a Table in Pycharm - python

I'm reading through How to think Like a Scientist. Great book! I'm using Pycharm and I've been stumped on a couple of obstacles. When I try to run:
i = 1
while i <= 6:
print(n * i, '\t',)
i += 1
print()
it only runs as a single line, but I want a table. This code is supposed to create a table where it shows the multiples of a given number. Yet, when I run it on Pycharm it gives the multiples of the number, but in a single line. Any and all assistance would be appreciated!

Python uses indentation to denote blocks of code (such as loops and conditionals). You need to indent the final three lines of code as such to get the loop to work:
i = 1
while i <= 6:
print(n * i, '\t',)
i += 1
print()
You may wish to use a for loop here, which is perhaps a little bit more concise:
for i in range(0,6):
print(n * i, '\t',)
i += 1
print()
You can read a little more about indentation denoting blocks here:
https://docs.python.org/3.5/faq/design.html?highlight=indentation
http://www.secnetix.de/olli/Python/block_indentation.hawk

i = 1
while i <= 6:
print(n * i, '\t',)
i += 1
print()

Related

Is loop "for" prior to "if" statement in Python?

I'm new to a programming language and wanted to start with Python as its the recommendation of most people (as far as i see).
So, im practising on some functions to improve my understanding on loops, and basic statements etc. Though i'm not very good at it yet, i do believe that i'll improve sooner or later.
Here is an example where i'm stuck at:
def L():
List = []
TauS = []
a = 12
for i in range(1,a+1):
if a % i == 0:
List.append(i)
if a % len(List) == 0:
TauS.append(a)
print(List)
print(TauS)
L()
This is the function i want to have and the output is:
[1, 2, 3, 4, 6, 12]
[12]
As i expected.However, the problem is that i want "a" to be a variable instead of a constant.Something like:
def L():
List = []
TauS = []
for a in range(2,20):
for i in range(1,a+1):
if a % i == 0:
List.append(i)
if a % len(List) == 0:
TauS.append(a)
print(List)
print(TauS)
L()
Fails because it seems like for loop is working before the 2nd if statement (if a % len(list)) == 0: TauS.append(a)).I have also tried a "while" loop instead of a "for" loop as:
a = 2
while a <= 20:
for i in range(1,a+1):...(The rest is the same)
It would be a better idea if your help focus on the basic ideas instead of just giving the right function.
Thanks a lot from now!
Regards.
Python uses indention levels to tell whether code is in within a function, loop or condition, the general thing being that if there is a : then all the code indented underneath it is within that statement.
The problem with your code is that the second if statement is on the same indention level as the for loop rather than being on the indention level below the for loop. This means that rather than running in the for loop it runs after it.
So to fix your code all you need to do is select the if statement and press crtl + ] which is pythons keyboard shortcut for indent code section.
edit:
I think what you're asking for is to get all the factors of numbers from 2 to 19 and then print numbers where the number of factors is a factor of that number.
def L():
List = []
TauS = []
for a in range(2,20):
l=[] #this is the list for each individual number
#if i is a factor of a add it to l
for i in range(1,a+1):
if a % i == 0:
l.append(i)
#if length of l is a factor of a add a to TauS
if a % len(l) == 0:
TauS.append(a)
List.append(l)
print(List)
print(TauS)
L()
It fails because of variable scope.
Python uses indention to represent code block. So, here for loop and 2nd if condition has same indention which means they belong to same code block and can access variables defined in the same or the outer code block. "List" & "Taus" in this case.
However, Variable "a" is localize to outer for loop and can be access in the same or inner for loop and cant be access from outside. Similarly variable "i" is specific to inner for loop and cant be access outside of the loops block, not even from outer for loop.
Hope it helps...

How to generate specific combination of numbers in Python

what I'm trying to do is a function for which you give a number and it lists every string of that length that contain numbers in ascending order with the conditions that I cannot have more than 4 time the same number and my number have to be consecutive. If possible, I would like not to list numbers that are anacycle of those already listed.
For example:
fct(5) gives me
"11112
11122
11123
11223 (11222 is omitted)
11233
11234
12223
12234
12345"
Do you think it is better to do this with regex and generate every combination or to increment the numbers in a list while I browse my initial list and modify it ?
Are other languages better to do something like this ?
EDIT : Sorry I think it wasn't enough clear.
I tried at beginning to do something like :
ls = list("1111222233334")
i = -1
while ls[0] == "1":
print("".join(ls))
if int(ls[i]) == int(ls[i-1]) and int(ls[i]) < 9:
ls[i] = str(int(ls[i])+1)
else:
i -= 1
Of course this doesn't work and I think there is too much condition if I go this way, this is why I ask if there is something already done in Python that can list every ascending number of specific length.
We cannot go over 9 so this function does anything if called with 37.
By anacycle I mean something that gives something else if read starting by the end (like "roma" and "amor").
Is it better to generate a list of every number of that length and then delete all those that do not correspond, + delete those that are equivalent to those that are already in ?
I finally decided to do this :
def handlisting(n):
L = [str(i) for i in range (int("1"*n), int(12345679 * (10**(n-8))) + 1)]
reg = "1{1,4}(2{1,4}(3{1,4}(4{1,4}(5{1,4}(6{1,4}(7{1,4}(8{1,4}(9{1,4})?)?)?)?)?)?)?)?\Z"
return list(filter(re.compile(reg).match, L))
I think that I can do better because this one is pretty slow, and it doesn't delete those that are the same than other if read starting by the end (it will return "112234" and "123344", or "11112" and "12222")
EDIT : It goes a little faster with a condition like this :
L = [str(i) for i in range (int("1"*n), int(12345679 * (10**(n-8))) + 1) if \
i%10 >= (i//10)%10 and i%100 >= (i//10)%100 and i%1000 >= (i//10)%1000 and i%10000 >= (i//10)%10000]

Why do I get a 'valueError' despite explicitly returning the expected number of values?

This is merge sort tweaked to count inversions. My code throws an odd error
(I'm implementing algos to learn python 3.x).
In line 11,
in merge_sort first_sorted_half, x = merge_sort(arr[:half])
[Previous line repeated 12 more times] ValueError: not enough values
to unpack (expected 2, got 1)
Even though I explicitly return two values? I'm new to python 3 so I'd like to understand exactly what's going on here, I can't seem to find a similar issue anywhere. A link to python docs for more on this would also be appreciated!
def merge_sort(arr):
if len(arr) <= 1:
return arr
half = int(len(arr)/2)
first_sorted_half, x = merge_sort(arr[:half])
second_sorted_half, y = merge_sort(arr[half:])
merged_halves, z = merge(first_sorted_half, second_sorted_half)
return merged_halves, x + y + z
def merge(first_half, second_half):
n = len(first_half) + len(second_half)
i = 0
j = 0
split_inversions = 0
ans = []
for k in range(n):
if i >= len(first_half):
ans.append(second_half[j])
j += 1
continue
if j >= len(second_half):
ans.append(first_half[i])
i += 1
continue
if first_half[i] > second_half[j]:
ans.append(second_half[j])
j += 1
split_inversions += len(first_half) - i
elif first_half[i] < second_half[j]:
ans.append(first_half[i])
i += 1
return ans, split_inversions
numbers = [3,2,1,4,5,6,8,10,9]
print(merge_sort(numbers))
The error you are getting says that your program executed that recursive call 12 times, and at the end it couldn't unpack the result.
What that means is, python expects you to return two values from merge_sort, because you unpack the result into first_sorted_half and x. However, when you return only arr from the condition len(arr) <=1, there is no value to unpack, only there exists the array.
So how you fix that is returning a value for the base case, like return arr, len(arr).
Whilst ilke444 is right - a bit more clarification is needed. To start: returning data variables is what you need but I do not know much about the len(arr) <=1 , and I am quite new to stackflow, I do not know this feature of Python 3. I specialize in Pygame/ standard packages.
First thing - arr in this "Code Snippet" (If it is) is not defined; and/or will need to be defined. Len stands for length as you know - and uses a quote (' ') to use it.
Like so:
len('arr')
would print:
3
because there are 3 Characters in this set. You are obviously new to python 3 as you said because the syntax is slightly different.
As this probably only solves the first bit - with this info I will leave you with 1 thing more.
Call to print requires a quote (' '),
Lists have [ ] Brackets instead of (),
Dictionaries have {} brackets and variables now require definition either by variable definition or function unless put in quote marks.
Thanks,
Jerry

Python simple loop

I am trying to make a simple loop where it prints the output numbers 0-9 on separate lines. What am I doing wrong? I have looked at the examples on here and they don't really help me. If you could explain where I went wrong that would be very helpful.
def singleline(item):
number = 0
while number < 10:
print(number)
number = number + 1
You've defined a function but you haven't called it. Just add
singleline(1)
to the end of the script.
Try using a for loop with range.
for num in range(10):
print(num)
This is more concise than using a while loop.
Also, if you are using a while loop, I would recommend using number+=1. It is the same as number=number+1, but just looks cleaner.
Firstly remember to call the function at the end of your otherwise you have just executed it singleline(). Also you haven't used the item you put into the parameters.
A better way to write this using a while loop would be.
def singleline():
num = 0
while num < 10:
print(num)
num += num
The += just means add one to of the variable on the left to the variable on the right. For example
a = 1
b = 2
a += b
a would not equal 3 because it adds b to it's original value.
However if you wanted something more efficient you could use this:
for num in range(10):
print(num)
for loops work in the same way as a while loop (take a condition and do content until stopped) but does it for the amount of times set. So in simple terms all this code means is print num plus 1.
Woah, your code is way too complicated -
for x in range (0, 10):
print x
Should work perfectly (python), Good Luck!

while loop won't break,should break when the counter is no longer less than the length of the array

trying to compare items in a and b and return greatest number at each index in list big - result should be [9,14,9,14,15,18,15].doing this for a class, must use while loop and counter
a = [7,12,9,14,15,18,12]
b = [9,14,8,3,15,17,15]
big = []
i = 0
length = len(a)
while i < length:
if a[i] > b[i]:
big.append(a[i])
else:
big.append(b[i])
i = i + 1
print(big)
There is nothing wrong with the code. I just copied it and ran through the IDLE. Output is exactly as you specified
If you run your code directly in the python shell, you will get a SyntaxError.
For more info, see http://bugs.python.org/issue11433
If you save the code down in a file, say test.py, then run python test.py, it will print out the result as expected.
Edit:
This answer is currently having a -1 rating. Before you downvote, can you actually read and try to understand the answer?
This is what I am talking about:

Categories