def f(x): ans = 2*x**3 - 3*x**2 - 5*x + 6 if ans == 0: print(ans, "=", x) for x in range(-10, 10): f(x)
Showing posts with label python. Show all posts
Showing posts with label python. Show all posts
Python | Polynomial finder (factors of x)
Yes, this is great :'), at first it printed all the numbers with what they were equivalent too, but I just made it so it only spits out the ones that equal 0, I'l try to make is so if there's only 2, it will find the third one by looking at (n) and seeing what else could be used to equal (n) by division or something, but that's for another day, adios amigos. (I know it's simple, but it works)
Python | wxPython
I'm just gonna leave this here...
import wx class bucky(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, 'Title.xom', size=(600, 400)) pos1 = 10 panel = wx.Panel(self) button = wx.Button(panel, label='Touch Me', pos=(pos1, 10), size=(60, 30)) self.Bind(wx.EVT_BUTTON, self.closebutton, button) self.Bind(wx.EVT_CLOSE, self.closewindow) status = self.CreateStatusBar() menubar = wx.MenuBar() first = wx.Menu() second = wx.Menu() first.Append(wx.NewId(), "New Window", "This is a new window") second.Append(wx.NewId(), "Open", "This will open me... :)") menubar.Append(first, "File") menubar.Append(second, "Edit") self.SetMenuBar(menubar) def closebutton(self, event): self.Close(True) def closewindow(self, event): self.Destroy() app = wx.App() frame = bucky(parent=None, id=-1) frame.Show() app.MainLoop()
Trinomial Solver
Aaaaaaand here is my first program in like 3 weeks, well, in Python at least, pretty simple but idc, till next time.
from math import sqrt def tri(a, b, c): x = (-b)-sqrt(b**2-(4*a*c)) y = 2*a x2 = (-b)+sqrt(b**2-(4*a*c)) q = x/y q2 = x2/y print('{:.2f}'.format(q)) print('{:.2f}'.format(q2))
Python | Pygame | True
All I can say, is finally.
import pygame, math from pygame import * DISPLAY = (800,640) DEPTH = 32 FLAGS = 0 ############################################################## # Classes! class Entity(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) ############################################################## class Player(Entity): def __init__(self, x, y): Entity.__init__(self) self.xvel = 0 self.yvel = 0 self.onGround = False self.image = Surface((32, 32)) self.image.convert() self.image.fill(Color("#FF0000")) self.rect = Rect(x, y, 32, 32) ############################################################## def update(self, up, down, left, right, platforms): if up: # Only jump if on the ground if self.onGround: self.yvel -= 10 if down: pass if left: self.xvel = -5 if right: self.xvel = 5 if not self.onGround: # Only accelerate with gravity if in the air self.yvel += 0.3 # Max falling speed if self.yvel > 30: self.yvel = 30 if not (left or right): self.xvel = 0 # Increment in x direction self.rect.left += self.xvel # Do x-axis collisions self.collide(self.xvel, 0, platforms) # Incrememnt in y direction self.rect.top += self.yvel # Assuming we're in the air self.onGround = False; # Do y-axis collisions self.collide(0, self.yvel, platforms) ############################################################## def collide(self, xvel, yvel, platforms): for p in platforms: if sprite.collide_rect(self, p): if isinstance(p, ExitBlock): event.post(event.Event(QUIT)) if xvel > 0: self.rect.right = p.rect.left if xvel < 0: self.rect.left = p.rect.right if yvel > 0: self.rect.bottom = p.rect.top self.onGround = True self.yvel = 0 if yvel < 0: self.rect.top = p.rect.bottom ############################################################## class Platform(Entity): def __init__(self, x, y): Entity.__init__(self) self.image = Surface((32, 32)) self.image.convert() self.image.fill(Color("#DDDDDD")) self.rect = Rect(x, y, 32, 32) def update(self): pass ############################################################## class ExitBlock(Platform): def __init__(self, x, y): Platform.__init__(self, x, y) self.image.fill(Color("#0033FF")) ######################################################################################################################### def main(): pygame.init() screen = display.set_mode(DISPLAY, FLAGS, DEPTH) display.set_caption('Use arrows to move!') timer = time.Clock() up = down = left = right = False bg = Surface((32, 32)) bg.convert() bg.fill(Color("#000000")) entities = pygame.sprite.Group() player = Player(32, 32) platforms = [] ############################################################## x = y = 0 level = [ "PPPPPPPPPPPPPPPPPPPPPPPPP", "P P", "PP P", "P PP P", "P PPP P", "P PPPP P", "P PPPPP P", "P PPPPP P", "P P", "P P", "P PP", "P P P", "P PPPPP P", "P PPP P", "P EEE P", "P P", "P P P", "P P", "P P", "PPPPPPPPPPPPPPPPPPPPPPPPP",] ############################################################## for row in level: for col in row: if col == "P": p = Platform(x, y) platforms.append(p) entities.add(p) if col == "E": e = ExitBlock(x, y) platforms.append(e) entities.add(e) x += 32 y += 32 x = 0 ############################################################## entities.add(player) running = True while running: timer.tick(100) for e in pygame.event.get(): if e.type == QUIT: running = False if e.type == KEYDOWN and e.key == K_UP: up = True if e.type == KEYDOWN and e.key == K_DOWN: down = True if e.type == KEYDOWN and e.key == K_LEFT: left = True if e.type == KEYDOWN and e.key == K_RIGHT: right = True if e.type == KEYUP and e.key == K_UP: up = False if e.type == KEYUP and e.key == K_DOWN: down = False if e.type == KEYUP and e.key == K_LEFT: left = False if e.type == KEYUP and e.key == K_RIGHT: right = False ############################################################## # Draw the background for y in range(20): for x in range(25): screen.blit(bg, (x * 32, y * 32)) # Update the player, draw everything else player.update(up, down, left, right, platforms) entities.draw(screen) pygame.display.flip() ############################################################## main() pygame.quit() ##############################################################
Python | Late to #CLASSES (geddit lel)
Finally, I have gotten the balls to start learning classes, haven't quite got the hang of them, but they are pretty interesting, so, look forward to great things, btw, I still have not given up my goal of creating a snake game before 2013 comes to it's end, I will, trust me, i will.
import math as _math class Math(): def __init__(self, x, y): self.x = x self.y = y self.result = 0 def __str__(self): return str(self.result) class Pythagorus(Math): def calculate(self): self.result = _math.sqrt(self.x ** 2 + self.y ** 2) obj = Pythagorus(8,5) obj.calculate() print(obj) class Person(): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return 'Hi! My name is {} and I am {} years old!'.format(self.name,self.age) class Student(Person): def __init__(self, name, age, loans): Person.__init__(self, name, age) self.loans = loans def __str__(self): return 'Hi! My name is {} and I am {} years old! But I owe ${} :/'.format(self.name, self.age, self.loans) person = Student('Samir',16,1002) print(person) class Person(): def __init__(self, name, age): self.name = name self.age = age def __str__(self): print('Person - ') return "My name is {}. I am {} years old. ".format(self.name, self.age) class Military(Person): def __init__(self, name, age, rank): Person.__init__(self, name, age) self.rank = rank def __str__(self): print('Military - ') return Person.__str__(self) + "I am a {}".format(self.rank) class Teacher(Person): def __init__(self, name, age, sub): print('Teacher - ') Person.__init__(self, name, age) self.sub = sub def __str__(self): return Person.__str__(self) + "I teach {}".format(self.sub) class Student(Person): def __init__(self, name, age, loans): Person.__init__(self, name, age) self.loans = loans class Animal: def __init__(self, name, bark): self.name = name self.bark = bark def Dog(self): print('{} is a dog, and dogs go {}!'.format(self.name, self.bark)) d1 = Animal('Rufus', 'Woof!') d1.Dog() class Person: population = 0 def __init__(self, name, age): self.name = name self.age = age print('{} has been born!'.format(self.name)) Person.population += 1 def __str__(self): return '{} is {} years old'.format(self.name, self.age) def __del__(self): print('{} is dying! :('.format(self.name)) Person.population -= 1 def totalPop(): print('There are {} people in the world.'.format(Person.population)) p1 = Person('Johnny', 20) print(Person.population) p2 = Person('Mary', 27) print(Person.population) print(p1) print(p2) class Student: def __init__(self, name): self.name = name self.attend = 0 self.grades = [] def addGrades(self, grade): self.grades.append(grade) def attendDay(self): self.attend += 1 def getAverage(): return sum(self.grades) / len(self.grades)
Python | Science
I can honestly say, this is the funnest piece of code, i've ever written, don't ask why, it just is.
n = {} for line in open('periodic_table.txt'): number, element = line.split() n[number] = element n2 = {} for line in open('periodic_table.txt'): element, number = line.split()[::-1] n2[element] = number n.update(n2) q = input('Enter element number or element name: ') while q: try: if q.isdigit(): print('Element number {} is {}'.format(q,n[q])) else: print('Element number for {} is {}'.format(q,n[q])) except: print("That's not an element!") q = input('Enter element number or element name: ')
Python | Nifty lil thang
Well, this could come in useful soon.
n = {} for line in open('french.txt'): english, french = line.split() n[english] = french n2 = {} for line in open('french.txt'): french, english = line.split()[::-1] n2[french] = english n.update(n2) for k, v in n.items(): print(k, ':', v)
Python | Revision test | Chemistry
Hopefully this will help me
while 1: a = 'NaCO3 + 2HCl -> 2NaCl + H2O + CO2' b = 'Pb(NO3) + 2Kl -> Pbl2 + 2KNO3' c = 'Zn + 2HCl -> ZnHCl2 + H2' aa = input("What's the WE for Sodium carbonate + Hydrochloric acid? ") if aa == a: print('correct!') else: print('no') bb = input("What's the WE for Pottasium iodide + Lead nitrate? ") if bb == b: print('correct!') else: print('no') cc = input('What\'s the WE for Hydrochloric acid + Zinc metal? ') if cc == c: print('correct!') else: print('no')
Python | Pygame collision
This is what I did, from a tutorial :'(
import pygame pygame.init() size = (1400, 800) window = pygame.display.set_mode(size) pygame.display.set_caption('Window') white = (255, 255, 255) black = (0,0,0) red = (255,25,25) moveX, moveY = 0, 0 clock = pygame.time.Clock() def detect(x1, y1, w1, h1, x2, y2, w2, h2): if x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 >= y2: return True elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 >= y2: return True elif x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 + h1 >= y2: return True elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 + h1 >= y2: return True else: return False class Sprite: def __init__(self,x,y): self.x = x self.y = y self.width = 50 self.height = 50 def render(self, coll): if coll: pygame.draw.rect(window, red, (self.x, self.y, self.width, self.height)) elif coll is False: pygame.draw.rect(window, black, (self.x, self.y, self.width, self.height)) Sprite1 = Sprite(100,150) Sprite2 = Sprite(200, 250) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: moveX = -5 if event.key == pygame.K_RIGHT: moveX = 5 if event.key == pygame.K_UP: moveY = -5 if event.key == pygame.K_DOWN: moveY = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: moveX = 0 if event.key == pygame.K_RIGHT: moveX = 0 if event.key == pygame.K_UP: moveY = 0 if event.key == pygame.K_DOWN: moveY = 0 window.fill(white) Sprite1.x+=moveX Sprite1.y+=moveY coll = detect(Sprite1.x, Sprite1.y, Sprite1.width, Sprite1.height, Sprite2.x, Sprite2.y, Sprite2.width, Sprite2.height) Sprite1.render(coll) Sprite2.render(False) clock.tick(120) pygame.display.flip() pygame.quit()
Python | NCSS Week 3
So, I got 100% second week in a row..... hehehehehheheheh ok,
here are the notes in which I used, PLUS at the very bottom is the problem that took me the longest to solve, I bet the solution is way shorter than my response, but whoooo carrreesssss
here are the notes in which I used, PLUS at the very bottom is the problem that took me the longest to solve, I bet the solution is way shorter than my response, but whoooo carrreesssss
# Looping over characters # Time to combine some of our skills. We want to use our understanding # of strings, the len function and while loops to print out each # character of a string, one per line ''' word = 'Grok' i = 0 while i < len(word): print(i, word[i]) i += 1 ''' # String methods # Since we're discussing strings, let's go over some more useful # string methods. We've seen how to call a method on a string object, (like upper) # and introduced a couple of string methods for converting # strings to uppercase and lowercase, and replacing bits of # a string with other strings. ''' s = 'hello world' print(s.startswith('hello')) print(s.endswith('rld')) ''' # Removing whitspace from around a string. ''' s = ' abc ' print(s.strip()) print(s.lstrip()) print(s.rstrip()) s = 'hello world' print(s.find('w')) print(s.find('x')) ''' # Finding factots - the problem # Let's look at a worked example using loops. We want to write a program # to find all the factors of 540. A factor of a number n is an int # that can be multiplied by another int to give n. For example, the factors # of 9 are; 1,2,4 and 8 since: ''' 1 x 8 = 8 2 x 4 = 8 ''' # And the factors of 24 are 1,2,3,4,6,8,12 and 24: ''' 1 x 24 = 24 2 x 12 = 24 3 x 8 = 24 4 x 6 = 24 ''' # One way of finding factors is to use your calculator and checking all the numbers less # than n one by one, This works well for small numbers (like 24) # but quicly becomes impractical for larger numbers (like 540). # Can you solve it faster using Python? # Finding factots - the algorithm # The first step in solving a programming problem is work out # the algorithm or method that we need to follow. # The simplest approuch is to mimic what you would do by hand # using your calculatr | Cheching each number one by one is called # brute force solution, Computers are so fast at doing basic calculations # that the brute force solution is often a good one for problems like this. # Let's write down the individual steps we need to follow: # 1. Choose the first number to test, start with 1: # 2. See if that number divided evenly into 540 using the modulus # operator, if it does print it out as a factor: # 3. Choose the next number by adding 1 to your last choice: # 4. If your number to test is greater than 540 then you have finished, # otherwise go back to step 2. # HA, i did it by myself wotofit ''' i = 1 x = 54324235435 while i <= x: if x % i == 0: print(i) i += 1 ''' # When a for loops is best # Every problem that can be solved using a while loop can also be # solved using a for loop (and vice versa) So how do you know # which one to use? # Generall, when you know how many iteratios you need ( either a set # number ot to iterate through a list) it is easier to use a for loop) # For example ''' colours = ['red', 'blue', 'green'] for i in colours: print(i) ''' # When a while loop is best # Generally, when you don't know how many iterations you need, # and you want to keep looping while some condition is true # a while loop is better, for example: ''' sum = 0 limit = 10 i = 0 while sum < limit: sum += i print(i, sum) i += 1 ''' # Storing multiple values # Imagine writing a program to store a ranking of your favourite # authors. Given what you know so far, you would use a seperate # variable for each author's name and mention each variable to print them ''' authors = ["J.K. Rowling", "P. Pullman", "S. Collins"] print(authors[0]) print(authors[1]) print(authors[2]) authors = ["J.K. Rowling", "P. Pullman", "S. Collins"] for author in authors: print(author) ''' ''' numbers = input('What are ur fave numbers: ') nums = numbers.split() for i in nums: print (i) ''' # Phonic tester ''' line = None while line != '': line = input('Line: ') if line == '': break phonic = line.split() start = phonic[0] start_4 = phonic [3] a = start[0] if start_4.startswith(a): print('Good!') else: print("That's not right!") ''' # Accessing list elements # List items can be accessed using indexing (a.k.a subscripting) ''' colours = ['red', 'blue', 'green', 'yellow'] print(colours[1]) print(colours[-1]) ''' # Modifying list elements # You may remember from earlier that strings are # Immutable, which means that you cannot change their value. # If you try to alter a character in a string, Python will # Complain with a type error! # Lists are different. List elements can be modified by assigning to # Subscripts: ''' colours = ['red', 'blue', 'green', 'yellow'] colours[0] = 'crimson' colours[-2] = 'lime' print(colours) ''' # Appending and sorting # There are various list methods that can be used to modify lists. # The append methos adds an item to the end of the list: ''' numbers = ['one', 'two', 'three'] numbers.append('four') print(numbers) ''' # The sort() method sorts the items in order, e.g. string in # alphabetical order and numbers in ascending order. ''' pets = ['dog','mouse','fish','cat'] pets.sort() print(pets) ''' # The reverse() method sorts the items in reverse order: ''' pets = ['dog','mouse','fish','cat'] pets.reverse() print(pets) ''' # Reversing a list # The reverse method reverses the order of the entire list. # Just like the string methods we saw last week, notice that calls # to list method name, seperated by a dot, e.g. pets.reverse() # Any other values the method needs to do its job is provided in a # normal way e.g 'cat' is given as an extra argument inside the round # brackets inn pets.append('cat') # Unlike methods applied to strings, notice that these methods modify # the original lists rather than creating new ones and so they don't return # a value. You can tell this because there is no output when you type them into # the interpreter, so we need to put pets on a separate line to see what happened # to our list. # Looping with append # Say we want to sort some books for the library catalogue. We ask the user which books they # are returning (one at a time), and then want to print them out in alphabetical order. ''' books = [] book = None while book != '': book = input('What book are you returning? ') books.append(book) books.sort() for i in books: print(i) ''' # List of characters and words # Lists can be constructed from strings using the list builtin function ''' print(list('hello')) ''' # Splitting on other characters # You can also split strings using other characters, or strings, as the seperator, For example # sometimes you may want to split a string using the colon character ':' ''' text = input('text: ') line = text.split(':') for i in line: print(i) ''' # Creating sublists from lists # Slicing also works like on strings to create a new sublist: ''' a = ['red','blue','green','yellow'] less = a[:2] print(less) ''' # This is useful for checking if a word is in a string: ''' words = ['the', 'fox', 'jumped', 'over', 'the', 'dog'] print('jumped' in words) ''' # Joinging a list of strings # Another useful string method is join which joins a list of strings back together using # a string as a seperator ''' sep = ':' val = ['a','b','c','d'] print(sep.join(val)) ''' # Splitting and joining # You'll often see a literal string (like the space ' ') used: ''' val = ['a','b','c','d'] print('.'.join(val)) ''' # This is handy when you want to remove duplicate spaces from use input. ''' msg = input('Enter your letters: ') letters = msg.split() print('.'.join(letters)) ''' # If the user enters a series of letters with extra spaces between them, # the program removes these spaces and prints them out with a single space separating each. # Checking if a word is alphabetical, reversed, or not in any order. ''' word = input('Word: ') word = word[0].lower() + word[1:].lower() al = list(word) al2 = al.sort() al3 = ''.join(al) al_2 = al.reverse() al_3 = ''.join(al) alpha = al3 revd = al_3 same = word[0] * len(word) if word == alpha: print('alphabetical') elif word == revd: print('reverse alphabetical') elif word != alpha or revd: print('not alphabetical in any way') ''' # Like Yoda, you speak # Yoda speaks in a bit of a strange way. Imagine you wanted to write a program to speak like # Yoda. Your program reads in four words from the user and moves them around to create a # sentence that sounded like Yoda # he is your father # --> # your father he is # Using a list structure makes this program quite easy to write. Lets write on that # reads in a single line of text and moves the words around using lists. Like always we first # break the problem down into smaller steps: # 1. Read the line of text # 2. Seperate the line into a list of two words # 3. Change the words to Yoda-speak order # 4. Print out the new text. ''' line = input('You say: ') yoda = line.split() yoda = yoda[2] + ' ' + yoda[3] + ' ' + yoda[0] + ' ' + yoda[1] print('Yoda says: ', yoda) ''' rule = [] broken = [] tb = 0 tr = 0 line = ' ' while line: lines = input('Line: ') line = lines.split() for word in line: if 'ie' in word: if 'cie' in word: tb += 1 elif word.count('cie') > 1: tb += 1 elif word.count('ie') > 1: tr += 1 elif 'ie' in word: tr += 1 if 'ei' in word: if 'cei' in word: tr += 1 elif word.count('cei') > 1: tr += 1 elif word.count('ei') > 1: tb += 1 elif 'ei' in word: tb += 1 print('Number of times the rule helped: {0}'.format(tr)) print('Number of times the rule was broken: {0}'.format(tb))
Python | O.M.G lol pygame is SO GREAT.
SO I FINALLY LEARNT HOW TO ADD IMAGES, USE KEY EVENTS, AND SET BACKGROUNDS, I MADE SOMETHING THAT WILL REVOLUTIONIZE THE WORLD (aka it's useless)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | # Importing pygame import pygame # Initializing pygame pygame.init() # Setting window and title window = pygame.display.set_mode((800,450)) pygame.display.set_caption('Mover') # Defining colors black = (0,0,0) white = (255, 255, 255) # Image mario = pygame.image.load('m1.png').convert_alpha() bg = pygame.image.load('bg.jpg') bg = pygame.transform.scale(bg, (800,450)) gun = pygame.image.load('gun.png') gun = pygame.transform.scale(gun, (140, 95)) # Running running = True # Defining the clock clock = pygame.time.Clock() # Identifying coordinates x, y = 0,0 moveX, moveY = 0,0 # Main Loop while running: for event in pygame.event.get(): # If X is clicked, running = False, which causes loop to exit. if event.type == pygame.QUIT: running = False # If key is pressed, add {} to (var) if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: moveX = -5 if event.key == pygame.K_RIGHT: moveX = 5 if event.key == pygame.K_UP: moveY = -5 if event.key == pygame.K_DOWN: moveY = 5 # Same if key, except all (var) = 0 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: moveX = 0 if event.key == pygame.K_RIGHT: moveX = 0 if event.key == pygame.K_UP: moveY = 0 if event.key == pygame.K_DOWN: moveY = 0 # Make background color white window.blit(bg, (0,0)) # Define x and y x += moveX y += moveY # Draw a rectangle, set it to relative coordinates # pygame.draw.rect(window, black, (x, y, 25, 25)) # Set image to coordinates window.blit(gun, (x,y)) # Set frames per second clock.tick(50) # Required command pygame.display.flip() # Exit when loop is False pygame.quit() |