Python range() giving the wrong list - python

I am using this little code to generate a weighted modulo-103 checksum.
The problem is that when I run the following code:
def checksum_bar(array):
s = array[0]
s += array[1]
for x in range(2, len(array)):
print x
s += array[x] * x
m = s % 103
I get the following result for x when entering a array of length 10:
1
2
3
4
5
6
7
8
9
10
But when I run the following code (3rd line commented):
def checksum_bar(array):
s = array[0]
#s += array[1]
for x in range(2, len(array)):
print x
s += array[x] * x
m = s % 103
It gives me the result I want, even though I didn't change the iteration:
2
3
4
5
6
7
8
9
10
Am I missing something here? I would like to know if someone can reproduce the same result and some explanation would be very nice too.

The two sets of code provided will give the same result, because the range function is sure to start from 2

Related

usage of continue loop, and or

I'm quite new in Python. I have searched on site but I couldn't find solution for that pease show me if I missed.
I am trying to understand loops and "and" "or" I did some experiment with these elements but I confused.
Bellow code I was expecting code pass the numbers which isn't dividable by 3 or 5 and print rest. But suprisingly It print the numbers which is dividable by 15! (other words which is dividable by 3 and 5)
for x in range(100):
if x % 3 != 0 or x % 5 != 0:
continue
print(x)
output:
0
15
30
45
60
75
90
And this one I was expecting it will pass the number which isn't dividable 3 and 5 But it prints the numbers which is dividable 3 or 5 as I wanted in my first example.
for x in range(100):
if x % 3 != 0 and x % 5 != 0:
continue
print(x)
output:
0
3
5
6
9
10
12
15
18
20
.............
I don't understand what I am missing. I'm aware that I can make it happen with if, elif and else form but I wanted to learn more about "continue" usage. I'd appereciate if you help me.
Thank you!
You may have an easier time understanding what's happening just by walking through the numbers and seeing what your logic does for each number. You have walked into a logic equivalence that can be confusing, and is expressed in De Morgan's Laws. Essentially you can say
(x % 3 != 0 or x % 5 != 0) = !(x % 3 == 0 and x % 5 == 0)
so your first logic test is checking whether a number is divisible by both 3 and 5, which are the multiples of 15. And your second test is
x % 3 != 0 and x % 5 != 0 = !(x % 3 == 0 or x % 5 == 0)
so you are testing whether a number is divisible by either 3 or 5.
The continue keyword will essentially end the current iteration of the loop, and jump directly to the start of the loop to re-evaluate the loop condition (see https://docs.python.org/3.8/tutorial/controlflow.html).
So, in your first block of code, any time x is not divisible by 3 or 5, it will not print the number, meaning the only numbers which are printed are those which are divisible by both 3 and 5.
You can clear up the or logic like this:
for x in range(100):
if x % 3 != 0: # skip 1,2,4,5,7,8,10,11,13,14,16....
continue
if x % 5 != 0: # skip 1,2,3,4,6,7,8,9,11,12,13,14,16...
continue
print(x) # only numbers that pass both checks 0,15,30,...
With this, only 0, 15, 30, ... get through
If you convert it with boolean algebra,
if x % 3 != 0 or x % 5 != 0:
is the same as
if x % 3 == 0 and x % 5 == 0:
which gives the same results (0,15,30,...)

convention range value in python

i can't understand this convention range in python, range(len(s) -1) for representing all elements including the last one. For me makes no sense like when I print all elements the last one is not included in the list. Someone could help me understand this logic?
this>
s = "abccdeffggh"
for i in range(len(s) -1):
print(i)
result this
0
1
2
3
4
5
6
7
8
9
you are trying to print range to compiler you saying like this print numbers greter than 1 and below than 10 to the output not include 1 and 10 compiler only print 2,3,4,5,6,7,8,9 in your case
s = "abccdeffggh"
this s string length must be 11 if you print like this
s = "abccdeffggh"
for i in range(len(s)):
print(i)
you get output as 1,2,3,4,5,6,7,8,9,10 that is the numbers between 0 and 11
but in your code you have subtract -1 from the length then your range is become -1 and 10 then compiler print all numbers between the -1 and 10 it not include -1 and 10
try this code
s = "abccdeffggh"
print(len(s))
print(len(s)-1)
for i in range(len(s)):
print(i)

Python: How to make numeric triangle with recursion

while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

Converting Yes to 1 and No to 0 in python

I have a csv file few columns are as Yes/No's I have tried most of the solutions on stack over flow nothing seems to be working.
sample['colval'] = sample['colval'].apply(lambda x: 0 if x=='N' else 1)
For example, I used the above code on my data. It converted everything to 1's, as in Y to 1 and N to 1.
So many other examples too, all yielded similar results, few resulting in 'None' as output for Y/N.
sample.colval[0:20]
0 N
1 N
2 N
3 N
4 N
5 N
6 N
7 N
8 N
9 N
10 N
11 Y
12 N
13 N
14 N
15 N
16 N
17 N
18 Y
19 N
Name: colval, dtype: object
Please help, Thank you
Found it difficult to repeat given the older version of Python and no access to the original data but your output above suggests whitespace in with the value. Try
sample['colval'] = sample['colval'].apply(lambda x: 0 if x.strip()=='N' else 1)

Creating a triangle using a ragged 2D array

i need to use a ragged 2D array to create a triangle like the one shown,
0 0 0 0 0 0
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
def triangle(n):
for i in range(n):
tri = n
for j in range(n-i):
tri = tri * 10 - n
print tri
i have tried this but it returns,
444445
44445
4445
445
45
Since you made atleast some effort, here it is one way to do it
We only need to iterate over the loop once. Since the index are int, we need to convert to str. Also, they start at 0 so either you iterate from n+1 or use i+1 to print so you get your expected output. You can then multiply how many times you want to print the numbers which is converted to string.
def triangle(n):
for i in range(n):
print (str(i+1) + " ") * (n - i)
Demo

Categories

Resources