What concept of physics are you basing your program on?
bumsfeld 413 Nearly a Posting Virtuoso
llsubzer0 commented: very helpful +0
bumsfeld 413 Nearly a Posting Virtuoso
What concept of physics are you basing your program on?
Another option is to use FMOD:
http://www.fmod.org/fmod-downloads.html#FMODStudio
Or check out:
http://www.portaudio.com/
Generally, your GUI toolkits like QT have audio play functions.
What is your textbook?
Your individual lists have to line up properly to match name and data:
name = ['Frank', 'Bill']
salary = [1234.0, 1535.0]
remark = [3, 2]
employee_list = zip(name, salary, remark)
print(employee_list)
'''
[('Frank', 1234.0, 3), ('Bill', 1535.0, 2)]
'''
# sort by remark which is at tuple index 2
employee_list_sorted = sorted(employee_list, key=lambda x: x[2])
print(employee_list_sorted)
'''
[('Bill', 1535.0, 2), ('Frank', 1234.0, 3)]
'''
The approach vegaseat used avoids potential match problems.
Check out this Python project dealing with sound waves at:
http://openbookproject.net/py4fun/wave/wave.html
Watch out for numpy arrays, they don't always behave as expected:
''' np_array_copy.py
watch out for alias copy of a np array
the normal Python3 list behaves better
'''
import numpy as np
arr1 = np.arange(10)
# even though it's sliced, this will be an alias copy
arr2 = arr1[:5]
# make a true copy
arr3 = np.copy(arr1[:5])
print(arr1)
print(arr2)
print(arr3)
# change an element in arr1 (or arr2)
arr1[3] = 77
print('-'*50)
print(arr1)
print(arr2)
print(arr3)
''' result ...
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4]
[0 1 2 3 4]
--------------------------------------------------
[ 0 1 2 77 4 5 6 7 8 9]
[ 0 1 2 77 4] <-- oops!
[0 1 2 3 4]
'''
Sets will be ordered by hash order, so you loose the relationship of word and frequency data.
It could be easier to use collections.Counter() on each of your text files and go from there.
You have two strings that look much alike:
waterkraftownermanuals
wadercraftownersmanual
Write Python program that will highlight the differences by capitalizing the characters that don't match:
waTerKraftownermanualS
waDerCraftownerSmanual
"Would you like to continue unprotected?"
~~~ question from my computer
Eggs with mushrooms and nutbread toast. Lots of coffee.
I like high tech gadgets, so I must be one geek. Even though some are nerdy gadgets too.
According to the prohibitionists here, bear would be better than beer.
Microsoft may have problems with its "new" Windows8 OS. Could it be a white elephant? Adoption numbers are much less then even the bloated Windows Vista OS. Most folks consider the tile based Metro interface ugly. Yes, you can switch to another interface, a lame recognition of the established user base.
Source:
http://www.zdnet.com/five-reasons-why-windows-8-has-failed-7000012104/
The 64 bit Python version does not work with 32 bit third party modules.
If the words in your list/file are unique, you can do something like this:
import pprint
# write a test file with unique words
names = '''\
paul
peter
sally
frank
jim
Sandra
quito
'''
fname = "names.txt"
with open(fname, 'w') as fout:
fout.write(names)
name_dict = {}
# read in the names line by line
for line in open(fname):
word = line.strip()
#print(word)
name_dict[word] = len(word)
pprint.pprint(name_dict)
''' my output -->
{'Sandra': 6,
'frank': 5,
'jim': 3,
'paul': 4,
'peter': 5,
'quito': 5,
'sally': 5}
'''
You need to check the effects of sample size.
You also need some way to exit the while loop.
Here is the simple shift crypt code:
''' crypt_shift.py
encrypt and decrypt text using the shift of
each character in given text string
uses leading period indicator for encrypted string
Python27 and Python32 work with this
'''
def shift_crypt(text):
"""
if text starts with period decrypt, otherwise encrypt
shift ascii value of each text char by 1
"""
if text.startswith('.'):
# also remove leading period
return ''.join(chr(ord(c) - 1) for c in text[1:])
else:
# add period to indicate encoded text
return '.' + ''.join(chr(ord(c) + 1) for c in text)
str_original = 'met me tomorrow noon at the train station'
# encrypt the string
str_encrypted = shift_crypt(str_original)
print("Original string:")
print(str_original)
print('-'*50)
print("Encrypted String:")
print(str_encrypted)
print('-'*50)
# decrypt the encrypted string sending it to the function again
str_decrypted = shift_crypt(str_encrypted)
print("Decrypted String:")
print(str_decrypted)
'''my output -->
Original string:
met me tomorrow noon at the train station
--------------------------------------------------
Encrypted String:
.nfu!nf!upnpsspx!oppo!bu!uif!usbjo!tubujpo
--------------------------------------------------
Decrypted String:
met me tomorrow noon at the train station
'''
See if you can combine the swap and shift crypt to make it harder on hackers to decrypt.
This shows the code for one simple crypt of text by swapping two adjoining characters each. You can make that more complex if you like. Can also be used for one nice riddle.
In my journey to find a new programing language to learn, I found Nimrod.
According to the spiel on its web page:
"Nimrod combines Lisp's power with Python's readability and C's performance."
Just curious to know if anbody here has used it?
Nimrod's home is at:
http://nimrod-code.org/
In Python2 input() is for numbers and raw_input() is for strings. It is best to use raw_input() and then convert to a number using int() or float() since input() uses eval() internally and that can also excute commands. Some evil genius might whipe out your diskdrive this way.
Short example:
name = raw_input("Enter your name: ")
number = int(raw_input("Enter you favorite integer number: "))
div = float(raw_input("What is 3 divided by 2? "))
print('-'*10) # print 10 dashes
print(name)
print(number)
print(div)
print('-'*10)
# optionally format via % specifier
sf = """
name = %s
favorite int = %d
3 div by 2 = %f
"""
print(sf % (name, number, div))
''' example output -->
Enter your name: Henri
Enter you favorite integer number: 7
What is 3 divided by 2? 1.5
----------
Henri
7
1.5
----------
name = Henri
favorite int = 7
3 div by 2 = 1.500000
'''
In most cases you can simply use the print() function, then it will work in both newer Python versions.
Print rightfully should be a function and not a statement, this was corrected in the newer versions.
If you work with Python on a scientific project, then Spyder is the way to go. It is written in Python and Pyside (PyQT). I like the pleasant layout of the IDE and its many tools and options.
Sorry, the code areas are still rather goofy in the 'new improved' DaniWeb
Avoid using names like list and sum since they are internal to Python. Something like this will work:
mylist = []
prompt = "%d) enter an integer (-99 to stop): "
for k in range(1000):
x = int(raw_input(prompt % (k+1)))
if x == -99:
break
mylist.append(x)
print(mylist) # test
'''
1) enter an integer (-99 to stop): 4
2) enter an integer (-99 to stop): 66
3) enter an integer (-99 to stop): 7
4) enter an integer (-99 to stop): 12
5) enter an integer (-99 to stop): -99
[4, 66, 7, 12]
'''
Just more complex since you also have tuples in your list. This may work:
alist = [[], [(u'0.77',)], [(u'0.34',)], [(u'0.12',)], [(u'0',)], [(u'0.0',)], [(u'0',)]]
value_list = [float(x[0][0]) for x in alist if x]
print(value_list)
'''
[0.77, 0.34, 0.12, 0.0, 0.0, 0.0]
'''
Writing/showing/copying code seems to be made very difficult in the new DaniWeb format!
BTW, how do you copy and paste the new DaniWeb code areas?
When you post, highlight your code and click on the code tab above, something like this:
def add(x, y):
return x+y
print(add(2, 3))
Write a program that checks on a political candidates promisses and how many he/she keeps once elected.
"Science without religion is lame, religion without science is blind."
Albert Einstein (German born American Physicist)
Salmon on spinach with grits.
Green alcohol, I drink to that!
I would say C++ gets the youngsters used to the rigors of programming.
I guess they call them robo calls. You just sit down for dinner and the phone rings with some recorded message from a political group that wants you to vote for their special interest candidate. I agree with AD, those things are taking over the phone and are nasty.
from visual import*
wallA = box(pos=vector(0,6,0), size=vector(12.1,0.2,12.1), color=color.red)
wallB = box(pos=vector(0,-6,0), size=vector(12.1,0.2,12.1), color=color.green)
wallC = box(pos=vector(6,0,0), size=vector(0.2,12.1,12.1), color=color.yellow)
wallD = box(pos=vector(-6,0,0), size=vector(0.2,12.1,12.1), color=color.yellow)
wallE = box(pos=vector(0,0,-6), size=vector(12.1,12.1,0.2), color=color.yellow)
ball=sphere(pos=vector(0,0,0), radius=0.20, color=color.white)
ball.vel=vector(1.5,-.9,-1.9)
vscale=3.0
dt=0.01
velarrow=arrow(pos=ball.pos, axis=ball.vel, color=color.blue)
ball.trail=curve(pos=[ball.pos], color=color.white)
t=0
scene.autoscale=false
while t<10:
rate(1/dt)
t=t+dt
if ((ball.pos.y-ball.radius+ball.vel.y*dt)<wallB.pos.y+0.5*wallB.height):
ddt=(wallB.pos.y+0.5*wallB.height-ball.pos.y+ball.radius)/ball.vel.y
ball.pos=ball.pos+ball.vel*ddt
ball.trail.append(ball.pos)
ball.vel.y=-ball.vel.y
ball.pos=ball.pos+ball.vel*(dt-ddt)
else:
ball.pos=ball.pos+ball.vel*dt
if ((ball.pos.y+ball.radius+ball.vel.y*dt)>wallA.pos.y-0.5*wallA.height):
ddt=(wallA.pos.y-0.5*wallA.height-ball.pos.y-ball.radius)/ball.vel.y
ball.pos=ball.pos+ball.vel*ddt
ball.trail.append(ball.pos)
ball.vel.y=-ball.vel.y
ball.pos=ball.pos+ball.vel*(dt-ddt)
else:
ball.pos=ball.pos+ball.vel*dt
if ((ball.pos.x+ball.radius+ball.vel.x*dt)>wallC.pos.x-0.5*wallC.length):
ddt=(wallC.pos.x-0.5*wallC.length-ball.pos.x-ball.radius)/ball.vel.x
ball.pos=ball.pos+ball.vel*ddt
ball.trail.append(ball.pos)
ball.vel.x=-ball.vel.x
ball.pos=ball.pos+ball.vel*(dt-ddt)
else:
ball.pos=ball.pos+ball.vel*dt
if ((ball.pos.x-ball.radius+ball.vel.x*dt)<wallD.pos.x+0.5*wallD.length):
ddt=(wallD.pos.x+0.5*wallD.length-ball.pos.x+ball.radius)/ball.vel.x
ball.pos=ball.pos+ball.vel*ddt
ball.trail.append(ball.pos)
ball.vel.x=-ball.vel.x
ball.pos=ball.pos+ball.vel*(dt-ddt)
else:
ball.pos=ball.pos+ball.vel*dt
if ((ball.pos.z-ball.radius+ball.vel.z*dt)<wallE.pos.z+0.5*wallE.width):
ddt=(wallE.pos.z+0.5*wallE.width-ball.pos.z+ball.radius)/ball.vel.z
ball.pos=ball.pos+ball.vel*ddt
ball.trail.append(ball.pos)
ball.vel.z=-ball.vel.z
ball.pos=ball.pos+ball.vel*(dt-ddt)
else:
ball.pos=ball.pos+ball.vel*dt
if ((ball.pos.z+ball.radius+ball.vel.z*dt)>(-wallE.pos.z)-0.5*wallE.width):
ddt=((-wallE.pos.z)-0.5*wallE.width-ball.pos.z-ball.radius)/ball.vel.z
ball.pos=ball.pos+ball.vel*ddt
ball.trail.append(ball.pos)
ball.vel.z=-ball.vel.z
ball.pos=ball.pos+ball.vel*(dt-ddt)
else:
ball.pos=ball.pos+ball.vel*dt
ball.pos=ball.pos+ball.vel*dt
velarrow.pos=ball.pos
velarrow.axis=ball.vel
ball.trail.append(ball.pos)
print "End of program. Ending time is ", t,"seconds."
print "Final Position of ball is ", ball.pos,"."
This code works just fine with vpython and python27. What is your exact traceback error message?
Using the Tkinter GUI toolkit that comes with Python you can use the password option this way:
# Tkinter, explore the entry field for passwords!
from Tkinter import *
def showme():
# clear the label
label2.config(text='')
# get the enter1 text and display in label
label2.config(text=enter1.get())
root = Tk()
# create a data entry widget
enter1 = Entry(root)
# forces Entry to echo as char "*"
enter1["show"] = "*"
# create a label widgets
label1 = Label(root, text='Type password here:')
label1.pack(side='top', fill=X) # topmost
# start enter1 empty
enter1.insert(0, '')
enter1.pack(side='top', fill=X) # below label1
label2 = Label(root)
label2.pack(side='top', fill=X) # below entry1
# cursor in enter1 field
enter1.focus()
# get entry text on Enter-key
enter1.bind('<Return>', (lambda event: showme()))
# or get entry text clicking on button
btn1 = Button(root, text='Get Text', command=showme)
btn1.pack(side='left')
root.mainloop()
It is never a good idea to change the same object you are iterating over in the loop. Simply create a new object and do the changes on that object.
You have to use the player instance and not the class name, also make player global since you create it in main():
import pygame
pygame.init()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("evin.png")
self.image = self.image.convert()
tranColor = self.image.get_at((1, 1))
self.image.set_colorkey(tranColor)
self.rect = self.image.get_rect()
self.x = 300
self.y = 300
self.rect.center = (self.x, self.y)
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
self.y -= 5
if keys[pygame.K_DOWN]:
self.y += 5
if keys[pygame.K_LEFT]:
self.x -= 5
if keys[pygame.K_RIGHT]:
self.x += 5
self.rect.center = (self.x, self.y)
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("enemy.png")
self.image = self.image.convert()
tranColor = self.image.get_at((1, 1))
self.image.set_colorkey(tranColor)
self.rect = self.image.get_rect()
self.x = 300
self.y = 200
self.rect.center = (self.x, self.y)
def update(self):
global player
if self.x < player.x:
self.x += 1
self.rect.center = (self.x, self.y)
elif self.x > player.x:
self.x -= 1
self.rect.center = (self.x, self.y)
if self.y < player.y:
self.y += 1
self.rect.center = (self.x, self.y)
elif self.y > player.y:
self.y -= 1
self.rect.center = (self.x, self.y)
def main():
global player
'Create the screen'
screen = pygame.display.set_mode((640, 480))
'Set the background'
background = pygame.Surface(screen.get_size())
background.fill((0, 0, 0))
'call the object'
player = Player()
enemy = Enemy()
'add object to group'
allSprites = pygame.sprite.Group(player)
enemySprites = pygame.sprite.Group(enemy)
clock = pygame.time.Clock()
keepGoing = True
while keepGoing:
clock.tick(30)
' handle events'
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
allSprites.clear(screen, background)
enemySprites.clear(screen, background)
allSprites.update()
enemySprites.update()
allSprites.draw(screen)
enemySprites.draw(screen)
pygame.display.flip()
if __name__ == "__main__":
main()
This could help you to get started with Jython (Java based Python):
http://www.daniweb.com/software-development/python/threads/191210/1565073#post1565073
Before enumerate() came around, you would have incremented the index this way:
def count_data_types(a_list):
answer = [0,0,0]
for x in a_list:
ind = 0
for t in (int, float, str):
if t == type(x):
answer[ind] += 1
ind += 1
return answer
print(count_data_types(['v', 3.0,1, 'etc']))
'''
[1, 1, 2]
'''
You can also use a dictionary approach as this example shows:
# create multiple Tkinter buttons using a dictionary:
import Tkinter as tk
def text_update(animal):
text.delete(0, tk.END)
text.insert(0, animal)
root = tk.Tk()
text = tk.Entry(root, width=35, bg='yellow')
text.grid(row=0, column=0, columnspan=5)
btn_dict = {}
col = 0
words = ["Dog", "Cat", "Pig", "Cow", "Rat"]
for animal in words:
# pass each button's text to a function
action = lambda x = animal: text_update(x)
# create the buttons and assign to animal:button-object dict pair
btn_dict[animal] = tk.Button(root, text=animal, command=action)
btn_dict[animal].grid(row=1, column=col, pady=5)
col += 1
# run the GUI event loop
root.mainloop()
You got to let us know why it isn't passing?
Here is example ...
# one look at the Tkinter Text widget
# use ctrl+c to copy, ctrl+x to cut selected text,
# ctrl+v to paste, and ctrl+/ to select all
# text area can be scrolled with mouse wheel
import Tkinter as tk
root = tk.Tk()
# create the text widget
# width=width in chars, height=lines of text
text = tk.Text(root, width=50, height=5, wrap='none', bg='yellow')
text.pack()
abc = "hello world"
# show result in text widget
text.insert('insert', abc)
# start cursor in the text widget
text.focus()
root.mainloop()
This year I'm a little bit older, a little bit rounder, but still none the wiser.
--- Karl Arm
I like Editra, works great for a number of programming languages.
Windows adds '\n\r' combo to the input() and Python 3.2 only removed the '\n', retaining the '\r' character. This bothersome bug is fixed in Python 3.2.1
Yeah, good idea thanks to narue!
# one short look at counters/accumulators
# tested with Python 3.2.1
class Count:
k = 0
def counter(self):
self.k += 1
return self.k
# this allows you to simply call Count.counter()
counter = classmethod(counter)
# test ...
for k in range(5):
print(Count.counter())
'''
1
2
3
4
5
'''
# one short look at counters/accumulators
# tested with Python 3.2.1
def xcounter():
"""
generator function (yield replaces return)
increments by one each call
"""
k = 0
while True:
k += 1
yield k
# next is needed with generator functions
# with Python2 use .next
# with Python3 use .__next__
counter = xcounter().__next__
for k in range(5):
print(counter())
'''
1
2
3
4
5
'''