Ok here is list comprehension way.
>>> [(index, item) for index, item in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
Or.
>>> [pair for pair in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
Ok here is list comprehension way.
>>> [(index, item) for index, item in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
Or.
>>> [pair for pair in enumerate(names)]
[(0, 'Google'), (1, 'Apple'), (2, 'Microsoft')]
You should almost never use global varible in function,it's ugly.
Function should take argument an return values out.
Some code you can look at.
#Ver_1
def foo():
bar = "Just a string"
return bar
print foo() #Just a string
#Ver_2
def foo(global_bar):
bar = "Just a string and from ouside {}".format(global_bar)
return bar
global_bar = "global Variable"
print foo(global_bar) #Just a string and from ouside global Variable
#Ver_3
def foo(global_bar="global Variable"):
'''Here i use default argument'''
bar = "Just a string and from default arg {}".format(global_bar)
return bar
print foo() #Just a string and from default arg global Variable
If the data endered ends with one of the 3 extensions, I would like it to be returned and the snes emulator to be opened.
Your logic dos not make sense to me.
If user input game.smc
,should all files that has a smc extensions be found?
Explain your self better.
You never use data
returned by os.listdir('/SNES/SNESRoms')
.data
return are all files in /SNES/SNESRoms
,but if you never use it what's the point?
What i mean is this,here i use data
to do something.
for data in os.listdir('/SNES/SNESRoms'):
print data #all files in /SNES/SNESRoms that you never use
if data.endswith(extensions):
print data #all files that ends with extension definde before in extensions.
For fun one with regex,but i guess this is a school task?
import re
string = 'alpha 111 bravo 222 alpha somethingA end, 333 bravo somethingB end 444 alpha 555 bravo'
pattern = re.compile(r'(alpha|bravo)(\s\w+\s)(end)')
for match in pattern.finditer(string):
print match.group(2).strip()
"""Output-->
somethingA
somethingB
"""
Would it be easier if the "file1.txt", file2.txt", etc were .csv files? Would this helping the coding? Thanks
No it would not help,the challenge is the same if you need to multiply vaules from difference files.
The only difference is \n
or ,
Look at this,if use spilt() on both the output list is the same.
>>> s = '''111.11
222.22'''
>>> s
'111.11\n222.22'
>>> s.split()
['111.11', '222.22']
>>> csv = '111.11, 222.22'
>>> csv
'111.11, 222.22'
>>> csv.split(',')
['111.11', ' 222.22']
>>> sum(float(i) for i in s.split())
333.33
>>> sum(float(i) for i in csv.split(','))
333.33
You can try this,glob will iterate over all your file..txt
I use fileinput
module to open all files.
Then calulate two sum based on enumerate
even/odd.
import fileinput
from glob import glob
sum_file = open("SumFile.csv", "w")
total = 0.0
total_1 = 0.0
fnames = glob('file*.txt')
for numb,line in enumerate(fileinput.input(fnames)):
if numb % 2 == 0:
total += float(line.strip())
else:
total_1 += float(line.strip())
sum_file.write('%6.20f,\n%6.20f,\n' % (total, total_1))
sum_file.close()
You don't need to include re it's a python build in module and cxFreeze will find it.
If you want to include moduls you also need to modify setup.
Here is a test i did with regex,as you see i include nothing.
If it work re_test.exe
will output ['fast', 'friendly']
''''
Put "my_cx_freeze.py" and "re_test.py"(your script) in same folder.
Run it from command line(cmd) or terminal linux,navigate to folder with script.
Then type python my_cx_freeze.py build
'''
#my_cx_freeze.py
from cx_Freeze import setup,Executable
includefiles = []
includes = []
excludes = []
packages = []
filename = "re_test.py"
setup(
name = 'myapp',
version = '0.1',
description = 'Re test',
author = 'None',
author_email = 'someting@my.org',
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [Executable(filename, base = None, icon = None)])
---
#re_test
import re
match = re.findall(r'\bf.*?\b', 'a fast and friendly dog')
print(match)
raw_input('Press enter to exit')
#input('Press enter to exit') #for python 3 use this
Something like this look better,and 'do' is not used in Python.
s = 'ABsomething'
if s.startswith(('AB','CC','EF','US')):
print '{}subroutine'.format(s[:2])
else:
print 'Substring not found'
>>> flowers = ['rose', 'bougainvillea', 'yucca', 'marigold', 'daylilly', 'lilly of the valley']
>>> thorny = []
>>> #First element in flowers list
>>> flowers[0]
'rose'
>>> #append first element to thorny list
>>> thorny.append(flowers[0])
>>> thorny
['rose']
>>> thorny.append(flowers[1])
>>> thorny
['rose', 'bougainvillea']
>>> thorny.append(flowers[2])
>>> thorny
['rose', 'bougainvillea', 'yucca']
>>> #Remember you can use help or look at Python doc
>>> help(thorny.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
>>> dir(thorny)
#All function/methods you can use on list,look away from magic methods start with __.
Some good example over,one more.
Running it interactive can help.
I keep function out from interactive environment,then it's eaiser to keep indentation.
def foo(x):
print 'foo got called with argument', x
def wrapped(y):
return x * y
return wrapped
Run it.
>>> foo
<function foo at 0x02AA1DB0>
>>> #Memory location of uncalled foo
>>> foo(4)
foo got called with argument 4
<function wrapped at 0x029955B0>
>>> #We see foo get called and we get memory location of uncalled wrapped
>>> foo(4)(5)
foo got called with argument 4
20
>>> #Both function is called
>>> #So store it in a varible
>>> bar = foo(4)
foo got called with argument 4
>>> #So to get the same as over foo(4)(5)
>>> bar(5)
20
Some hint that should help you.
>>> lst = [1,2,3,4,5,6]
>>> lst[:3]
[1, 2, 3]
#Assign to list thorny
>>> help(lst.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
#Or
>>> help(lst.extend)
Help on built-in function extend:
extend(...)
L.extend(iterable) -- extend list by appending elements from the iterable
>>> #Concatenation of lists?
>>> ['Hello'] + ['world']
['Hello', 'world']
The functional programming way with map()
is short and fine for this.
In Python are list comprehension used much and in many cases more prefered than a functional style.
def to_numbers(str_list):
return [int(i) for i in str_list]
lst = ['1', '2']
print to_numbers(lst)
If you wonder why i have changed to small letter and use _,look at PEP-8.
mac_address live alone in global space.
If you want it in your class you have pass it in as a instance variable or a agrument for for method resolve.
>>> from foo import Mac
>>> b = Mac(mac_address)
>>> b.resolve()
{'000000': 'xerox0', '000001': 'xerox1', '000002': 'xerox2'}
Or
class Mac:
def __init__(self,hexmac):
self.hexmac = hexmac
def resolve(self, mac_address):
return self.hexmac, mac_address
mac_address = { \
'000000':'xerox0', \
'000001':'xerox1', \
'000002':'xerox2', \
}
Use class.
>>> b = Mac('123')
>>> b.resolve(mac_address)
('123', {'000000': 'xerox0', '000001': 'xerox1', '000002': 'xerox2'})
but i wanted to learn re module..
Start with something simpler.
An example could be something like this.
Match phonenumber with +.
>>> import re
>>> s = '"taruna"," 09015561619"," +918968391049",,"tarunthegreat43@gmail.com",,,'
>>> re.findall(r'\+\d+', s)
['+918968391049']
So \+
macth +
.+
alone has a spesiell mening(Matches 1 or more of the preceeding token)\d
Matches any digit character (0-9)
And last +
so we get whole number.
Email adress.\w+
Matches any word character
Then mactch @
,then a new \w+.\w+
So will this work?
>>> s = '"taruna"," 09015561619"," +918968391049",,"tarunthegreat43@gmail.com",,,'
>>> re.findall(r'\w+@\w+.\w+', s)
['tarunthegreat43@gmail.com']
Read python doc
There are many online tools that can help with regex.
http://www.gskinner.com/RegExr/
http://osteele.com/tools/rework/
http://regexlib.com/?AspxAutoDetectCookieSupport=1
http://rubular.com/
When you iterate over with csv.reader(ins) you get a list output.['3.2323232312']
>>> map(int, ['3.2323232312'])
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.2323232312'
>>> map(float, ['3.2323232312'])
[3.2323232312]
Even if you use float you just get 3 separate list,and sum() would not work.
If you want to add up those numbers,here one way.
with open('e1.csv') as ins:
print sum(float(i) for i in ins) #14.1092143611
If you have more problem post an example of how E1.csv
look,not just a column.
You dont have to post whole file,but some lines that are complete and desired output.
One more stone turned:
Collections is good,and i think we should also mention the star when it's come to counting stuff collections.Counter.
>>> from collections import Counter
>>> import random
>>> Counter(random.randint(1,10) for i in range(100))[3]
8
>>> Counter(random.randint(1,10) for i in range(100))[3]
9
Some more fun with Counter.
>>> from collections import Counter
>>> lst = [3,3,3,3,9,9,1,3,3,5]
>>> counter = Counter(lst)
>>> counter[3]
6
>>> counter.most_common(2)
[(3, 6), (9, 2)]
>>> counter.most_common(1)
[(3, 6)]
>>> fruits = ['Apple', 'Apple', 'Pear', 'Orange', 'Banana', 'Apple', 'Banana']
>>> fruit_count = Counter(fruits)
>>> fruit_count
Counter({'Apple': 3, 'Banana': 2, 'Orange': 1, 'Pear': 1})
>>> fruit_count.most_common(1)
[('Apple', 3)]
>>> fruit_count.most_common(2)
[('Apple', 3), ('Banana', 2)]
>>> fruit_count['Apple']
3
>>> import itertools
>>> nested_lst = [[1,3,3],[1,2,3]]
>>> nested_counter = Counter(itertools.chain(*nested_lst))
>>> nested_counter[3]
3
>>> nested_counter
Counter({3: 3, 1: 2, 2: 1})
>>> nested_counter.most_common(1)
[(3, 3)]
Can clean it up little.
import random
count = 0
for x in range (100):
i = random.randint(1,10)
if i == 3:
count = count + 1
print count
There are other way to write this,here is one.
>>> import random
>>> [random.randint(1,10) for i in range(100)].count(3)
7
thanks but why doesn't the sleep work...?
If you look at the documentation for time.sleep(), you see that it basically blocks execution of that thread for the specified interval.
The problem is that GUI is a single thread,so if you block the thread then you block all execution in that thread.
This means that the GUI is unusable during the sleep and will in may cases lock up.
Most GUI toolkit has bulid in soultion for this.
In Tkinter it's after
Wxpython has wx.timer
a = [0,1,2,3,4,5,6,7,8,9]
a[0]=input()
a[1]=input()
a[2]=input()
a[3]=input()
a[4]=input()
a[5]=input()
a[6]=input()
a[7]=input()
a[8]=input()
a[9]=input()
In Python we dont like long code that dos repating stuff.
>>> [int(raw_input('Enter numbers: ')) for i in range(10)]
[90, 5, 27, 63, 12, 47, 10, 150, 120, 40]
After sorting you can use zip()
to make number par.
>>> lst
[5, 10, 12, 27, 47, 48, 63, 90, 120, 150]
>>> zip(lst,lst[1:])
[(5, 10),
(10, 12),
(12, 27),
(27, 47),
(47, 48),
(48, 63),
(63, 90),
(90, 120),
(120, 150)]
The next step can be to iterate over number par and and get subtract result.
Then from that list take out min()
number index value in zip()
list.
So here is here is my version,not tested probably only with this list.
def foo(lst):
lst = sorted(set(lst))
number_par = zip(lst,lst[1:])
lowest_par_result = [abs(y-x) for x,y in number_par]
lowest_par_index = lowest_par_result.index(min(lowest_par_result))
return number_par[lowest_par_index]
lst = [90, 5, 27, 63, 12, 47, 10, 150, 120, 48]
print foo(lst) #(47, 48)
The file i use num.txt
is just a copy of contend in your post.
I have tested code in python 2.7 and 3.2,works fine for me.
also i still have no idea how to just import the excell spreadsheet into python to use,
You most use using something like xldr
A example of use here by Gribouillis.
ive also tryed just using the numbers in a .txt file.. like so.
An example of how to do this,and doing som calulation.
with open('num.txt') as f:
numb_list = [[float(i) for i in list(i.strip())] for i in f]
for index,numbs in enumerate(numb_list, 1):
print('{:<2} {} : {:.2f} {}'.format(index,numbs, sum(numbs)/len(numbs), sum(numbs)))
"""Output-->
1 [0.0, 0.0, 2.0, 0.0, 5.0, 6.0, 3.0, 0.0] : 2.00 16.0
2 [5.0, 1.0, 9.0, 0.0, 0.0, 2.0, 3.0, 2.0] : 2.75 22.0
3 [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0] : 0.12 1.0
4 [1.0, 1.0, 1.0, 0.0, 2.0, 2.0, 2.0, 1.0] : 1.25 10.0
5 [5.0, 3.0, 2.0, 0.0, 0.0, 2.0, 5.0, 5.0] : 2.75 22.0
6 [2.0, 2.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0] : 0.88 7.0
7 [3.0, 2.0, 5.0, 0.0, 1.0, 2.0, 0.0, 4.0] : 2.12 17.0
8 [3.0, 0.0, 7.0, 1.0, 3.0, 5.0, 2.0, 4.0] : 3.12 25.0
9 [0.0, 2.0, 6.0, 1.0, 0.0, 5.0, 2.0, 1.0] : 2.12 17.0
10 [4.0, 0.0, 2.0, 0.0, 3.0, 2.0, 1.0, 0.0] : 1.50 12.0
11 [1.0, 1.0, 1.0, 0.0, 2.0, 2.0, 2.0, 1.0] : 1.25 10.0
12 [5.0, 3.0, 2.0, 0.0, 0.0, 2.0, 5.0, 5.0] : 2.75 22.0
"""
Looking at code you are doing some stuff that are not so good.str(idList[index][:-1]
this is not nessessay and don't do it inside open()
Look at this.
""" url.txt
ttp://www.youtube.com/
ttp://www.google.no/
ttp://www.sol.no/
"""
with open('url.txt') as f:
idList = [item.strip() for item in f]
print idList
#--> ['ttp://www.youtube.com/', 'ttp://www.google.no/', 'ttp://www.sol.no/']
As you see i get a list list without \n
Some test code you can lok at.
>>> index = 0
>>> for i in range(3):
... i, idList[index]
... index +=1
...
(0, 'ttp://www.youtube.com/')
(1, 'ttp://www.google.no/')
(2, 'ttp://www.sol.no/')
>>> for i in range(4):
... i, idList[index]
... index +=1
...
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
IndexError: list index out of range
This can be shorter look at this.
>>> for i in range(3):
... i, idList[i]
...
...
(0, 'ttp://www.youtube.com/')
(1, 'ttp://www.google.no/')
(2, 'ttp://www.sol.no/')
>>> for i in range(4):
... i, idList[i]
...
...
(0, 'ttp://www.youtube.com/')
(1, 'ttp://www.google.no/')
(2, 'ttp://www.sol.no/')
Traceback (most recent call last):
File "<interactive input>", line 2, in <module>
IndexError: list index out of range
I did not flag it was happygeek,read Comments.
The code you gave me does not allowed the people to type quit to quit in the middle of the game.
I can change code so that is possible,but what's the logic in that?
The user get a chooice of how many question,if user choose 4 question the he/she get 4 question.
Maybe user get tired after 3 and want to quit.
dean.ong.14 you have asked this qustion before.
In the last post i tok time to structured and change code for a better soultion,did you even look at that?
http://www.daniweb.com/software-development/python/threads/438691/import-random-failed..-please-help-me#post1886678
i have to copy paste my downloaded python packages for them to work?
You do not copy/paste into site-packages folder yourself,you can but that's not the correct way(and it may not work).
3 methods:
First the manual way.
You download a packages extract to where-ever you want.
From command line cmd naviagte to extract folder then write python setup.py install
Under this install will files go to site-packages folder and package is installed.
There are two tool for eaiser install easy_install and pip(recommended)
pip also have an uninstall function for packages.
Both of these tool will download a package from web and install it.
So as an example from cmd you write pip install numpy
then download and install happens automatically.
Rembere to check environment variables Path
In Path if not there add ;C:\python27\;C:\python27\scripts
Or for python 3 ;C:\python33\;C:\python33\scripts
Restart to make it work.
This can be needed to be correct for all method i postet over to work fine.
If you want to use getter/setter you follow advice from JasonHippy,i have tested it and it's works.
If you wanne use my code is complete in my last post.
Dont mix stuff together.
the book wants them there (and I'm graded on if I do what the book asks)
If you want to learn python you can burn that book,and get a book that learn you python in a correct manner
and not mixing in stuff from other languages that dos not make any sense in python.
JasonHippy has give advice of why you get that error and how to fix it.
If you scrap the setArea and setPerimeter method and use recalculate it look like this.
>>> tri = Triangle(side1, side2, side3)
>>> tri.recalculate()
>>> tri.getArea()
11.61895003862225
>>> tri.getPerimeter()
18.0
>>> tri._GeometricObject__color
'green'
So a rewrite to get the same.
from math import *
class GeometricObject():
def __init__(self, color = "green", filled = True):
self.color = color
self.filled = filled
class Triangle(GeometricObject):
def __init__(self, side1=1, side2=1, side3=1):
super().__init__()
self.side1 = float(side1)
self.side2 = float(side2)
self.side3 = float(side3)
def calulate(self):
self.perimeter = self.side1 + self.side2 + self.side3
s = (self.side1 + self.side2 + self.side3) / 2
self.area = sqrt(s* (s-self.side1) * (s-self.side2) * (s-self.side3))
'''
side1 = 8
side2 = 4
side3 = 6
color = 'Yellow'
filled = 1
'''
Use it:
>>> tri = Triangle(side1, side2, side3)
>>> tri.calulate()
>>> tri.area
11.61895003862225
>>> tri.perimeter
18.0
>>> tri.color
'green'
Do not use use evalside1 = int(input("Enter a value for side 1: "))
Actually, I have a C# background and the book is written to be a step into Java
Please do not try to learn any programming language by leveraging knowledge of another programming language.
Programming languages (with a few exceptions) are more different than alike.
It's much easier on your brain to start "from scratch" when learning a new language.
Try to avoid comparing syntax or semantics between languages.
I think you have teacher with java background.
There are really no need for getters/setters in both of these Class.
Java programmers will often introduce private members, and then add getters and setters.
This is evil; the attribute should have been public in the first place.
Something to read Python is not Java
Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans. Do not write getters and setters. This is what the 'property' built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in 'property'. That means that until you prove that you need anything more than a simple attribute access, don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well.
Just a demo with GeometricObject class.
Use it:
>>> c = GeometricObject('Yellow', False)
>>> c._GeometricObject__color
'Yellow'
>>> c._GeometricObject__filled
False
>>> c._GeometricObject__color = 'Black'
>>> c._GeometricObject__filled = True
>>> c._GeometricObject__color
'Black'
>>> c._GeometricObject__filled
True
Rewrite it.
class GeometricObject():
def __init__(self, color = "green", filled = True):
self.color = color
self.filled = filled
def __str__(self):
return 'Color {} and filled {}'.format(self.color, self.filled)
Use it:
>>> c = GeometricObject('Yellow', False)
>>> c.color
'Yellow'
>>> c.filled
False
>>> c.color …
Yes a for loop and using comparison operators will work.
Here is a hint.
t = (20, 58, 70, 92, 98)
A,F = 0,0
for mark in t:
if mark < 60:
F += 1
elif mark >= 90:
A += 1
else:
pass
print('{} people got A\n{} people got F'.format(A, F))
Run this,here i use list comprehension,it can be written without and just append to a list.
Just to show that a loop can save you from writing test1,test2.....
score_lst = [int(input('What is the score of test number {}? '.format(i))) for i in range(1,6)]
print(score_lst)
You are doing some strange stuff.
Do you get urllib to work for this site?
import urllib2
url = "http://www.blah.fi/"
read_url = urllib2.urlopen(url).read()
print read_url #403 error
This site are blocking use of urllib.
I had to use Requests to get source code.
You can use BeautifulSoup to get all link,no need to use regex.
import requests
from bs4 import BeautifulSoup
url = "http://www.blah.fi/"
url_read = requests.post(url)
soup = BeautifulSoup(url_read.content)
links = soup.find_all('a', href=True)
for link in links:
print link['href']
urllib2.urlopen('http://www.blah.fi/' + link).read()
is this really what you want?
Will give you output like this.
>>> 'http://www.blah.fi/' + 'http://v-reality.info/' + '<hr>'
'http://www.blah.fi/http://v-reality.info/<hr>'
soup = BeautifulSoup(open(html))
not this way,the normal way is.
url = urllib2.urlopen("http://www.blah.fi/")
soup = BeautifulSoup(url)
tag = soup.find_all(Do stuff you want)
IOError: [Errno 36] File name too long:
The error is pretty clear,put i do not understand that it come from line 3.
A filename can not be longer than 255 character.
Look at output from content = soup.find(id="content")
print content
print type(content)
print repr(content)
I'm not really sure how to test a python library for successful installation though.
import bs4
>>> bs4.__version__
'4.1.0'
>>> from bs4 import BeautifulSoup
>>> print BeautifulSoup.__doc__
#You get description if it work
I have structured code better by using functions and some changes/corrections.
This make it easier to test code and as you want start and stop the quiz.
import random
try:
input = raw_input
except:
pass
def all_quest():
'''All questions that can be used'''
questions = [("Denis Glover wrote the poem The Magpies ", 'yes'),
("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
# several lines omitted for clarity...
("Kiri Te Kanawa is a Wellington-born opera singer ", 'no'),
("Phar Lap was a New Zealand born horse who won the Melbourne Cup ", 'yes'),
("Queen Victoria was the reigning monarch of England at the time of the Treaty ", 'yes'),
("Split Enz are a well-known rock group from Australia who became very famous in New Zealand during the 80s ", 'no'),
("Te Rauparaha is credited with intellectual property rights of Kamate! ", 'yes'),
("The All Blacks are New Zealands top rugby team ", 'yes'),
("The Treaty of Waitangi was signed at Parliament ", 'no'),
("The Treaty of Waitangi was signed in 1901 ", 'no'),
("Aotearoa commonly means Land of the Long White Cloud ", 'yes')]
random.shuffle(questions)
return questions
def numb_of_quest(questions):
'''Return the number of questions to be asked'''
while True:
try:
maxQuestions = int(input("Enter the number of questions to ask (more than 0 and less than to {0}): ".format(len(questions))))
if 0 <= maxQuestions < len(questions):
return (maxQuestions)
else:
print('Not between 0 and {},try again\n'.format(len(questions)))
except Exception as e:
print("Please enter …
Some additional info.
Sometime it can convenient to not type in filename manually,but extract filename from url.
Like when downloading more than one image or iterate over a list of url`s.
strip()
is not needed here for a single image.
But can be needed if iterating over many url`s to strip of new line(\n)
import webbrowser
try:
# Python2
from urllib import urlretrieve
except ImportError:
# Python3
from urllib.request import urlretrieve
url = "http://www.google.com/intl/en/images/logo.gif"
# Take out filname from url
filename = url.strip().split('/')[-1]
urlretrieve(url.strip(), filename)
print("image saved as {}".format(filename))
# try to show the saved image file ...
webbrowser.open(filename)
>>> m = 1
>>> oldVelocity = m.v
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: 'int' object has no attribute 'v'
As it say int object has no attibute 'v'
The dot "." is the member access operator.
Generally an object of a class has attributes/methods.
So as an example i do this.
>>> class Foo:
v = 100
>>> m = Foo()
>>> m.v
100
Or.
>>> class Foo:
@property
def v(self):
return 5000
>>> m = Foo()
>>> m.v
5000
Here you see a class Foo that has attribute and method v.
So int class has no attribute/methods that is called v and give and error.
That was the long explanation of the error,maybe it was just and type error as pyTony metion.
As posted over we need more info,like input data.
Code use Numpy and it use function add() and dot().
To see what these numpy function dos,look into numpy doc here is add()
To test function so it work i guessed for a nested list as input data.
from numpy import *
def CalcCentre(data):
centre = array([0,0,0])
count = 0
for p in data:
centre = add(centre, array(p[:3]))
count += 1
centre = dot(1./count, centre)
return centre
print CalcCentre(array([[1,2,3], [4,5,6]]))
#--> [ 2.5 3.5 4.5]
I get the step value counting down and was able to get the correct outcome but I am confused on the ending value (-1) and why that made it work.
>>> start = 7
>>> stop = 1
>>> step = -1
>>> for r in range(start,stop,step):
r
7
6
5
4
3
2
>>> help(range)
Help on built-in function range in module __builtin__:
range(...)
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
to cups.')) is missing line 5.
ok lets say every character is 3 digits. i want to read from file and print each character. How to do this?
Something like this.
def foo(filename, chunks):
with open(filename) as f:
numb_list = list(f.read())
return [numb_list[i:i+chunks] for i in range(0, len(numb_list), chunks)]
lst = foo('data.txt', 3)
for item in lst:
print chr(int(''.join(item)))
"""Output-->
h
e
l
l
o
"""
But I believe that this is not the best way of writing the program. If you look at the while loop, the condition will never evaluate to true. Is this right?
Yes that loop will not work,only way that will work if you guess right on first attempt.
It better/clearer to use !=(not equal).
As long as guess !=(not equal) secret_number
,the while loop will run.
So then it can look like this,see also that i use int(input(""))
.
so that we compare integer with integer(not string with integer).
#Python 3.x
import random
secret_number = random.randint(1,100)
attempts = 0
guess = 0
while guess != secret_number:
guess = int(input("Enter Guess Here: "))
if guess > secret_number:
print('Lower...')
elif guess < secret_number:
print('Higher...')
attempts += 1
print("You guessed it! The number was {0} in {1} attempts".format(secret_number, attempts))
enjoy:
Not so much to enjoy in that code.
You dont read file line by line as @vimalya mention.
With read()
you read all file into memory.del
we almost never need to use in python.
Example.
data.txt-->
header
1 2 3
4 5 6
7 8 9
---
with open('data.txt') as f:
line = f.next()
for line in f:
#print line
#You can procces data like this
print [int(item) for item in line.split()]
"""Output-->
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
"""
Next time vimalya try to post some code,not just a task to solve.
A regex version,but i do like Vega soultion better.
import re
def is_alpha_space(name):
name_nospace = ''.join((name.split()))
if re.search(r"\W", name_nospace) or len(name_nospace) < 1:
return False
return True
name = "Mark Zumkoff"
print(is_alpha_space(name)) # True
name = "Mark Zumkoff@"
print(is_alpha_space(name)) # False
name = " "
print(is_alpha_space(name)) # False
You should uppgarde your pyS60 version if enumerate() not work.
enumerate() was new in python 2.3 in 2003.
It`s difficult to write/learn python if you cannot use features implemented last 10 years.
It`s simpel with python to,and this is a python forum.
@crishein14 save script in folder with files and run.
import os, glob
for numb,name in enumerate(glob.glob('*png')):
os.rename(name, '{num:03d}.png'.format(num=numb))
Colons(:) are basic and important in python.
Other languages use { }
or other method to indicate/use a code block.
Python use indentation
after colons(:) to indicate/use a code block.
word = 'hi'
if word == 'hi':
print'Now this block get executed an word is equal to hi'
else:
print'Now this block get executed an word is not equal to hi'
So it look like this.
print "Welcome to the English to Pig Latin translator!"
original = raw_input("Please enter a word: ")
pyg = "ay"
if len(original) >= 1 and original.isalpha():
word = original.lower()
first = word[0]
#if word == a or e or i or o or u:
if first in 'aeiou':
print "Your first letter is a vowel"
else:
print "You'r first letter is a consonant"
print "So your word is {}".format(original)
else:
print "No word detected."
Dont use variable name as sum
and file
,these word are use by python.
So my_file is ok because it not used by python an give a NameError.
>>> sum
<built-in function sum>
>>> file
<type 'file'>
>>> my_file
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'my_file' is not defined
count()
as used over is ok to use for a word as "Olympics".
But to count other word,it can act not as expected.
If i want to count word "hi" that occurred 1 time in variable s i get 4.
>>> s = 'hi is hirohito in japan,higher or lower'
>>> s.count('hi')
4
There are several way to solve this,split(
) and using collections.Counter
can be one nice way.
>>> from collections import Counter
>>> s = 'hi is hirohito in japan,higher or lower'
>>> s = s.split()
>>> c = Counter(s)
>>> c['hi']
1
The best way is to always use raw string(r
) when give path in windows.
There is also an option to use \\
or /
.
So this do not work.os.chdir('C:\test')
This work.
os.chdir(r'C:\test')
os.chdir('C:\\test')
os.chdir('C:/test')
The reason why is this way,is that a singel backslashes(\
) in python can(do) get read as an escape character.
@sepp2k also metion that you need escape your backslashes.
Take a look at this.
>>> s = 'C:\test'
>>> print s
C: est
>>> print repr(s)
'C:\test'
>>> repr(s)
"'C:\\test'"
Then with raw string.
>>> s = r'C:\test'
>>> print s
C:\test
>>> print repr(s)
'C:\\test'
>>> repr(s)
"'C:\\\\test'"
One more \
>>> s = 'C:\\test'
>>> print s
C:\test
I only use BeautifulSoup or lxml,because they are by far the two best parser for python.
Can show you on way with BeautifulSoup.soup.find_all('router')
find all ruter tag,i take out router 1 router_tag[0]
Then put id and ip text in a dictionary.
from bs4 import BeautifulSoup
xml_file = """\
<routingTable>
<router>
<id>1</id>
<ip>1.1.1.1</ip>
<nexthop>1.1.1.2</nexthop>
</router>
<router>
<id>2</id>
<ip>2.2.2.1</ip>
<nexthop>2.2.2.2</nexthop>
</router>
</routingTable>"""
router1_dict = {}
soup = BeautifulSoup(xml_file, 'xml')
router_tag = soup.find_all('router')
router_1 = router_tag[0]
router1_dict[router_1.find('id').text] = router_1.find('ip').text
print router1_dict #--> {u'1': u'1.1.1.1'}
Komodo Edit there is a little more stuggle to setup run button.
http://community.activestate.com/forum-topic/executing-python-code-within-komodo-edit
Komodo IDE has run button build in,because it has debugging features for python build in.
Look at Pyscripter(windows only) and Spyder great editors for python.
Can also mention Pydev wish is powerful,not as lightweigt need of course to install Eclipse.
There is no need to use split(' ') Lucaci,just use split().
split() always splits on all whitespace if left unspecified.
A little help or mayby to much.
>>> s = "This is it!".split()
>>> s
['This', 'is', 'it!']
>>> len(s[0])
4
>>> [len(i) for i in s]
[4, 2, 3]
Try to figure out what happens in code over.
And as a practise [len(i) for i in s] write this line as a basic for loop with append as pyTony suggest.
This line called list comprehesion and are very common to use in python,so it good to look into it even if you have just start learing python.
Nice to use with, not sure when it was introduced?
In python 2.5 september 19, 2006.
Bare "except:", with no exception specified is nasty because it can easily hide bugs.
except: #Dont do this
To use your code as example.
def file_exists(filename):
'''
a file exists if you can open and close it
'''
try:
f = ope(filename) # misspelled "open"
f.close()
return True
except:
return False
print file_exists('somefile.txt')
The misspelled "open" triggers a NameError,which is caught by the except clause.
So funcion return False,so it hide the real problem that there is NameError.except IOError
will only catch IOError and show that NameError is the problem.
When people see bare "except:" in code they can complain about it.
http://python.6.n6.nabble.com/issue4788-two-bare-quot-except-quot-clauses-are-used-in-the-ssl-module-td701941.html