"Name of function is not defined" - python

A complete newbie's question:
The code is intended to find the longest string in a list and display it.
It does not work when I run it (as a file, or directly in the shell). I keep getting an error message that the function's name is not recognized. Your help and advice would be highly appreciated.
The correct result is shown with the print command, but when I try to run the complete file I keep getting the above-mentioned error.
def longest(mylist):
mylist = ["111", "44", "baking", "dot"]
list1 = max(["111", "44", "baking", "dot"], key=len)
longest(list1);
print(list1)
Error running the file:
File "<stdin>", line 1
python [filename].py
SyntaxError: invalid syntax
Error when pasting the code into the shell:
SyntaxError: invalid syntax
>>> mylist = ["111", "44", "baking", "dot"]
>>> list1 = max(["111", "44", "baking", "dot"], key=len)
>>> longest(list1);
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'longest' is not defined
>>> print(list1)
baking

The function does not do anything in your code.
Could have shorten to the below.
max_value = max(["111", "44", "baking", "dot"], key=len)
print(max_value)

Your code is not written properly, you should go through python tutorials to learn the basics. There are plenty of tutorials available on internet.
Python Tutorial at TutorialsPoint
Python Official Doc
Now, the answer to your question is :
#!/usr/bin/python
# This is the function which takes list as an argument and
# returns the longest string from the list
def longest(mylist) :
l = max(mylist, key=len)
return l
# This is the list which contains all the strings
mylist = ["111", "44", "baking", "dot"]
# This is the function call with "mylist" as argument
# and, the return value is assigned to a variable "x"
x = longest(mylist)
# prints the output
print(x)

This is not a solution to your problem where longest can't be found, but a working implementation of your code.
def longest(mylist):
return max(mylist, key=len)
list1 = ["111", "44", "baking", "dot"]
print(longest(list1))

Your problem is in your function.
You're receiving an argument in your function and you're overriding this argument at line 2.
Here what your function needs to look like
def longest(mylist):
mylist = max(mylist, key=len)
return mylist
And then after you're calling your function with your argument
mylist = ["111", "44", "baking", "dot"]
mylist = longest(mylist);
print(mylist)
Plus in your shell you didn't define your function so the interpreter doesn't know it

Related

NameError, name is not defined

I wrote a simple code to check if a list is sorted or not.
I have two questions:
First, my result is wrong. I guess the issue is with following the line. Which one is correct?:
sorted_list = mylist[:].sort()
sorted_list = list(mylist[:]).sort()
As second question, when I try to print(sorted_list), I get NameError which is sorted_list is not defined which is weird. Because I've already defined it in the second line. Would you please help me understand why I'm getting this error?
def is_sorted(mylist):
sorted_list = mylist[:].sort()
# mylist.sort()
if sorted_list == mylist:
return True
else:
return False
print(is_sorted(['Aajid', 'Bafiee', 'Hello']))
print(sorted_list)
Output:
False
Traceback (most recent call last):
File "e:\NectCloud\Python\is_sorted.py", line 11, in <module>
print(sorted_list)
^^^^^^^^^^^
NameError: name 'sorted_list' is not defined
Thanks
Use
mylist = [1, 5, 3, 6, 2]
sorted_list = sorted(mylist)
mylist.sort() does inplace sorting and returns None. For more information about sorting see https://docs.python.org/3/howto/sorting.html.
sorted_list is not defined in outer scope since it is only defined in the function scope. See https://realpython.com/python-scope-legb-rule/.

custom sort function in python 3 [duplicate]

In Python 2.x, I could pass custom function to sorted and .sort functions
>>> x=['kar','htar','har','ar']
>>>
>>> sorted(x)
['ar', 'har', 'htar', 'kar']
>>>
>>> sorted(x,cmp=customsort)
['kar', 'htar', 'har', 'ar']
Because, in My language, consonents are comes with this order
"k","kh",....,"ht",..."h",...,"a"
But In Python 3.x, looks like I could not pass cmp keyword
>>> sorted(x,cmp=customsort)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'cmp' is an invalid keyword argument for this function
Is there any alternatives or should I write my own sorted function too?
Note: I simplified by using "k", "kh", etc. Actual characters are Unicodes and even more complicated, sometimes there is vowels comes before and after consonents, I've done custom comparison function, So that part is ok. Only the problem is I could not pass my custom comparison function to sorted or .sort
Use the key keyword and functools.cmp_to_key to transform your comparison function:
sorted(x, key=functools.cmp_to_key(customsort))
Use the key argument (and follow the recipe on how to convert your old cmp function to a key function).
functools has a function cmp_to_key mentioned at docs.python.org/3.6/library/functools.html#functools.cmp_to_key
A complete python3 cmp_to_key lambda example:
from functools import cmp_to_key
nums = [28, 50, 17, 12, 121]
nums.sort(key=cmp_to_key(lambda x, y: 1 if str(x)+str(y) < str(y)+str(x) else -1))
compare to common object sorting:
class NumStr:
def __init__(self, v):
self.v = v
def __lt__(self, other):
return self.v + other.v < other.v + self.v
A = [NumStr("12"), NumStr("121")]
A.sort()
print(A[0].v, A[1].v)
A = [obj.v for obj in A]
print(A)
Instead of a customsort(), you need a function that translates each word into something that Python already knows how to sort. For example, you could translate each word into a list of numbers where each number represents where each letter occurs in your alphabet. Something like this:
my_alphabet = ['a', 'b', 'c']
def custom_key(word):
numbers = []
for letter in word:
numbers.append(my_alphabet.index(letter))
return numbers
x=['cbaba', 'ababa', 'bbaa']
x.sort(key=custom_key)
Since your language includes multi-character letters, your custom_key function will obviously need to be more complicated. That should give you the general idea though.
I don't know if this will help, but you may check out the locale module. It looks like you can set the locale to your language and use locale.strcoll to compare strings using your language's sorting rules.
Use the key argument instead. It takes a function that takes the value being processed and returns a single value giving the key to use to sort by.
sorted(x, key=somekeyfunc)

A function, to apply a function to a list

I am trying to write a function, that applies a function to a list. I am trying to capitalise all the words in a list but can't get it to work. Here is what I've done so far:
list = ("hello", "this", "is", "a", "test")
def firstFunction(x):
return list.upper()
print firstFunction
The error I get is:
<function firstFunction at 0x0000000002352A58>
I'm really stuck on what to do next, any help would be greatly appreciated.
EDIT:
I've just changed it but it's still not working:
mylist = ("hello", "this", "is", "james")
def firstFunction(x):
return may(lambda: x.upper(), mylist)
print firstFunction()
That isn't an error. It is the function's address in memory. You are seeing it because you didn't invoke the function.
Overall, there are three problems with your code:
You are not invoking the function. Adding (...) after it will do this.
You are not passing in an argument to the function, which it requires.
There is no upper method on a tuple (list in this case is a tuple).
Below is a fixed version of the code that does what I think you want:
# Don't name a variable 'list' -- it overshadows the built-in.
lst = ("hello", "this", "is", "a", "test")
def firstFunction(x):
return tuple(y.upper() for y in x)
print firstFunction(lst)
Output:
('HELLO', 'THIS', 'IS', 'A', 'TEST')
Here are some references on everything done here:
http://docs.python.org/2/reference/compound_stmts.html#function-definitions
https://wiki.python.org/moin/Generators
http://docs.python.org/2.7/library/stdtypes.html#str.upper
While other answers are great, I want to mention that there's already a function in python, called map(), and it does almost exactly what you need:
Apply function to every item of iterable and return a list of the
results..... The iterable
arguments may be a sequence or any iterable object; the result is
always a list.
So you code becomes
print map(str.upper, lst)
or, if you need a tuple, then:
print tuple(map(str.upper, lst))
You don't need anonymous lambda function here, because str.upper() accepts one argument. I think there's a debate about how pythonic this functional programming is, but I personally like it sometimes.
Actually nor the list, nor the tuple has no a method .upper().
So to achieve this you could just execute this statement:
print tuple(x.upper() for x in ("hello", "this", "is", "a", "test"))
http://codepad.org/MZ14yXeV
or this one:
print map(lambda x: x.upper(), ("hello", "this", "is", "a", "test"))
http://codepad.org/kc1LaNCY
list = ("hello", "this", "is", "a", "test")
is a tuple, an immutable, you cannot alter it, use,
print tuple((ele.upper() for ele in list))
I think this is the most pythonic one:
def cap(tup):
return map(str.upper, tup)
>>> tup = ("hello", "this", "is", "a", "test")
>>> cap(tup)
['HELLO', 'THIS', 'IS', 'A', 'TEST']
>>>
What you are trying to do involves list comprehensions:
print [firstFunction(x) for x in list]
what this does is: construct the list whose elements are the result of applying the function
to each of the items in you input list and then printing it.
Some (hopefully helpful) comments
It is bad practice to name a variable list; even though it is not a keyword,
it is the name of a fundamental python type, so re-binding it could cause confusion
elsewhere.
In your definition def firstFunction(list) -- the name list that appears in the
argument list does not have any relationship to the list variable that was defined earlier in your example. You may want to look at this question or the python documentation to understand how the scoping rules work in python.

How do I write the date to a .txt?

I am trying to write the date to a .txt file. The following is the code that I have made to do this but it always gives me an error.
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0]
file = open('Date.txt', 'a')
file.write(mylist)
file.close()
This code gives me the following error:
Traceback (most recent call last): File "/Volumes/CHROME
USB/STORAGE/Date.py", line 9, in
file.write(mylist) TypeError: argument 1 must be string or read-only character buffer, not list
Will someone please give me an example of a working code?
You can only write strings, it is stated in the error.
So you can do this to write the liste (converted in string) into the txt file:
file.write(str(mylist))
Simple example
>>> a= [1,2,3]
>>> b = str(a)
>>> b
'[1, 2, 3]'
>>> f = open("data","w")
>>> f.write(b)
>>> f.close()
>>>
$ cat data
[1, 2, 3]
File#write expects a string, not a list. Try file.write(repr(mylist)).
If you want to write the contents of the list, do it like this:
for entry in mylist:
file.write(str(entry))
or
map(lambda x: file.write(str(x)), mylist)

SyntaxError: invalid syntax while building a dict from a list using Python 2.6

I created a Python script with Python2.7 and it works fine. However, when I run the same script with Python2.6, I got a "SyntaxError: invalid syntax" error.
After investigating, the problem seems to be related to a for loop.
l1 = [["a1", "a2"], ["b1", "b2"]]
print {item[0]:item[1] for item in l1}
When I run the above code with Python 2.7, I've got the following output:
{'a1': 'a2', 'b1': 'b2'}
When I run the same code with Python 2.6, I've got the following error:
>>> l1 = [["a1", "a2"], ["b1", "b2"]]
>>> print {item[0]:item[1] for item in l1}
File "<stdin>", line 1
print {item[0]:item[1] for item in l1}
^
SyntaxError: invalid syntax
>>>
Any help is appreciated.
Regards,
Allen
Try this:
print dict(item for item in l1)
Edit about your comment: If you want to explicitly select items, wrap them in a tuple:
print dict((item[1], item[4]) for item in l1)
Dictionary comprehensions aren't available in Python 2.6. See Space_C0wb0y's answer for how to get around that in code.
try this:
print dict([tuple(i) for i in l1])

Categories