I'm a newbie to Python and one of our practice examples is in the code below but there is no feedback on what the code is doing. The question in the exercise asks "How many times is P printed out" I've provided the output below.
From what I understand on my own, the length of s is 6 and the range is 0 to 5 but since we are saying "range(len(s))" are we basically asking the loop to run 6 times?
Also, can someone help me understand the print(s[idx % 2])? How does the print statement generate the output shown below? If I were to change it to print(s[ 0:2 ] then I would be given "pypypy" horizontally which is different.
Thank you for the help.
s = "python"
for idx in range(len(s)):
print(s[idx % 2])
Output
p
y
p
y
p
y
Strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. Therefore you can get the character at position 1 (remember that the first character has the position 0) via the following code snippet, e.g:
a = "Hello, World!"
print(a[1]) // e
print(a[2]) // l
Now looking at why your code outputs what it does (second part of your question). Recall that % is the modulo operator.
In the first run, idx = 0. So your statement becomes:
print(s[0 % 2]) = print(s[0]) = 'p' -> first letter of s.
Next idx = 1. So your statement becomes:
print(s[1 % 2]) = print(s[1]) = 'y' -> second letter of s.
Next idx = 2. So your statement becomes:
print(s[2 % 2]) = print(s[0]) = 'p' -> first letter of s.
And so on, 6 times (idx takes values of 0, 1, 2, 3, 4, 5).
P.S. Commenting on your comment regarding setting print(s[ 0:2 ]) - this is known as string slicing (essentially call out a range of characters from the string) - [0:2] means you are starting at index 0 and extend up to but not including index 2, so 'py'.
are we basically asking the loop to run 6 times?
Yes
can someone help me understand the print(s[idx % 2])?
Yes
How does the print statement generate the output shown below?
The % operator is the modulo operator. It gives the remainder of a division. For the range in question, the results are
0 divided by 2 is 0 with a remainder of 0
1 divided by 2 is 0 with a remainder of 1
2 divided by 2 is 1 with a remainder of 0
3 divided by 2 is 1 with a remainder of 1
4 divided by 2 is 2 with a remainder of 0
5 divided by 2 is 2 with a remainder of 1
As you can see, the remainder toggles between 0 and 1.
Indexing the string will thus result in s[0] which is p and s[1] which is y.
Related
can someone explain this function to me?
#from the geeksforgeeks website
def isPalimdrome(str):
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
I dont understand the for loop and the if statement.
A - why is the range from 0 to length of the string divided by 2?
B - what does "str[len(str)-i-1" do?
//sorry, ik I ask stupid questions
To determine if a string is a palindrome, we can split the string in half and compare each letter of each half.
Consider the example
string ABCCBA
the range in the for loop sets this up by only iterating over the first n/2 characters. int(n/2) is used to force an integer (question A)
ex_str = 'ABCCBA'
for s in range(int(len(ex_str)/2)):
print(ex_str[s])
A
B
C
we now have to look at the letters in the other half, CBA, in reverse order
adding an index to our example to visualize this
string ABCCBA
index 012345
to determine if string is a palindrome, we can compare indices 0 to 5, 1 to 4, and 2 to 3
len(str)-i-1 gives us the correct index of the other half for each i (question B)
example:
ex_str = 'ABCCBA'
for s in range(int(len(ex_str)/2)):
print(f'compare index {s} to index {len(ex_str)-s-1}')
print(f"{ex_str[s]} to {ex_str[len(ex_str) - s - 1]}")
compare index 0 to index 5
A to A
compare index 1 to index 4
B to B
compare index 2 to index 3
C to C
for i in range(0, int(len(str)/2)):
Iterate through(go one by one from) 0(because in string first letter's index is 0) to half length of the string.
Why to only half length?
Because in a palindrome you need to compare only half length of string to the other half.
e.g., RADAR. 0=R, 1=A, 2=D, 3=A, 4=R. Number of letters = 5.
int(len(str)/2) will evaluate to 2. So first two letters will be compared with last two letters and middle one is common so will not be compared.
if str[i] != str[len(str)-i-1]:
Now, length of string is 5 but index of letters in string goes from 0 to 4, which is why len(str)-1 (5-1 = 4, i.e., last letter R).
len(str)-1-i Since i is a loop variable, it will be incremented by 1 every time for loop runs. In first run i is 0, in second 1....
The for loop will run two times.
str[i] != str[len(str)-1-i] will be evaluated as-
0 != 4 i.e. R != R FALSE
1 != 3 i.e. A != A FALSE
This code is not very readable and can be simplified as pointed out by others. This also reflects why code readability is important.
1. why is the range from 0 to length of the string divided by 2?
That's because we don't need to iterate all the way through the string but just halfway through it.
2. what does "str[len(str)-i-1]" do?
It returns the ith element from the end ie for a string "noon" when i is 0 it will get str[3] ie n
Easiest way to check palindrome is this
def isPalimdrome(s):
return s == s[::-1]
Reading the string from the beginning is same as reading it reverse.
I have the following problem statement:
Write a function odd_finder(a,b,c,d,e,f,g,h,i,j) which takes 10 integers as inputs and returns the count of positive odd integers. For instance, if the 10 integers inputted by the user are 1,2,3,4,5,-1,-2,-3,-4,0 then output by the function will be 3 (3 positive odd integers: 1,3 and 5).
I wrote this code:
def odd_finder(a,b,c,d,e,f,g,h,i,j):
count = 0
for number in range(10):
if(number % 2 != 0 & number >= 0):
count = count + 1
print(count)
For the example input, my code prints 5 instead of the correct answer of 3. What is wrong with the code? I'm not sure if the issue is with my range or with the operator for evaluating positive integers as number > 0 prints overall count of 0.
There are some issues with the function you have written:
You are taking values a through j as parameter, but not using them, you are just using the values coming from range(10) which will always be 0 through 9 no matter what are the values passed to the function for a through j.
You are combining the conditions using bitwise and operator &, which has higher precedence than !=, and >=, take a look at precedence table
You are comparing against zero number >= 0 which will be true for number=0, but 0 is not an odd integer.
A modified version of the function would look something like this:
def odd_finder(a,b,c,d,e,f,g,h,i,j):
numbers = (a,b,c,d,e,f,g,h,i,j) #Create a sequence to iterate
count = 0
for number in numbers: #range(10):
if(number % 2 != 0 and number > 0):
count = count + 1
print(count)
OUTPUT:
>>> odd_finder(1,2,3,4,5,-1,-2,-3,-4,0)
3
The first issue is fixed by creating a sequence from the values a through j in order to iterate these values. You can then replace range(10) by iterating numbers
The second issue is fixed by replacing bitwise and operator & by logical and operator
The third issue is fixed by using greater than operator > in place of greater than or equal to >=
I am new to the world of Python and programming in general, and today I have faced a problem with augmented assignment. I unfortunately do not understand the code, and what for i in range(multiplier) and answer *= number does. I tried understanding it but I still don't really get the logic behind it. Can somebody please explain?
number = 5
multiplier = 8
answer = 0
for i in range(multiplier):
answer *= number
print(answer)
range([start], stop[, step])
range is a function that takes a number and return a list of number from 0 ... right through to the number you gave it as an argument.
BUT THE KEY TO NOTICE IS THAT IT WILL NEVER INCLUDE THE NUMBER YOU
TOLD IT TO COUNT TO
. Example :
This is an example of giving the function range 1 argument:
>>> # One parameter
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
Here is an example of giving it two arguments where the first argument is telling the function what to start the list it returns at. The second argument is where it should end:
>>> # Two parameters
>>> for i in range(3, 6):
... print(i)
...
3
4
5
Here is an even cooler example where we use the third argument as well. This argument tells the function to count from whatever number you told it to start at, right through to whatever number you told it to stop at (just like the above to examples)... only now, the third argument tells it in what steps to count:
Like count from 2 to 12 but count in 2's:
>>> # Three parameters
>>> for i in range(2, 12, 2):
... print(i)
...
2
4
6
8
10
SO....
the for loop is just iterating through that list of numbers that is given back by the function range
so lets break that for loop in to pseudo code.
***loop***
for i in range(multiplier):
answer *= number
***Pseudo code***
Give me a list of numbers
(not giving it a start value but only a value to end the count at).
The numbers has to be from 0 to multiplier (8).
so range(multiplier) -> range(8) -> [0, 1, 2, 3, 4, 5, 6, 7]
now you have a list
now you ask the compiler to go through that list.
you say : go through that list and everytime you at a new number, give it to me in the for of a variable called i.
then when you have i, you don't use it because i was just trying to loop 8 (multiplier) times... but now take the answer and add to it this (answer * number) ... this will happen 8 times because you loop 8 times
Ploblem:
Bubble sorting is an algorithm that sorts sequences of length N in such a way that two adjacent elements are examined to change their positions. Bubble sorting can be performed N times as shown below.
Compare the first value with the second value and change the position if the first value is greater.
Compares the second value with the third value, and if the second value is greater, it changes its position.
...
Compare the N - 1 and N - values and change the position if the value of N - 1 is greater.
"Supchan" I know the result of bubble sorting, of course. However, since N is very large, it takes a long time to perform the above steps K times. Write a program that will help you to find the intermediate process of bubble sorting.
My Code
def bubble(list):
temp = 0
for i in range(0, len(list)):
for j in range(i+1, len(list)):
if (list[i] > list[j]):
temp = list[i]
list[i] = list[j]
list[j] = temp
return list
numbers = input()
items = [int(num) for num in numbers.split()]
print(bubble(items))
Test Condition
N and K are given in the first line.
The second line gives the status of the first sequence. That is, N integers forming the first sequence are given in turn, with spaces between them.
1 ≤ N ≤ 100,000
1 ≤ K ≤ N
Each term in the sequence is an integer from 1 to 1,000,000,000.
Input & Output
input: 3 1 2 5 4
output: 1 2 3 4 5
The code I wrote seems to work fine. However, the grading of the coding test rejects me.
I can not understand the reason because the reason is not listed. Is there a problem with my code?
Try changing the line
numbers = input()
to
numbers = raw_input()
It could be that the test input might be in the form
1 5 6 4 3
instead of
'1 5 6 4 3'
which might cause error while running using input()
While doing some list comprehension exercises, i accidentally did the code below. This ended up printing True/False for all 16 entries on the list.
threes_and_fives =[x % 3 == 0 or x % 5 == 0 for x in range(16)]
print threes_and_fives
After i played with it i was able to get the outcome that I wanted, where it printed the numbers from that list that are divisible by 3 or 5.
threes_and_fives =[x for x in range(16) if x % 3 == 0 or x % 5 == 0]
print threes_and_fives
My questions is why did the first code evaluated to true or false and the other one didn't? I'm trying to get a grasp of python so the more explanations the better :) Thanks!
What you may be missing is that there is nothing special about relational operators in Python, they are expressions like any others, ones that happen to produce Boolean values. To take some examples:
>>> 1 + 1 == 2
True
>>> 2 + 2 == 5
False
>>> [1 + 1 == 2, 2 + 2 == 5]
[True, False]
A list comprehension simply collects expressions involving elements of an iterable sequence into a list:
>>> [x for x in xrange(5)] # numbers 0 through 4
[0, 1, 2, 3, 4]
>>> [x**2 for x in xrange(5)] # squares of 0 through 4
[0, 1, 4, 9, 16]
Your first expression worked just like that, but with the expression producing Booleans: it told Python to assemble a list of Boolean values corresponding to whether the matching ordinal is divisible by 3 or 5.
What you actually wanted was a list of numbers, filtered by the specified condition. Python list comprehensions support this via an optional if clause, which takes an expression and restricts the resulting list to those items for which the Boolean expression returns a true value. That is why your second expression works correctly.
In the following code:
[x % 3 == 0 or x % 5 == 0 for x in range(16)]
The list comprehension is returning the result of x % 3 == 0 or x % 5 == 0 for every value in range(16), which is a boolean value. For instance, if you set x equal to 0, you can see what is happening at every iteration of the loop:
x = 0
x % 3 == 0 or x % 5 == 0
# True
Hope this helps, and happy FizzBuzzing
In your first code sample, you are putting the value of
x % 3 == 0 or x % 5 == 0
into your list. As that expression is evaluated as true or false, you will end up with boolean values in the list.
In the second example, your condition is the condition for including x in the list, so you get the list of numbers which are divisible by 3 or 5. So, the list comprehension statement has to be read as
Include value x from the set {0,1,...,15} where condition (x is divisible by 3 or 5) is met.
EDIT: Fixed the set according to #user4815162342's comment.
The following line is a condition returning True or False:
x % 3 == 0 or x % 5 == 0
So in your first attempt you have put it in your list
This is simply the allowed expression syntax in Python. For a list comprehension, you need ...
Item to appear in the final list
Source of items
Restrictions
The first example you gave evaluates to a Boolean value (True / False).
The second one says to put the value of x into the list, with the restriction of divisibility.