Trying to find float variables in a list with recursion - python

I'm trying to write a program that goes through a list using recursion that counts how many float variables are in the list.
def recFloatCount(lst):
string = ''
if len(lst) <= 0:
return
else:
if type(lst[0]) == float:
string = string + str(lst[0])
recFloatCount(lst[1:])
print(len(string))
The way this is supposed to work is that the program will go though the list, add each float to string, then print the length of string. However, when I run the program using
recFloatCount([1, 2.0, 3])
it returns
0
3
0
How can I get this so it just prints 1?

This task is quite a bad place to use recursion. But lets assume you really need to
variable string being created "locally" for every function run. So, its empty while running code for 1 and 3. If you need to count floats, string is bad container. You should use integer and pass it down to next calls, so function should accept list and counter state.

Related

how to reverse string using lists python

I found this piece of code from a related question about reversing strings in python, but can someone please interpret it in plain English? Please note that I am still new to python and only learnt how to use while loops and functions yesterday :/ so I cant really put this into words myself cause my understanding isn't quite there yet.
anyways here is the code:
def reverse_string(string):
new_strings = []
index = len(string)
while index:
index -= 1
new_strings.append(string[index])
return ''.join(new_strings)
print(reverse_string('hello'))
Surely by knowing what it does, you can figure the code. In the while loop, the index value starts from the end of the string and counts down to 0. In each step, it adds that character (again, starting from the end) to the end of the list it is building. Finally, it combines the list into a string.
So, given 'abcd', the list gets built:
'abcd' #3 -> ['d']
'abcd' #2 -> ['d','c']
'abcd' #1 -> ['d','c','b']
'abcd' #0 -> ['d','c','b','a']
Well basically, the get the length of the string with the len method. Which will return you an integer value representing how long that string is.
They then use the length of this string and effectively iterate down to zero in a while loop. Using the -= operator.
Each iteration (meaning each time around the loop) it will take away from length until it reaches zero.
So lets use hello as an example input and go through this together.
reverse_string('hello') is how we would call the method, done in the print statement of your code.
We then enter the function and perform these steps:
We create a new empty array called new_strings.
We find the length of the initial string hello which returns us 5. Meaning that now index is equal to 5.
We create a while loop that keeps on going until index is no more using while(index): - a while loop like this treats a 0 value as falsy and will terminate upon reaching this. Therefore when index is 0 the loop will stop.
The first line of this loop performs index -= 1 which is the same as writing index = index - 1 so the very first loop through we get index = 5 - 1 and then now index is equal to 4.
Because Python then lets us access the character of a string using string[index] (and because this works from 0 -> n) performing hello[4] will in fact give us the character o.
We also append this character to the array new_strings meaning that as we go through the iterations to reach zero it will add each character backwards to this array giving us ['o', 'l', 'l', 'e', 'h']
Since index is now zero we leave the loop and perform a join operation on the array to yet again create a string. The command ''.join(new_strings) means that we wish to join the array we previously had without a separator. If we had done '#'.join(new_strings) we instead would have gotten o#l#l#e#h instead of olleh.
I hope this answer gives you some clarity.
Sure, It is very simple program. You should reffer string methods and string indexing in python to get clear idea. Let me explain this in deatial.
print(reverse_string('hello'))//The print function is calling another function
reverse_string and passing argument"hello".
def reverse_string(string):// The argument "hello" is stored in the variable
string in reverse_string function.
**new_strings = []** // created a new empty list
**index = len(string)** // len function returns the length of the argument
passed to the function. len("hello")=5 and assigned
to index. index=5.
while index: // while loop exicute until the condition get false .In this
example when index =0.in string the indexing start from 0 .For
example.
string[0]=h,string[1]=e,string[2]=l,string[3]=l,string[4]=o.
**index -= 1** //Note the last letter 'o' is in string[4] and the len
function returned 5 so we need to decrement index variable
to 4 so that it will pointing to string[4]=o
new_strings.append(string[index]) // append string[4] that is o and so on ...
return ''.join(new_strings)

Python - Need help understanding () vs [] when used with length

I'm new to Python and I'm messing around with this and I don't really know why when I change the brackets to parenthesis I get an error, or why I can't just use len(text - 1).
I'm looking at this code:
def reverse(text):
result = ""
length = len(text)
for i in text:
result += text[length - 1]
length -= 1
return result
Any help with understanding this is greatly appreciated!
Thanks!
You can't use text - 1 because that doesn't make sense; you cannot take 1 from a string.
Now, as for len(...) this is a function so has () for the call rather than []. You pass it the thing you want the length of.
text[length - 1] is indexing into the string, at a position, and follows the list syntax for indexing or sub-scripting.
When you use len(text - 1) you try to subtract int (1) from str (text). It is insupported operation in python (and moreover, impossible). To get a part of string you need you must use text[length - 1].
Python Parentheses
Parentheses play many different roles in Python these are some of the main roles they play:
The mathematical role:
Python parentheses act like parentheses in math as they are at the top of the Python Priority Precedence
This means that this:
>>> 3 + 4 * 2
returns:
12
Whereas with parentheses:
>>> (3 + 4) * 2
returns:
14
But that's not all, their priority also expands to Boolean expressions:
for example:
False and False or True and True
evaluates to True as and is executed before or. However, if you add some parentheses:
False and (False or True) and True
It evaluates to False as the or is executed before the and
Tuple
In python, when you put something in a tuple you use () notation.
Functions
When you declare or call a function you always need to add the parentheses after the function name. Think of them as a basket to put the arguments in. If you forget them the Python interpreter will think that you are calling a variable for example:
list
This is a variable called list and does nothing special
list() #Empty basket
This, however, is a call to a function as there is a "basket"
Square Brackets
Square Brackets also have quite a few roles:
Lists
In python, you use square brackets if you want to declare a list instead of a tuple.
List comprehension
List comprehension is actually pretty complicated so read this for more information but just know that it uses square brackets
Looking up
The main use of square brackets is to look up a value inside a list, tuple, or dictionary. Think of it like the google search bar: you write what you want and it tells you what it has. For example:
tuple = (2, 4)
if you want to get 4 you will need to look up the 2nd value of the tuple:
tuple[1] #The first value is 0
Slicing
Slicing is simply the idea of taking only certain parts of a list (or tuple, dictionary or even string). Here is an explanation by Greg Hewgill (https://stackoverflow.com/a/509295/7541446):
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step
The key point to remember is that the :end value represents the first
value that is not in the selected slice. So, the difference beween end
and start is the number of elements selected (if step is 1, the
default).
The other feature is that start or end may be a negative number, which
means it counts from the end of the array instead of the beginning.
So:
a[-1] # last item in the array a[-2:] # last two items in the
array a[:-2] # everything except the last two items
Python is kind to the programmer if there are fewer items than you ask
for. For example, if you ask for a[:-2] and a only contains one
element, you get an empty list instead of an error. Sometimes you
would prefer the error, so you have to be aware that this may happen.
I hope this provided useful insight to explaining the difference between parentheses and square brackets.
This means that in your question len() is a function where you are putting text inside the basket. However, when you call text[length-1] you are looking up the value at position length-1
The python builtin function len() returns the length in numbers of the object in argument e.g
temp = [1, 2, 3, 4]
length = len(temp)
then the len() will return 4 in this case. but if someone write
length = len(temp-1)
then
temp-1
is not a valid object, therefor you cannot use it.
The reason you can't do len(text-1) is because text is a string type you are trying to reverse, and being a string you cannot combine it with numbers(unless they are a string, but thats a different story) without getting an error. Therefore you do len(text)-1 because len(text) would equal the length of whatever the text is(lets say four), and then you can subtract 1 from 4 because 4 is an integer.
The reason you need brackets and not parentheses when you are doing text[length-1] is because in python trying to get a single value out of a string requires the use of string[] and putting a position in the string inside the []. You use partakes to call functions like print(string) or len(text), so putting text(length-1) would create an error that basically says the program doesn't have a function named "text" and it doesn't know what to do.
Hope this helps. Tell me if you have any more questions.

TypeError : string indices must be integers

I've returned to Python after a few years doing C code and I'm a little confused while training myself to get my Python coding habits back.
I've tried to run this little, very simple, piece of code but I keep getting a TypeError as described in the title. I've searched a lot but cannot figure out what is the problem with this :
def toLower(pStr):
i = 0
for i in pStr:
if ord(pStr[i]) >= 65 and ord(pStr[i]) <= 90:
pStr[i] = chr(ord(pStr[i])+28)
return pStr
testStr = "TEST STRING"
print(toLower(testStr))
Considering that i is an integer, I don't understand why I get this error. Maybe I think too much like i'm doing C IDK.
You are iterating over the string, so each i is bound to a single character, not an integer. That's because Python for loops are Foreach constructs, unlike C.
Just use that character directly, no need to index back into the string. Python strings are also immutable, so you can't replace characters in the string object. Build a new object:
def toLower(pStr):
output = []
for char in pStr:
if ord(char) >= 65 and ord(char) <= 90:
char = chr(ord(char)+28))
output.append(char)
return ''.join(output)
If you must generate an index for something, you'd generally use either the range() type to produce those for you, or use enumerate() to produce both an index and the value itself in a loop.
Also, note you don't need to set the for loop target name to a default before the loop unless you need to handle the case where the loop iterable is empty and you expect to use the target name after the loop. In other words, your i = 0 is entirely redundant.

codecademy Practice Makes Perfect digit_sum

The purpose is Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number's digits.
For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4.
(Assume that the number you are given will always be positive.)
https://www.codecademy.com/zh/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#
Your function fails on digit_sum(1000). It returns 12 when it should return 1.
If I put the dig=[] upper on the def digit_sum, the course occurred alarm that "digit_sum(1000) result is 12 instead of 1" , but I ran this program on my local notepad+powershell, it ok , the result is right.
after that I put the dig=[] into the first line of function , then it worked normally .
I didn't get 2 points....
What's the difference between "dig=[]" inside/outside the function
if the "dig=[]" outside the function is wrong , why I can ran it successfully on my local....?
Thanks for guys to help me......
dig=[]
def digit_sum(n):
u=str(n)
for i in u:
dig.append(i)
s=0
for number in dig:
int(number)
s=s+int(number)
return s
So the difference between inside/outside is locality. When you put dig outside, you create a global list. From there, you're constantly appending to that- the list is never cleared! So if I run digit_sum(1234), I properly get 10. If I immediately thereafter run digit_sum(1000), dig==['1','2','3','4','1','0','0','0'] which will then add all those and mess up.
If you do dig = [] inside the function, it creates a new, local list - it isn't being changed each time, it's a new empty list for each rotation.
The reason you're getting it correctly sometimes is because the function has side effects, so order of calling and history of calling matters. Try to avoid side effects of functions- either don't alter a list, or copy the list>alter that copy>return the copy if you want to assign the new list (or just work with the new list.)
def digit_sum(n):
n = str(n)
total = 0
for i in n:
total += int(i)
return total
Something like :
def digit_sum(n):
dig=0 # this is the result os the sum
number=str(n) #transform the number into string so we can iterate
for i in range(len(number)):
dig=dig+int(number[i]) #transform the char to int
return dig #return the sum
I take the number (eg 123) and I transform it to a string so I can get the length of the string (the number of digit). Then I simply add them (after transforming them to integers) and return the result
dig=[] means you declare an array variable which is not what you want here. If it is declared in the function it means that when the function ends, the variable "disappeared", you won't be able to call it back. It'll only exist IN the function. If it is before the function, the variable exists to the end of your program.
Your aptenpt isn't correct. You want to populate your array with the number THEN sum them. In fact when you assign a number to your array dig you are summing then. For exemple 123 will sum : 1 then 1+2 then 1+2+3
The previous answer is all right.
Just to focuse your attention so that you could avoid mistakes in the future:
When you write:
u=str(n)
for i in u:
dig.append(i)
you don't append the digits of the number to the dig. Instead you add digits 0, 1 ,2 ,3 .. so on. Exactly them however the number may be. Because the For Loop iterates from the beginning to the end of a string, a list etc. and the variable after the word For is just a counter - starting from 0 and ending at the end of the object.
Tha is why the answer of Hearner is right:
the number[i] 's are summed not the i's.
for i in range(len(number)):
dig=dig+int(number[i])

Why cant I hard code in the values that are in the range of the for statement?

I do not understand how the following code works in the function:
for i in range(len(s)-len(sub)+1):
if sub == s[i:i+len(sub)]:
Why cant I just pass range(4) for it to work?
write a function that takes two string parameters called 'sub' and 's' and returns the number of times sub occurs as a contiguous substring of s
s= "nickdick"
sub= "ick"
def function(sub,s):
count = 0
for i in range(len(s)-len(sub)+1):
if sub == s[i:i+len(sub)]:
count +=1
print(count)
return count
You can use 4 and it would be valid code if len(s)-len(sub)+1 happened to be 4 for those strings. However, the purpose of writing it using len is so that if you decide to change s or sub, the code still functions and you don't have to go through and manually change the "magic constant" 4.

Categories

Resources