No Count function on Python on my Raspberry Pi - python

When I try to use the 'list.count' function on my raspberry Pi it comes up with
Name Error: name 'count' is not defined
Is there any thing I can do about it? Thank you in advance for any help. I am using Python. I am just starting out with Python and in my tutorial it states
>>>count(seq,'a')
With 'seq' being a sequence of letters that I entered earlier. I expect it is meant to count the number of 'a's in the sequence.453
Thank you all very much for your quick responses and answers, I have now fixed the problem. This was my first ever online question that I asked so thank you again. The second answer by Markus Unterwaditzer finally solved the problem with 'seq.count('a')'
Also thanks to DSM for finding the tutorial and explaining why I had my problem. Everything works now and I am back to learning my first computer language.

Ah. The magic in the tutorial is in the
from string import *
line, which is bad practice. It imports everything from the string module into scope, including the function string.count:
>>> print string.count.__doc__
count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
count is also a method of strings, so you can write
>>> 'aaa'.count('a')
3
which is generally preferred. In modern Python, the string module doesn't even have a count function.

I expect it is meant to count the number of 'a's in the sequence
Depending on what list is, that's probably not the correct syntax. If list is a string you can do this:
>>>a = "hello"
>>>a.count('h')
1
>>>a.count('l')
2
Works the same for a "list":
>>>a = ['h','e','l','l','o']
>>>a.count('l')
2

>>> seq = ['a', 'b', 'c', 'a']
>>> seq.count('a')
2
>>> type(seq) is list # the reason it's mentioned as list.count
True
>>> list.count(seq, 'a') # the same thing, but nobody does it like that
2

Related

Why can a list in Python be used with the increment assignment operator and a string?

This isn't so much an "I can't get something to work" question as an, "I don't understand what's going on under the hood," question.
I'm learning Python and found that a list can use the increment augmented assignment operator with a string. Example:
listvar = []
listvar += 'asdf'
will result in listvar being
['a', 's', 'd', 'f']
Like it iterated over it and appended each element, while doing it with
listvar = listvar + 'asdf'
gives an expected error.
I read that the increment augmented assignment operator keeps a new object from being created with mutable objects, versus self=self+thing, and I noticed the working example gives an error for any object that isn't iterable (e.g. an integer), but that's where my understanding of differences ends.
What is happening when the augmented assignment operator is used in this context?
Python version is 3.9 if that matters.
edit: Tim thoroughly answered my question, but just in case anyone else comes along with a similar question, the accepted answer to this question about differences between .append() and .extend() also adds more details.
list += x is basically the same as list.extend(x). It expects to receive a sequence, not a single item. You have given it a sequence, but when a string is treated as a sequence, it is a series of one-character substrings.
To add a single item, you need to use
listvar.append('asdf')

Stuck with a simple code

So i have this code:
print("immutable"[-5:][:3]==9)
(i'm pretty new to coding in python 3 and i understand what my code is suppoused to do or rather what i'm trying to do which is to count the lengt of the word "immutable")
But what i can't figure out is how or rather why the output is "False".
I've even tried messing around with that code taking in len(9), or ==[9], changing the number etc. those times i gotten an error i understod why but i just can't get my head around why i get "False", the reason i can't wrap my head around it might as well just be because of me staring myself blind at this code but i would like any kinds of help i can get since right now i'm stuck.
What you are looking for is len():
print(len("immutable") == 9)
which will output:
True
Why does this work?
Well, first take a look at the documentation for len():
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
So, to give some examples using len():
>>> len("hello")
5
>>> len("fish")
4
>>> len("abc123")
6
>>> len("immutable")
9
What the code is doing is comparing whether the length of the string: "immutable" is equal to (==) 9. Simple as that!
Hopefully you understand how to do it now!

Python Regex return both results when 2 conditions set which partially satisfy one another WITHOUT IF statements nor Test groups and NOT AS A TUPLE

I'm going to have quite a few questions about regex in the coming days. Out of 10 challenges I gave myself over the past 5 days, I managed to solve 6.
I'm hoping the following isn't simple and embarrassing, but what I'm trying to do use re.findall to return results for both conditions even though the condition for set 2 may have already partially been satisfied by set 1.
Example (Problem):
>>> str = 'ab1cd2efg1hij2k'
>>> re.findall('ab1cd|ab', str)
['ab1cd']
>>> re.findall('ab|ab1cd', str)
['ab']
So notice that depending on whichever comes first in the OR statement determines what the single element of the array is. What I want is to be able to return both for a 2 element array and preferably not a Tuple. The readings I've done on regex ANDing have focused on making regexes match 2 different strings as opposed to returning multiple results that may mutually satisfy one another partially. Below is what I desire.
Desired Output:
>>> str = 'ab1cd2efg1hij2k'
>>> re.findall('{SOMETHING_THAT_RETURNS_BOTH}', str)
['ab', 'ab1cd']
The closest I've gotten is the following:
>>> re.findall('ab|[\S]+?(?=2e)', str)
['ab', '1cd']
>>> re.findall('ab|[\S]+(?=2e)', str)
['ab', '1cd']
but the second capture group ignores ab. Is there a directive in regex to say restart from the beginning? (?:^) seems to work the same as a ^ and using it in several ways didn't help thus far. Please note I DO NOT want to use regex IF statements nor test to see if a previous group matched just yet because I'm not quite ready to learn those methods before forming a more solid foundation for the things I don't yet know.
Thanks so much.
If you can relax tuple requirement then following regex with 2 independent lookaheads is needed due to your requirement of capturing overlapping text:
>>> print re.search(r'(?=(ab1cd))(?=(ab))', str).groups()
('ab1cd', 'ab')
Both lookaheads have a capturing group thus giving us required output.
You can also use findall:
>>> print re.findall(r'(?=(ab1cd))(?=(ab))', str)[0]
('ab1cd', 'ab')
Looking at the desired output the regex pattern shouldn't really require any lookaheads:
str = 'ab1cd2efg1hij2k1cd'
res = re.findall(r'((ab)?1cd)', str)
[list(row) for row in res][0]
The ? Quantifier — Matches between zero and one times, as many times
as possible, giving back as needed (greedy).
Result:
['ab1cd', 'ab']

Python.Issues with indexing- running a sequence of elements backwards

I am using Python 3.4.1. The purpose of this program is to take a series of elements that the user types in and run them backwards. For example, "Hello" becomes "olleH". I've been trying to get this right for a while now and It's been completely stumping me for quite some time.
word=input("Type any word:")
word_l=len(word)
word2=None
for word in range(word_l):
word2+=word[word_l]-i
print(word2)
Sorry if this seems like a serious noob question. Thanks.
This is a standard indexing problem. There's a third optional argument when you're slicing that creates a step. By setting that step to -1 you reverse the sequence:
>>> word = "hello"
>>> print(word[::-1])
olleh
>>>
Rule of thumb: If you are using string index or list indexes in a loop in Python to access each element -- look at the problem again 'cause there probably is a better way to do it.
You can simply add each character to the string in turn which will reverse the string:
word='Hello'
word2=''
for c in word:
word2=c+word2
print(word2)
You can also just use reversed:
>>> ''.join(reversed('Hello'))
'olleH'
word=input("Type any word:")
word_l=len(word)
word2=''
for i in range(word_l):
word2+=word[word_l-i-1]
print(word2)

python 2.7 string_name.find() function always returning -1 when using variable

Python 2.7 on Windows 10
So, I've started trying to use a function that, in all of my examples, locates the first iterance in a string of the requested word.
Example:
message = "Hello, World."
print(message.find('World'))
and it will return:
7
This works for me. However I'm trying to give a string, then ask if the user would like to locate a word within that string. If the answer is yes, the program is asking which word and the input from the user is being assigned the variable dokokotoba and then I'm trying to find the word dokokotoba.
The program runs fine in all aspects save that every time I try to find a word, it returns -1, which indicates failure. I don't understand why. Is it because I can't use a variable there? If so, I can't see why not.
You have .find('dokokotoba') instead of .find(dokokotoba).
You are looking for the string 'dokokotoba', not the value of the variable. That string is not present in message, no.
Pass in the variable, not a string literal:
message.find(dokokotoba)
Note the lack of quotes there.
Demo:
>>> message = 'foo bar baz'
>>> message.find('bar')
4
>>> dokokotoba = 'bar'
>>> message.find(dokokotoba)
4
>>> message.find('dokokotoba')
-1
The proper way is
message.find(dokokotoba)
and not
message.find('dokokotoba')
In the second case you are simply searching for the string "dokokotoba" in the message.

Categories