Explain in English how this code iterates over a number - python

What does this code mean in English? What is actually happening?
[int(n) for n in str(octal)]
It's part of a larger set of code/loop (see below.)
What I understand is that it's taking in a number as the variable input to a function. This part of the code is allowing it to loop over the number. What I need to understand is the specifics of this line of code. int(n), the for loop of n in str(octal). I need to understand it in English so that I can solve the rest of the code issue. (Which I deliberately did not state.) octal is the input variable to the entire function.
for each_number in [int(n) for n in str(octal)]:
print (octal)
print(n)
# Check for each of the permissions values
for value, letter in value_letters:
if value >= value:
print (value, letter)
result += letter
value -= value
print (result)
else:
value -= 1
result += "-"
Print ("else statment", value, letter, result)
print("end of function")
print(" ")
return result

[int(n) for n in str(octal)]
It's a list comprehension. It's usually helpful to read these right-to-left.
str(octal): Cast the variable octal to a string.
for n in str(octal): For every character n in the string:
int(n): Cast the value to an integer.
[...]: Return these results as a list.
So, the full expression returns a list of integers generated by iterating through every character in str(octal) and casting each character as an int.

It's a list comprehension. Let's look at what this code might normally look like:
my_list = []
for n in str(octal):
my_list.append(int(n))
Essentially, the list comprehension condenses this for-loop down into a single line. The statement before the for indicates what will be appended your output list. Then the for section indicates what you're looping over, just like the first line of a regular for-loop.
At a high level, this comprehension is separating the characters (presumably individual numbers) of the variable octal into a list. To do this, it's casting octal into a string so it can iterate over the individual characters, and then converting each character back into an int before putting it into the output list. So if octal = 175 then your output list would be [1, 7, 5]

lst = [int(n) for n in str(octal)]
is the equivalent of:
lst = [] # Define an empty list
# We want every digit of octal, so we need to convert it into a string
for n in str(octal): # For every digit in the octal
lst.append(int(n)) # Add the character converted into an integer to the list

In Python, it's called list comprehension:
You can translate it as:
result = []
for n in str(octal):
result.append(int(n))
So your code above can be written in a procedural way like:
for n in str(octal):
each_number = int(n)
print(octal)
print(n)
# Check for each of the permissions values
for value, letter in value_letters:
if value >= value:
print(value, letter)
result += letter
value -= value
print(result)
else:
value -= 1
result += "-"
print("else statment", value, letter, result)
print("end of function")
print(" ")
return result
Looking at your code I don't see the reason for using list comprehension since 'each_number' is not used anywhere you the code.

Related

how do I capture the first non-zero integer from the back of an integer?

def last_digit(n):
factorials = []
for i in range(1,n + 1):
i = str(i)
i = i[::-1]
for j in i:
if j != 0:
factorials.append(j)
break
For each integer from 1 to some integer n, I am trying to capture the 'first' non-zero integer from the back of each integer.
For example, if we had 18600, then the integer I want is 6.
When I run the above code on paper it works, however when I run it on my IDE, it is not correct, in particular for '10', it captures the zero, but what I thought is happening is I reverse it so it becomes '01'; then the inner for loop will capture the first non-zero.
To achieve this you should first convert the integer 'n' to a string and iterate through it in the reverse order.
Below is the code for demonstrating this.
def last_digit(n):
n=str(n)
rev=n[::-1] # Reversing the string 'n'
for i in rev:
if i!='0' :
print(i)
break
You can first convert the number to string and then do this:
def last_digit(n):
factorials = []
for i in range(1,n + 1):
i = str(i)
factorials.append(i.strip('0')[-1])
return factorials
strip function will remove all the zeros from beginning and end if the string and then using index -1 you can get the last character.

even and uneven letter, TypeError: not all arguments converted during string formatting

def ul(a):
if a %2 == 0:
print(a.upper())
else:
print(a.lower())
ul(input())
I get following error:
TypeError: not all arguments converted during string formatting
I want to write every even letter in uppercase and every uneven letter in lowercase
What I'm doing wrong?
What you are now doing with this function is check whether the input (a string) is divisible by 2. This is not really what you wanted to do and it raises an error because strings are not modulo divisible.
You should better loop through the indices of the input string to fill a second string with upper and lower case letters:
def ul(s):
outstring = ''
for i in range(len(s)): ## For each index of the string
if i%2==0:
outstring += s[i].upper() ## Even indices become upper case
else:
outstring += s[i].lower() ## Odd indices become lower case
print(outstring)
ul(input("Enter a string: "))
You are trying to get mode of string as I understand. You should use len(a).
def ul(a):
if len(a) %2 == 0:
print(a.upper())
else:
print(a.lower())
ul(input())
Try this
def ul(a):
a = a.lower()
if ord(a) %2 == 0:
print(a.upper())
else:
print(a.lower())
if you want user to enter only Alphabets, then try this
def ul(a):
if ord(a) >= 110 and ord(a) < 123:
a = a.lower()
if ord(a) %2 == 0:
print(a.upper())
else:
print(a.lower())
else:
print("Please enter Alphabets only")
Input will give you a string. You want to use the modulo operator %, which is exactly how you usually find the evenness of a number. So, you are on the right track!
What actually happens is that Python interprets your % as the format operator (probably has a fancy name).
number = 2
print("Number %d is this" % number)
>>> Number 2 is this
Strings in Python are immutable, so you can't just change the string that easily.
Try this Replacing every 2nd character in a string , where you construct a new string by adding all the individual characters together.
def ul(word):
new = []
for i in range(len(word)):
if i%2 == 0:
new += word[i].upper()
else:
new += word[i].lower()
print("".join(new))
This will go through the string character by character, transform the individual character based on if it is even or not, and then construct a list "new", that holds all the individual characters. In the end, just join it, so create a new string out of the list.
There are more pythonic ways to do this using list comprehension, but for now this is easier to read and understand.

Is there a problem with my string replacement code?

string = input()
for i in range(len(string)):
if i % 3 == 0:
final = string.replace(string[i], "")
print(final)
I was asked the question: "Given a string, delete all its characters whose indices are divisible by 3."
The answer for the input Python is yton. However, my code gives Pyton.
The code makes sense to me but I'm a beginner. Any help?
The problem is that while you are looping, you are overriding the final variable every time the index is divisible by 3.
Instead, try defining the final variable before you start the loop, and add the letters as you loop over them, and only when they their index is NOT divisible by 3 (thus, ignoring the ones where the index IS divisible by 3).
Something like this should work:
string = input()
final = ""
for i in range(len(string)):
if i % 3 != 0:
final += string[i]
print(final)
In your current code, final is used through each iteration of the loop. It continues updating by replacing one character. In each iteration, final is replaced by a different string with one letter from string removed. After the loop has completed, it effectively only replaced one letter, which in this case is "h".
Use this instead (thanks to Mateen Ulhaq for the idea):
print("".join(x for i, x in enumerate(input()) if i % 3 != 0))
string=input()
final=""
for i in range(len(string)):
if i % 3 != 0:
final+=string[i]
print(final)
In your code, the line final = string.replace(string[i], "") would run like this.
Supposing the input is "hellobaby":
i=0, final="ellobaby"
i=3, final="helobaby"
i=6, final="hellobby"

printing each letter of string same number of times as number of letters

I am trying to make this function so that it prints each letter of the string, the number of times the same of number of letters in the string. so for example if the string was 'hi' , then the output of the function would be:
hh
ii
(each letters on separate lines like above)
however my code only prints 'ii' for the above example and I don't quite know why.
def vertical_strings(string):
"""takes a string and prints each letter on new line repeating each letter for length of word"""
num = len(string)
for char in string:
new = char * num
return new
print(vertical_strings('hi'))
def vertical_strings(string):
"""takes a string and prints each letter on new line repeating each letter for length of word"""
num = len(string)
for char in string:
new = char * num
print new
vertical_strings('hi')
You just have to make minor tweaks in your code
Since you need to print, have the print on each iteration of the code
You're returning the result for last letter only, try using a list of all letters repeated instead, then join the list's elements by a newline (\n) character:
def vertical_strings(string):
num = len(string)
new = []
for char in string:
new.append(char * num)
return '\n'.join(new)
print(vertical_strings('hi'))
Output:
hh
ii
I think that there should also be a provision to capture unique letters only from the given string. My solution here emphasizes with a palindrome mom that there exists two unique character and there should be only two lines of output. Please check it out and give your feedback.
def vertical_strings(string):
return [x*len(string) for x in list(set(string))]
[print(x) for x in vertical_strings('mom')]
Output:
mmm
ooo

using a function to turn a list of strings separated by commas into integers

"The point of this code is to input a list of integers as strings and have the output be a list of integers, thus allowing the user to find the average. I can't seem to understand why it is not working, I keep getting splitting issues"
def is_integer(s):
if s == s.isdigit():
return True
else:
return False
def are_all_integers(strs):
for s in strs.split(","):
if s == s.isdigit:
return True
else:
return False
def strs_to_num(strs):
integers = []
for s in strs:
integers.append(int(s))
return integers
def get_ints():
list_of_integers = []
s = input("Enter some digits: ")
s = s.split()
while (len(s) < 2) and (are_all_integers(s) is False):
s = input("invalid input, try again: ")
for integer in s:
strs_to_num(integer)
list_of_integers.append(integer)
return list_of_integers
def main():
s = get_ints()
avg = sum(s)/len(s)
print(sum(s))
print(len(s))
print("The average of these numbers are", avg)
main()
There are several issues:
1)
If you use descriptive variable names you will find
that the code is easier to read.
You use the name s for:
input string - "4 5 6"
list of strings - ["4","5","6"]
string repr. of int - "4"
list of integers - [4,5,6]
This gets confusing.
2)
You never call the function is_integer(s) so you
can delete it.
3)
The function are_all_integers() tries to split the
list of integer strings. Then it checks if s is equal
to s.isdigit. As s is True (!= '') and s.isdigit (which
has the value "<built-in method isdigit of str object at 0x0547B320>")
is also True, the whole expression is True.
The correct expression would be: if s.isdigit(). You
have to have parenthesis at the end or Python will not
know that you are asking for the value of the function.
Also, the function are_all_integers() returns True for the first item that
is an integer and will not evaluate subsequent strings in the list.
4)
The while loop condition should be OR:ed. Then you must split
the input string to create the list passed to are_all_integers().
5)
The function strs_to_num() can be replaced by builtin function int().
6)
Spend some time learning how to debug your code. At your level this
can be accomplished by working in small steps and printing intermediate
results to the console. Google for help on this and don't bother with
logging or debugging tools just yet.

Categories