text
stringlengths
37
1.41M
""" I made this application because I cannot use GIMP that well. In fact it was the most iritating experience for me, trying to make tileset of 50 images. One pixel mistake and you can do it again. That is why I created this. It creates a tileset.png out of all png files located in \tiles\ directory. """ from PIL import Image import sys class Tileset(object): def __init__(self): # x and y is the width and height of the tile (self.x, self.y) = (70, 70) # width represents how many tiles we want to have in one line self.width = 10 # separators will separate tiles from each other (self.xs, self.ys) = (1, 1) @staticmethod def load_tiles(): import glob names = glob.glob('tiles/*.png') tiles = [] for i, tile in enumerate(names): tiles.append(Image.open(tile)) tiles[i].convert("RGBA") return tiles def create_image(self): import math tiles = self.load_tiles() x = self.x * self.width + self.width * self.xs - self.xs row = math.ceil(len(tiles) / self.width) y = self.y * row + row * self.ys - self.ys new_im = Image.new('RGBA', (x, y)) a = 0 i = 0 while i < y and a < len(tiles): j = 0 while j < x and a < len(tiles): new_im.paste(tiles[a], (j, i)) j += self.x + self.xs a += 1 i += self.y + self.ys return new_im def main(): new = Tileset() ''' If you want to change Tile size you should do it here new.x = 30 new.y = 30 10 tiles in one row is too much? new.width = 5 now it is changed to 5 change new.xs and new.xy if you want tiles to be separated differently ''' tileset = new.create_image() tileset.save("tileset.png", "PNG") return 0 if __name__ == '__main__': sys.exit(main())
import sqlite3 #Cria as databases que serão manipuladas pela main. conn = sqlite3.connect('nome_aluno.db') cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS nome_aluno ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome TEXT NOT NULL ); """) conn = sqlite3.connect('resposta.db') cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS resposta ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, id_aluno INTEGER NOT NULL, id_prova INTEGER NOT NULL, resposta TEXT, FOREIGN KEY (id_aluno) REFERENCES nome_aluno(id) ); """) conn = sqlite3.connect('gabarito.db') cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS gabarito ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, id_prova INTEGER NOT NULL, peso TEXT, gabarito TEXT, FOREIGN KEY(id_prova) REFERENCES resposta(id_prova) ); """) conn.close
def fact(n): # recursive function to calculate the factorial of a given input if n==1: return 1 else: j= n*fact(n-1) return j k=int(input("Enter the input")) # getting input from the user n=fact(k) print(n)
def pivotIndexOptimized(nums): if len(nums) <= 2: return -1 left_sum, pivot, right_sum = 0, 0, sum(nums[1:]) if left_sum == right_sum: return pivot for i in range(len(nums) - 1): left_sum += nums[pivot] pivot += 1 right_sum -= nums[pivot] if left_sum == right_sum: return pivot return -1 print("enter the element in an array") a=[int(x) for x in input().split()] k= pivotIndexOptimized(a) print(k)
a=input("Enter the first binary string :") b=input("Enter the second binary string : ") a= int(a,2) b= int(b,2) c= bin(a+b) c=c[2:] print(c) # k=max(len(a),len(b)) # l=min(len(a),len(b)) # addZero=k-l # print(addZero) # if len(a)>len(b): # for z in range(addZero): # b='0'+b # else: # for z in range(addZero): # a='0'+a # # c='' # total=int(a)+int(b) # print(total)
class Solution : def searchInsert(self,nums,target): i=0 if(nums[0]>target) : return 0 elif(nums[-1]<target): return len(nums) else : while(i<len(nums)): if(nums[i]==target): return i elif(nums[i]>target): return i i=i+1 print("Enter the numbers: ") a=[int(x) for x in input().split()] target=int(input("Enter the number needs to be searched/inserted ")) sol=Solution() k=sol.findTarget(a,target) print(k)
def findPattern(pattern,str): str = str.split() dict = {} for k in range(len(pattern)): if dict[pattern[k]]==str[k]: print("ok") elif dict[pattern[k]]!=str[k] and pattern[k] not in dict.keys(): dict[pattern[k]]=str[k] else: return False return True a=input("enter the pattern: ") b=input("enter the string: ") giru=findPattern(a,b) print(giru)
def sort(prices): if not prices: return 0 arr.sort() profit = arr[-1] - arr[0] return profit arr=[] for i in range(1,6): arr.append(int(input("Enter the %d price : "%i))) k=sort(arr) print(k)
lst = list() while (True): inp = raw_input("Enter a number: ") if inp == "done" : break if inp == 'Done': break inp = float(inp) lst.append(inp) #print "Debug:", lst print max(lst) print min (lst)
def primes_until_n(n): noprimes = [j for i in range(2, int(n ** (1 / 2)) + 1) for j in range(i * 2, n + 1, i)] return [x for x in range(2, n + 1) if x not in noprimes] def give_n_primes(n): return [p for p in [a for a in range(1, (n ** 2 + 1)) if all([(a % b != 0) for b in range(2, a)])][1:n]] # n = input("n: ") n = 21 # print(primes_until_n(n)) print(give_n_primes(n)) ''' from itertools import count, islice primes = (n for n in count(2) if all(n % d for d in range(2, n))) print("100th prime is %d" % next(islice(primes, 99, 100))) [p for p in [a for a in range(1,1000) if all([(a % b != 0) for b in range(2, a)])][:input('How many prime numbers? ')]] [p for p in [a for a in range(1,1000) if all([(a % b != 0) for b in range(2, a)])][1:n]] def give_n_primes(n): primes = [] # Loop through 9999 possible prime numbers for a in range(1, (n**2+1)): # Loop through every number it could divide by for b in range(2, a): # Does b divide evenly into a ? if a % b == 0: break # Loop exited without breaking ? (It is prime) else: # Add the prime number to our list primes.append(a) # We have enough to stop ? if len(primes) == n: return primes '''
def staircase(n): for i in range(n): print(' '*(n-i-1)+'#'*(i+1)) ''' for i in range(1,n+1): print(' '*(n-i)+'#'*(i)) for i in range(1,n+1): print(' '*(n-i)+'#'*i) for i in range(1,n): print(" "*(n - i - 1),"#"*i) print("#"*n) for i in range(n,0,-1): print("#"*(abs(n-i+1)), " "*(abs(i-n+1))) ''' n = 8 staircase(n)
import json myfile = json.load(open('TestDuplicateFile', 'r')) uniq = set() for p in myfile: if p in uniq: print "duplicate : " + p del p else: uniq.add(p) print uniq
''' --- Day 3: Spiral Memory --- ___,@ / < ,_ / \ _, ? \`/______\`/ ,_(_). |; (e e) ;| \___ \ \/\ 7 /\/ _\8/_ \/\ \'=='/ | /| /| \ \___)--(_______|//|//| \___ () _____/|/_|/_| / () \ `----' / () \ '-.______.-' _ |_||_| _ (@____) || (____@) \______||______/ You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this: 17 16 15 14 13 18 5 4 3 12 19 6 1 2 11 20 7 8 9 10 21 22 23---> ... While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1. For example: Data from square 1 is carried 0 steps, since it's at the access port. Data from square 12 is carried 3 steps, such as: down, left, left. Data from square 23 is carried only 2 steps: up twice. Data from square 1024 must be carried 31 steps. How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port? Your puzzle input is 289326. IMPORTANT SOURCES: https://en.wikipedia.org/wiki/Ulam_spiral#frb-inline https://www.youtube.com/watch?v=iFuR97YcSLM ''' import math ''' https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python Returns if a number is prime. Returns true if all numbers between 2 and 0 return !0 remainder. Might use this ''' def is_prime(n): if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) input = 289326 currentSpot = input oddLayer = math.ceil(math.sqrt(input)) #now we know what layer we are in manDistance = oddLayer - 1 numSteps = 0 oddIndex = (oddLayer-1)/2 if(oddIndex % 2 == 0): #odds are in favor if is_prime(input): numSteps = manDistance elif manDistance % 2 == 0: numSteps = manDistance - 1 else: numSteps = manDistance -oddIndex else: if is_prime(input): numSteps = manDistance elif manDistance % 2 == 0: numSteps = manDistance - oddIndex else: numSteps = manDistance - 1 print(numSteps)
''' Spiral primes Problem 58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? ''' import itertools #diagonalnih elementov: # 1-1 3-5 5-9 7-13 # stranica n, diagonalnih pa je ((n-1)/2)*4 + 1 #ko gremo na n=3 se pomaknemo 4x za 2 (da smo na diagonali) # n=5 4x za 4 # n=7 6 # n=2k+1 2k #iscemo, kdaj je ratio = prime / diagonalne < 0.1 def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: #vsa liha ostanejo d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True kandidat = 1 prastevila = 0 for k in itertools.count(1): n = 2 * k + 1 #dolzina stranice #if not n % 1001: # print(n) #napredek for _ in range(4): kandidat += 2 * k if prime(kandidat): prastevila += 1 if prastevila / (((n - 1) / 2) * 4 + 1) < 0.1: print(n) #26241 break
''' Permuted multiples It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' def st2set(n): '''stevke da v mnozico''' assert n >= 0 #zakaj pa ne stevke = set() while n != 0: stevke.add(n % 10) n //= 10 return stevke import itertools for i in itertools.count(1): if st2set(i) == st2set(2*i) == st2set(3*i) == st2set(4*i) == st2set(5*i) == st2set(6*i): print(f'tole iščemo: {i}') break #tole iščemo: 142857
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' # def je_deljivo_s_katerim_od(n, seznam): # if seznam == []: # return False # else: # return n % seznam[0] == 0 or je_deljivo_s_katerim_od(n, seznam[1:]) # # def prastevila_do(n): # if n <= 1: # return [] # elif je_deljivo_s_katerim_od(n, prastevila_do(n - 1)): # return prastevila_do(n - 1) # else: # return prastevila_do(n - 1) + [n] # # x = prastevila_do(10 ** 6) # # print(x[1001]) # # #presežemo rekurzijo, vendar bi to moglo delovati. def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: #vsa liha ostanejo d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True zaporedno = 0 n = 2 while True: if prime(n): zaporedno += 1 if zaporedno == 10001: print(n) break n += 1
''' Truncatable primes The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. ''' def prastevilo(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: #vsa liha ostanejo d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True def truncatable(n): if not prastevilo(n): return False shranjen_n = n while n > 0: #režemo z desne if not prastevilo(n): return False n //= 10 while shranjen_n > 0: #režemo z leve if not prastevilo(shranjen_n): return False shranjen_n = int(str((int(str(shranjen_n)[::-1]) // 10))[::-1]) # n = n brez prve števke return True kandidat = 10 #za <10 ne upoštevamo sez = [] while len(sez) != 11: if truncatable(kandidat): print(kandidat) sez.append(kandidat) kandidat += 1 print(sum(sez)) ''' 23 37 53 73 313 317 373 797 3137 3797 739397 sum = 748317 '''
""" singly-linked list """ class ListNode(object): def __init__(self): self.val = None self.next_node = None class LinkedList_handle: def __init__(self): self.cur_node = None def add(self, data): """add a new node pointed to previous node""" node = ListNode() node.val = data node.next_node = self.cur_node self.cur_node = node return node def print_ListNode(self, node): while node: if not isinstance(node.val, type(None)): if node.next_node: print('\nnode: ', node, ' value: ', node.val, ' next: ', node.next_node.val) else: print('\nnode: ', node, ' value: ', node.val, ' next: ', "NULL") else: print('\nnode: ', node, ' value: ', "NULL", ' next: ', "NULL") node = node.next_node def main(): print("===Singly-Linked List===") mylnklist = LinkedList_handle() n1 = ListNode() mylnklist.add(1) n2 = ListNode() mylnklist.add(2) n3 = ListNode() mylnklist.add(3) mylnklist.print_ListNode(mylnklist.cur_node) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Created on Fri Mar 17 10:34:56 2017 @author: nielton """ def ler_numeros(n): lista = [] for i in range(n): numero = int(input("Digite um número!")) lista.append(numero) return lista
from tkinter import * from TableTester import * def show_result(): resulttext.delete(1.0, END) resulttext.insert(INSERT, EpisodeFromShow(e1.get())) window = Tk() window.title("Random Episode Generator") label = Label(window, text="Enter your show:") label.grid(row=0, sticky=W) e1 = Entry(window, width=22) e1.grid(row=0, column=1, sticky=W) button = Button(window, text="Choose", width=10, command=show_result) button.grid(row=0, column=2, sticky=E) #frame = Frame(window) #frame.grid(row=1) resulttext = Text(window, width=40, height=3) resulttext.grid(row=1, columnspan=3) #resulttext.insert(INSERT, "") window.mainloop()
# Project Euler 15 - Lattice Paths def latticePaths(rows, columns): grid = list(list(1 for _ in xrange(columns+1)) for _ in xrange(rows+1)) for x in xrange(1, columns+1): for y in xrange(1, rows+1): grid[y][x] = grid[y-1][x] + grid[y][x-1] return grid[len(grid)-1][len(grid[0])-1] def main(): print latticePaths(20, 20) if __name__ == '__main__': main()
# 20 - Factorial Digit Sum from math import factorial def main(): print sum(int(d) for d in str(factorial(100))) if __name__ == '__main__': main()
while(True): try: texto = list(input()) i, b = False, False for n in range(len(texto)): if(texto[n] == '*' and not b): texto[n] = "<b>" b = True pass if(texto[n] == '*' and b): texto[n] = "</b>" b = False pass if(texto[n] == '_' and not i): texto[n] = "<i>" i = True pass if(texto[n] == '_' and i): texto[n] = "</i>" i = False pass pass print("".join(texto)) pass except EOFError: break
testes = int(input()) while (testes > 0): numeros = input().split() num1, num2 = numeros[0], numeros[1] if(len(num1)>= len(num2)): if(num1[len(num1)-len(num2):] == num2[:]): print("encaixa") pass else: print("nao encaixa") else: print("nao encaixa") testes -= 1
testes = int(input()) while testes>0: alfabeto = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split() frase = input() for i in frase: for j in alfabeto: if (i==j): alfabeto.remove(j) break pass pass pass if(len(alfabeto) == 0): print("frase completa") pass elif(len(alfabeto) <= 13): print("frase quase completa") pass else: print("frase mal elaborada") pass testes -= 1 pass
#!/usr/bin/python # -*- coding: utf8 -*- import math as m a= input ("Ingrese un numero : ") b= m.sin(a) c= m.cos(a) print ("El seno es ")(b) print ("El coseno es ")(c)
# Recursion - function calling itself def f(): print("f") def g(): print(g) f() # g() # RecursionError depth exceeded print("END") g() # error commented out # Control recursion with depth def controlled(depth): print("recursion depth", depth) if depth > 0: controlled(depth - 1) print("recursion depth", depth, "has closed.") controlled(10)
''' Searching problems (25pts) Complete the following 3 searching problems using techniques from class and from the notes and the textbook website. Solutions should use code to find and print the answer. ''' import re def split_line(line): # uses regular expressions to split line of text into word list return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line) # 1. (6pts) Write code which finds and prints the longest # word in the provided dictionary. If there are more # than one longest word, print them all. file = open('../Searching/dictionary.txt') list_of_words = [] word_len = 0 for line in file: line = line.strip().upper() words = split_line(line) for word in words: list_of_words.append(word) length_amount = [] length_list = [] for word in list_of_words: new_len = len(word) length_amount.append(new_len) length_amount.sort() if new_len == length_amount[-1]: length_list.append(word) print(length_list[-1]) # 2. (8pts) Write code which finds the total word count AND average word length # in "AliceInWonderLand.txt" file = open('../Searching/AliceInWonderLand.txt') list_of_words = [] word_len = 0 for line in file: line = line.strip().upper() words = split_line(line) for word in words: list_of_words.append(word) print("There are", len(list_of_words), " words in Alice In Wonderland.") for word in list_of_words: word_len += len(word) word_len = word_len/len(list_of_words) print("The average word length in Alice In Wonderland is", word_len) # 3. (3pts) How many times does the name Alice appear in Alice in Wonderland? alice_count = [] for word in list_of_words: if word == "ALICE": alice_count.append(word) print("The name Alice appears", len(alice_count), "times.") # 4. (6pts) Find the most frequently occurring seven letter word in "AliceInWonderLand.txt" seven_letter_words = [] repeated_words = [] other_list = [] for word in list_of_words: if len(word) == 7: seven_letter_words.append(word) for word in seven_letter_words: frequency = seven_letter_words.count(word) repeated_words.append(frequency) repeated_words.sort() if frequency == repeated_words[-1]: other_list.append(word) print("The seven letter word that occurs the most frequently is", other_list[-1]) # 5. (2pts, small points challenge problem) # How many times does "Cheshire" occur in"AliceInWonderLand.txt"? # How many times does "Cat" occur? # How many times does "Cheshire" immediately followed by "Cat" occur? cheshire_count = [] for word in list_of_words: if word == "CHESHIRE": cheshire_count.append(word) print("The word Cheshire appears", len(cheshire_count), "times.") cat_count = [] for word in list_of_words: if word == "CAT": cat_count.append(word) print("The word cat appears", len(cat_count), "times.") cheshire_cat_count = 0 for num in range(len(list_of_words)): current_word = list_of_words[num] if current_word == "CHESHIRE" and list_of_words[num + 1] == "CAT": cheshire_cat_count += 1 print("The word 'Cheshire' immediately followed by the word 'Cat' (Cheshire Cat) occurs", cheshire_cat_count, "times.")
import numpy as np from board import Board import random class State(): # Initializing state (0 wins and games by default) def __init__(self, board, parent, children, play): self.set(board, parent, children, play, 0, 0) # board - game board # parent - parent State object # children - array of children State objects # play - integer representing the play to get to this node from parent # wins - no. of simulated wins # games - no. of simulated games (if 0, node hasn't been expanded yet) def set(self, board, parent, children, play, wins, games): self.board = board self.parent = parent self.children = children self.play = play self.wins = wins self.games = games # Generates children for current state def generate_children(self): plays = self.board.legal_plays() children = [State(self.board.next_state(play), self, [], play) for play in plays] self.children = children class MCTS(): # Initializes AI with their dedicated player number (1 or 2) def __init__(self, player): self.player = player self.root = None # Causes AI to calculate the best move from the current game state and returns it. def get_play(self, board, iterations): # Root node self.root = State(board, None, [], None) self.root.generate_children() # Running MCTS for _ in range(iterations): self.select(self.root) # Choosing the best play based on denominator (games played) bestChild = max(self.root.children, key=lambda c: c.games) # Returning the best play winrate = 100 * bestChild.wins / bestChild.games if bestChild.board.current_player() == self.player else 100 * (1 - (bestChild.wins/bestChild.games)) print("AI: {0:d}, perceived winrate: {1:.2f}%".format( bestChild.play, winrate)) return bestChild.play def select(self, state): # If any children are unexpanded, expand child childrenExpanded = True children = state.children for s in children: if s.games <= 0: self.expand(s) childrenExpanded = False break # If all children were already expanded, move on to UCB if childrenExpanded: maxVal = -50000 for s in children: uc = self.ucb1(s, state) if uc > maxVal: maxVal = uc maxState = s if len(children) != 0: self.select(maxState) else: self.expand(state) def ucb1(self, child, parent): # If the child node belongs to same as parent, return the standard ucb value if child.board.player == parent.board.player: return child.wins/child.games + np.sqrt(2*np.log(parent.games)/child.games) # If the child and parent are different, inverse the utility (winrate) else: return (1 - child.wins/child.games) + np.sqrt(2*np.log(parent.games)/child.games) def expand(self, state): # Expands a child node after selection (generate children and then run a simulation) state.generate_children() winner = self.run_simulation(state.board) self.update(state, winner) def run_simulation(self, board): # Plays out a random game from the current position, returns the winning player sim = Board(board.aSide.copy(), board.bSide.copy(), board.player) while sim.winner() == 0: plays = sim.legal_plays() selected_play = random.choice(plays) sim = sim.next_state(selected_play) return sim.winner() def update(self, state, winner): # Update all nodes in path until root is reached while state.parent != None: state.games += 1 # Draw if winner == -1: state.wins += 0.5 # Opponent wins elif winner != self.player and state.board.current_player() != self.player: state.wins += 1 # AI wins elif winner == self.player and state.board.current_player() == self.player: state.wins += 1 state = state.parent # Update root state.games += 1 if winner == self.player: state.wins += 1
class User: # here's what we have so far def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 # adding the deposit method def make_deposit(self, amount): # takes an argument that is the amount of the deposit self.account_balance += amount # the specific user's account increases by the amount of the value received def make_withdrawal(self, amount): self.account_balance -= amount def display_user_balance(self): print(self.account_balance) def transfer_money(self, other_user, amount): self.account_balance -= amount other_user.make_deposit(amount) user1 = User("Joe", "[email protected]") user2 = User("James", "[email protected]") user3 = User("Jane", "[email protected]") user1.make_deposit(21) user1.make_deposit(76) user1.make_deposit(6000) user1.display_user_balance() user2.make_deposit(86) user2.make_deposit(2084) user2.make_withdrawal(73) user2.make_withdrawal(88) user2.display_user_balance() user3.make_deposit(408) user3.make_withdrawal(488) user3.make_withdrawal(274) user3.display_user_balance() user1.transfer_money(user3, 200) user1.display_user_balance() user3.display_user_balance()
pomo = 25 rest = 5 mult_pomo = [25,50,75,100,125,150,175] ideal = int(input("how many minutes do you want to work for?")) total = (ideal/pomo*rest)+ideal goal = ideal/pomo+rest #clock = x/pomo+rest mult_goal = [4,8,12,16,20] #intro print("goal:", ideal, "minutes and", ideal/60, "hours") print( "total required time:", total, "minutes and", total/60, "hours.", goal, "is the minumum amount of rounds required.") #conditionals(x == counter) for x in total: if x == mult_pomo: print("time for a 5 minute break") #if clock == mult_goal: print("your breaks are now 30 minutes starting now")
#!/usr/bin/python3 nums = { 21, 11, 42, 29, 22, 71, 18 } print(nums) print("Number of elements: {0}".format(len(nums))) print("Minimum: {0}".format(min(nums))) print("Maximum: {0}".format(max(nums))) print("Sum: {0}".format(sum(nums))) print("Sorted elements:") print(sorted(nums))
# Difficult challenge no. 2 import time def main(): pass def timer(): print('Timer will start when you press enter.') input('Press enter to continue: ') t0 = time.time() print('Timer has started.') print('Timer will stop when you press enter.') input('Press enter to continue: ') print('Timer has stopped.') t1 = time.time() print(t1 - t0) if __name__ == '__main__': main()
# Challenge 29 Easy # https://www.reddit.com/r/dailyprogrammer/comments/r8a70/3222012_challenge_29_easy/ def pal(test): f = list(str(test)) b = f[::-1] if f == b: print('{} is a palindrome!'.format(test)) else: print('{} is not a palindrome.'.format(test))
# Challenge 26 Intermediate # Harder than expected. Sorta works import csv # Entry must be a list format # Sheet is CSV you want to add to # Entry is data you want to add to the CSV def writedata(sheet, entry): sheetdata = [] # reading the CSV and storing the info with open(sheet, 'r') as csvfile: csvreader = csv.reader(csvfile) for row in csvreader: sheetdata.append(row) # adding entry to the info sheetdata.append(entry) # writing everything to the CSV with open(sheet, 'w') as csvfile: csvwriter = csv.writer(csvfile,delimiter = ',') for row in sheetdata: csvwriter.writerow(row) # somehow there are extra lines added to the CSV (could be due to LibreOffice)
import random, string def main(): pass def create_pw(): qty = int(input('How many passwords would you like to generate? ')) print('Algorithm will generate {} passwords.'.format(qty)) length = int(input('How long should the passwords be? ')) print('The passwords will be {} letters long.'.format(length)) pw_list = [] chars = string.ascii_letters + string.digits + string.punctuation for _ in range(qty): pw_list.append(''.join(random.sample(chars, length))) print(pw_list) if __name__ == '__main__': main()
# DailyProgrammer Challenge 8 Easy # write a program that will print the song "99 bottles of beer on the wall." def ninetynine(): for n in range(99,2,-1): print('{} bottles of beer on the wall, {} bottles of beer. Take one down, pass it around, {} bottles of beer on the wall.'.format(n, n, n-1)) print('2 bottles of beer on the wall, 2 bottles of beer. Take one down, pass it around, 1 bottle of beer on the wall.') print('1 bottle of beer on the wall, 1 bottle of beer. Take one down, pass it around, no more bottles of beer on the wall.')
# 1. дефиниция на класа class Point: # Конструктор на класа def __init__(self): print('object constructor') # Данни на класа self.x = 10 self.y = 20 # Методи на класа def draw(self): print(f'draw point at:({self.x}, {self.y})') if __name__ == '__main__': # 2. декларация на променлива от типа # p1 - обект, Point - клас p1 = Point() print(f'p1:({p1.x}, {p1.y})') p1.x = 15 p1.draw()
# 1. дефиниция на класа class Point: # данни на класа (статична променлива) label = 'A' # Конструктор на класа def __init__(self, x = 0, y = 0, *args, **kwargs): print('object constructor') # Данни на обекта self._x = x self._y = y Point.label = 'M' # Методи на класа def draw(self): print(f'draw point at:({self._x}, {self._y})') def move_to(self,dx,dy): self._x += dx self._y += dy if __name__ == '__main__': # 2. декларация на променлива от типа # p1 - обект, Point - клас p1 = Point(0, 45) p2 = Point(5,8) p1.z = 100 # динамичен атрибут Point.label = 'P' # p1.label = 'XX' маскира label на ниво клас!!! print(f'label:{p1.label} p1({p1._x}, {p1._y}, {p1.z})') #AttributeError # print(f'label:{p2.label} p2:({p2._x}, {p2._y}, {p2.z})') print(f'label:{p2.label} p2:({p2._x}, {p2._y})')
# глобална променлива # def first_element(el): # return el[1] if __name__ == '__main__': sq = lambda a: a ** 2 pw = lambda a: a ** 2 if a % 2 else a ** 3 # 1. # print(f'4 ^ 2 = {sq(4)}') # print(f'pw(3) = {pw(3)}') # print(f'pw(4) = {pw(4)}') items = [('A', 5, 7), ('D', 2, 6), ('B', 4, 8), ('D', 2, 5)] # 2. # items.sort() # print(f'in-place,default sorted:{items}') # 3. # items.sort(key = first_element ) # items.sort(key = lambda el: el[1] ) # 4. items.sort(key = lambda el: (el[1],el[0],el[2]) ) print(f'sorted:{items}') values = [2,5,7,9,4] for v in map( lambda e: e ** 2, values): print(v)
from datetime import datetime import pandas as pd def getdatenow(): return datetime.today() def stringtodatetime(str="20210101"): # from datetime import datetime # datetime_str = '09/19/18 13:55:26' datetime_object = datetime.strptime(str, '%Y%m%d') # print(type(datetime_object)) return datetime_object # printed in default format def objtodatetime(objs=None): # from datetime import datetime # datetime_str = '09/19/18 13:55:26' for obj in range(0, len(objs) - 1): objs[obj] = datetime.strptime(objs[obj], '%Y%m%d') # print(type(datetime_object)) return objs # printed in default format def inttodatetime(pdint=None): pdint = pd.DataFrame([20211203.0]) # for item in range(0,len(pdint)): # pdint.values[item]. if __name__ == '__main__': print(stringtodatetime()) # print(Gettimenow()) # print(Getdatenow())
mylist = ["a","b","c","d","a","a"] mylist = list(dict.fromkeys(mylist)) print(mylist) #copy list thislist = ["Gayu","Digu","divya","Yash"] copylist = thislist.copy() print(copylist)
from array import * array_num = array('i',[7,8,5,4,8,6,2,8,9]) print('Original Array :' +str(array_num)) print('Remove the first occurance: ') array_num.remove(8) print('New Array :' +str(array_num))
#def small_num(items): # smallest_number = 0 #print("smallest number is :", min([5,3,2])) def smallest_num(items): multi_numbers = items[0] for x in items: if x < multi_numbers: multi_numbers = x return multi_numbers print(smallest_num([5,5,2,-9]))
from logics.classes.propositional import Formula class PredicateFormula(Formula): """Class for representing predicate formulae. Extends the propositional class ``Formula``, but has some differences: * Atomics are now of the form ``['R', 'a', 'x']`` * When the terms are applied function symbols, they must come as tuples, where the first element of the tuple is the function symbol, and the following are its arguments, e.g. ``['R', ('f', ('f', 'x')), 'a']`` represents the formula ``R(f(f(x)), a)`` * Now we have quantified formulae of the form ``['∀', 'x', PredicateFormula]`` * Will also accept bounded quantified formulae of the form ``['∀', 'x', '∈', term, PredicateFormula]`` As in ``Formula``, the ``__init__`` method will turn inner lists into ``PredicateFormula``, so you can write ``PredicateFormula(['~', ['P', 'x']])`` instead of ``PredicateFormula(['~', PredicateFormula(['P', 'x'])])`` Examples -------- >>> from logics.classes.predicate import PredicateFormula The following are examples of predicate formulae (and are well-formed for `logics.instances.predicate.languages.classical_function_language`): >>> PredicateFormula(['P', 'x']) >>> PredicateFormula(['∧', ['~', ['P', 'a']],['X', 'a']]) >>> PredicateFormula(['R', 'a', 'b']) >>> PredicateFormula(['P', ('f', ('g', 'a', 'x'))]) >>> PredicateFormula(['∀', 'x', ['P', 'x']]) >>> PredicateFormula(['∃', 'x', ['∀', 'X', ['X', 'x']]]) >>> PredicateFormula(['∀', 'x', '∈', ('f', 'a'), ['P', 'x']]) Some properties and methods are available because we are extending ``Formula`` >>> from logics.instances.predicate.languages import classical_function_language >>> PredicateFormula(['P', 'x']).is_schematic(classical_function_language) False >>> PredicateFormula(['∧', ['P', 'x'], ['A']]).is_schematic(classical_function_language) True >>> PredicateFormula(['∧', ['P', 'x'], ['A']]).main_symbol '∧' >>> PredicateFormula(['∃', 'x', ['∀', 'X', ['X', 'x']]]).depth 2 >>> PredicateFormula(['∃', 'x', ['∀', 'X', ['X', 'x']]]).subformulae [['X', 'x'], ['∀', 'X', ['X', 'x']], ['∃', 'x', ['∀', 'X', ['X', 'x']]]] >>> f = PredicateFormula(['∧', ['P', 'x'], ['A']]) >>> f.substitute(PredicateFormula(['P', 'x']), PredicateFormula(['Q', 'x'])) ['∧', ['Q', 'x'], ['A']] >>> f ['∧', ['P', 'x'], ['A']] >>> f.instantiate(classical_function_language, {'A': PredicateFormula(['P', 'a'])}) ['∧', ['P', 'x'], ['P', 'a']] >>> f2 = PredicateFormula(['∧', ['P', 'x'], ['Q', 'x']]) >>> f2.schematic_substitute(classical_function_language, ... PredicateFormula(['∧', ['A'], ['B']]), ... PredicateFormula(['∧', ['B'], ['A']])) ['∧', ['Q', 'x'], ['P', 'x']] """ @property def is_atomic(self): """Same as in propositional ``Formula``. Overriden to work with this class. Examples -------- >>> from logics.classes.predicate import PredicateFormula >>> PredicateFormula(['P', 'x']).is_atomic True >>> PredicateFormula(['∧', ['~', ['P', 'a']],['X', 'a']]).is_atomic False """ #Predicate language atomics are those that have no members of the same class inside for subelement in self: if isinstance(subelement, self.__class__): return False return True def arguments(self, quantifiers=('∀', '∃')): """Same as in propositional ``Formula``. Overriden in order to accomodate quantified formulae. Examples -------- >>> from logics.classes.predicate import PredicateFormula >>> PredicateFormula(['∧', ['P', 'x'], ['A']]).arguments() [['P', 'x'], ['A']] >>> PredicateFormula(['∃', 'x', ['∀', 'X', ['X', 'x']]]).arguments() [['∀', 'X', ['X', 'x']]] >>> PredicateFormula(['∃', 'x', '∈', 'y', ['∀', 'X', ['X', 'x']]]).arguments() [['∀', 'X', ['X', 'x']]] Notes ----- If your language uses different quantifiers, pass them as a list of strings to the `quantifiers` parameter. """ # Return only the immediate subformulae. Overriden so that ∀x Px returns only [Px], and not [x, Px]. # By default assumes that the quantifiers are the standard ones, if you need different ones, pass a different # second parameter. if self[0] in quantifiers: if self[2] == '∈': return self[4:] return self[2:] return super().arguments() def free_variables(self, language, term=None, _bound_variables=None): """Returns the set of free variables inside a predicate formula or term if `term` is ``None`` will evaluate the whole formula. Otherwise, will only evaluate the term given. `_bound_variables` is internal and should not be altered. Examples -------- >>> from logics.classes.predicate import PredicateFormula >>> from logics.instances.predicate.languages import classical_function_language >>> PredicateFormula(['∀', 'X', ['X', 'x']]).free_variables(classical_function_language) {'x'} >>> PredicateFormula(['∀', 'x', ['X', 'x']]).free_variables(classical_function_language) {'X'} >>> PredicateFormula(['∃', 'x', '∈', 'y', ['∀', 'X', ['X', 'x']]]).free_variables(classical_function_language) {'y'} >>> PredicateFormula(['∀', 'x', ['P', ('f', 'x')]]).free_variables(classical_function_language) set() >>> PredicateFormula(['∀', 'x', ['P', ('f', 'x')]]).free_variables(classical_function_language, term=('f', 'x')) {'x'} """ free = set() if _bound_variables is None: _bound_variables = set() # Term if term is not None: # If you are evaluating a particular term (e.g. 'a' or ('f', ('g', 'x')) # Atomic term, e.g. 'a' if type(term) == str: if language._is_valid_variable(term) and term not in _bound_variables: return {term} return set() # Molecular term ('f', ('g', 'x')) for subterm in term: free |= self.free_variables(language, term=subterm, _bound_variables=_bound_variables) return free # Atomic if self.is_atomic: # If you are evaluating the entire atomic formula, evaluate each argument (incl the predicate) for argument in self: free |= self.free_variables(language, term=argument, _bound_variables=_bound_variables) return free # Molecular if self.main_symbol in language.quantifiers: # In case of a bounded quantifier, check for free variables in the bound (before adding to the bounded) if self[2] == '∈': free |= self.free_variables(language, term=self[3], _bound_variables=_bound_variables) # Quantified formula: add the quantified variable to bound_variables _bound_variables |= {self[1]} # Return the varibles in each immediate subformula for subformula in self.arguments(): free |= subformula.free_variables(language, _bound_variables=_bound_variables) return free def is_closed(self, language): """Determines if a formula is closed (i.e has no free variables) Examples -------- >>> from logics.classes.predicate import PredicateFormula >>> from logics.instances.predicate.languages import classical_function_language >>> PredicateFormula(['∀', 'X', ['X', 'x']]).is_closed(classical_function_language) False >>> PredicateFormula(['∀', 'X', ['∀', 'x', ['X', 'x']]]).is_closed(classical_function_language) True """ return self.free_variables(language) == set() def is_open(self, language): """Determines if a formula is open (i.e. has free variables) Examples -------- >>> from logics.classes.predicate import PredicateFormula >>> from logics.instances.predicate.languages import classical_function_language >>> PredicateFormula(['∀', 'X', ['X', 'x']]).is_open(classical_function_language) True >>> PredicateFormula(['∀', 'X', ['∀', 'x', ['X', 'x']]]).is_open(classical_function_language) False """ return not self.is_closed(language) def vsubstitute(self, variable, substitution, quantifiers=('∀', '∃'), term=None, _bound_variables=None): """Variable substitution method. Returns the PredicateFormula that results from substituting the free occurences of `variable` for `substitution`. Parameters ---------- variable: str The variable whose free occurrences you wish to substitute substitution: str or tuple The term you wish to substitute it with quantifiers: tuple of str, optional By default, assumes that the quantifiers are '∀', '∃', so that you do not have to pass a language as argument; If you have different quantifiers, you can call this differently (e.g. ``quantifiers = your_language.quantifiers``) term: str or tuple, optional if you only wish to substitute inside a term, as in the `free_variables` method. _bound_variables Internal, you should not alter its value Examples -------- >>> from logics.classes.predicate import PredicateFormula >>> PredicateFormula(['P', 'x']).vsubstitute('x', 'a') ['P', 'a'] >>> PredicateFormula(['∀', 'x', ['P', 'x']]).vsubstitute('x', 'a') ['∀', 'x', ['P', 'x']] >>> PredicateFormula(['∧', ['P', 'x'], ['∀', 'x', ['P', 'x']]]).vsubstitute('x', 'a') ['∧', ['P', 'a'], ['∀', 'x', ['P', 'x']]] >>> PredicateFormula(['∀', 'x', ['X', 'x']]).vsubstitute('X', 'P') ['∀', 'x', ['P', 'x']] >>> PredicateFormula(['∀', 'X', ['X', 'a']]).vsubstitute('X', 'P') ['∀', 'X', ['X', 'a']] >>> # The bound is not under the scope of the quantifier: >>> PredicateFormula(['∀', 'x', '∈', ('f', 'x'), ['P', 'x']]).vsubstitute('x', 'b') ['∀', 'x', '∈', ('f', 'b'), ['P', 'x']] """ if _bound_variables is None: _bound_variables = set() # Term if term is not None: # If you are substituting a particular term (e.g. 'a' or ('f', ('g', 'x')) # Atomic term, e.g. 'a' if type(term) == str: if term == variable and term not in _bound_variables: return substitution return term # Molecular term ('f', ('g', 'x')) newterm = list() for subterm in term: newterm.append(self.vsubstitute(variable, substitution, quantifiers=quantifiers, term=subterm, _bound_variables=_bound_variables)) return tuple(newterm) if self.is_atomic: # If you are evaluating the entire atomic formula, evaluate each argument (incl the predicate) new_formula = self.__class__() for argument in self: new_formula.append(self.vsubstitute(variable, substitution, quantifiers=quantifiers, term=argument, _bound_variables=_bound_variables)) return new_formula # Molecular # First, copy everything that is not a subformula (connective, quantifier, variable, '∈', bound) new_formula = self.__class__([x for x in self if type(x) != self.__class__]) if self.main_symbol in quantifiers: # In case of a bounded quantifier, substitute variables in the bound (before adding to the bounded) if self[2] == '∈': new_formula[3] = self.vsubstitute(variable, substitution, quantifiers=quantifiers, term=self[3], _bound_variables=_bound_variables) # Quantified formula: add the quantified variable to bound_variables _bound_variables |= {self[1]} # Substitute each immediate subformula for subformula in self.arguments(): new_formula.append(subformula.vsubstitute(variable, substitution, quantifiers=quantifiers, _bound_variables=_bound_variables)) return new_formula def _is_molecular_instance_of(self, formula, language, subst_dict, return_subst_dict): # We only need the quantifier case here, for the rest call the super method if self.main_symbol == formula.main_symbol and self.main_symbol in language.quantifiers: # Check that the variable is the same if self[1] != formula[1]: if not return_subst_dict: return False return False, subst_dict # Bounded quantifier case if formula[2] == '∈': # The bounds must be equal (we do not presently have metavariables for terms) if self[2] != '∈' or self[3] != formula[3]: if not return_subst_dict: return False return False, subst_dict # If the above is satisfied, the quantified subformula must be an instance result = self[4].is_instance_of(formula[4], language, subst_dict, return_subst_dict=True) if not return_subst_dict: return result[0] return result # Non-bounded quantifier, check the quantified subformula directly after the variable else: result = self[2].is_instance_of(formula[2], language, subst_dict, return_subst_dict=True) if not return_subst_dict: return result[0] return result return super()._is_molecular_instance_of(formula, language, subst_dict, return_subst_dict)
import numpy as np class Vector: """Vector represents translation and stores 3 values Attributes ---------- x The x value y The y value z The z value """ def __init__(self, x, y, z): """ Parameters ---------- x The x value y The y value z The z value """ super(Vector, self).__init__() self.x = x self.y = y self.z = z @staticmethod def zero(): """Creates vector with zero x, y and z""" return Vector(0, 0, 0) @staticmethod def lerp(start, end, t): """Calculates linear interpolation between start and end for given t""" return start + t * (end + -1 * start) def normalized(self): """Calculates colinear vector with length 1""" return 1 / self.magnitude() * self def magnitude(self): """Calculates Euclidean length of vector""" return (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5 def times(self, other): """Multiplies vector by scalar value Parameters ---------- other The scalar value to multiply on """ return Vector( other * self.x, other * self.y, other * self.z ) def cross(self, other): return Vector( self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x, ) def dot(self, other): return self.x * other.x + self.y * other.y + self.z * other.z def angle_to(self, other, axis): crossed = self.cross(other) collinearity = crossed.dot(axis) return np.arctan2( crossed.magnitude(), self.dot(other) ) * (1 if collinearity > 0.0 else -1) def __str__(self): return "[{}, {}, {}]".format(self.x, self.y, self.z) def __repr__(self): return "Vector[{}, {}, {}]".format(self.x, self.y, self.z) def __add__(self, other): if isinstance(other, Vector): return Vector( self.x + other.x, self.y + other.y, self.z + other.z ) def __mul__(self, other): return self.times(other) def __rmul__(self, other): return self.times(other) class Quaternion: """Quaternion represents rotation and stores 4 values Attributes ---------- w The w value x The x value y The y value z The z value """ def __init__(self, w, x, y, z): """ Parameters ---------- w The w value x The x value y The y value z The z value """ super(Quaternion, self).__init__() self.w = w self.x = x self.y = y self.z = z @staticmethod def identity(): """Creates quaternion representing no rotation""" return Quaternion(1, 0, 0, 0) def rotate(self, vector): """Rotates given vector Parameters ---------- vector Vector to be rotated """ pure = Quaternion(0, vector.x, vector.y, vector.z) rotated = self * pure * self.conjugate() return Vector(rotated.x, rotated.y, rotated.z) def magnitude(self): return (self.w ** 2 + self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5 def normalized(self): return 1 / self.magnitude() * self def dot(self, other): return self.w * other.w + self.x * other.x + self.y * other.y + self.z * other.z @staticmethod def slerp(start, end, t): dot = start.dot(end) if dot < 0.0: start = -1 * start dot = -dot if dot >= 1.0: return start theta = np.arccos(dot) * t q = (end + -dot * start).normalized() return np.cos(theta) * start + np.sin(theta) * q def conjugate(self): """Calculates quaternion representing reverse rotation""" return Quaternion(self.w, -self.x, -self.y, -self.z) def multiply(self, other): """Multiplies quaternion on other quaternion Parameters ---------- other The other quaternion to multiply on """ return Quaternion( self.w * other.w - self.x * other.x - self.y * other.y - self.z * other.z, self.w * other.x + self.x * other.w + self.y * other.z - self.z * other.y, self.w * other.y - self.x * other.z + self.y * other.w + self.z * other.x, self.w * other.z + self.x * other.y - self.y * other.x + self.z * other.w ) def plus(self, other): return Quaternion( self.w + other.w, self.x + other.x, self.y + other.y, self.z + other.z ) def times(self, other): """Multiplies quaternion on scalar Parameters ---------- other The scalar value to multiply on """ return Quaternion( other * self.w, other * self.x, other * self.y, other * self.z ) @staticmethod def from_angle_axis(angle, axis, math_source=np, unit=True): """Calculates quaternion representing rotation around given axis on given angle Parameters ---------- angle The rotation angle in radians axis The rotation axis math_source The source of sin and cos operations, default is numpy unit Marks if axis is considered unit, default is True """ if not unit: axis = axis.normalized() c = math_source.cos(angle / 2) s = math_source.sin(angle / 2) return Quaternion( c, s * axis.x, s * axis.y, s * axis.z ) def __str__(self): return "[{}, {}, {}, {}]".format(self.w, self.x, self.y, self.z) def __repr__(self): return "Quaternion[{}, {}, {}, {}]".format(self.w, self.x, self.y, self.z) def __mul__(self, other): if isinstance(other, Vector): return self.rotate(other) if isinstance(other, Quaternion): return self.multiply(other) return self.times(other) def __add__(self, other): return self.plus(other) def __rmul__(self, other): return self.times(other) class Transform: """Transform represents translation and rotation Attributes ---------- translation The translation vector rotation The rotation quaternion """ def __init__(self, translation: Vector, rotation: Quaternion): """ Parameters ---------- translation The translation vector rotation The rotation quaternion """ super(Transform, self).__init__() self.translation = translation self.rotation = rotation @staticmethod def identity(): """Creates Transform representing no translation and no rotation""" return Transform( Vector.zero(), Quaternion.identity() ) def inverse(self): conj = self.rotation.conjugate() return Transform( conj * (-1 * self.translation), conj ) @staticmethod def lerp(start, end, t): return Transform( Vector.lerp(start.translation, end.translation, t), Quaternion.slerp(start.rotation, end.rotation, t) ) def __str__(self): return "[\n\t{}\n\t{}\n]".format(str(self.translation), str(self.rotation)) def __repr__(self): return "Transform[\n\t{}\n\t{}\n]".format(str(self.translation), str(self.rotation)) def __add__(self, other): if isinstance(other, Transform): return Transform( self.translation + self.rotation * other.translation, self.rotation * other.rotation ) if isinstance(other, Vector): return self.translation + self.rotation * other
import sys, getopt, io def my_argument_function(argv): """Get the CLI argument into a python dictionary The dictionary that is used in My_Logger_Class is called argu and commes with already predefined arguments such as freq=5. The Try usese the getopt to get the opt/arguments from the user imput. In the For Loop, the apropriate user imput argument is placed in the right slot in the dictionary called argu. """ argu = { 'freq' : 5, 'url' : 'http://api.openweathermap.org/data/2.5/weather?q=Zurich,CHZH&appid=3836093dde650898eb014e6f27304646', 'xpath' : '', 'key' : 'name', 'change' : 'no', } try: opts, args = getopt.getopt(argv,"hf:u:x:k:c:",["freq=","url=","xpath=","key=","change="]) except getopt.GetoptError: print('-f <freq> -u <url> -x <xpath> -k <key> -c <y/n>') sys.exit() for opt, arg in opts: if opt == '-h': print('restlogger -f <freq> -u <url> -x <xpath> -k <key> -c <y/n>') sys.exit() elif opt in ("-f", "--freq"): argu['freq'] = int(arg) elif opt in ("-u", "--url"): argu['url'] = arg elif opt in ("-x", "--xpath"): argu['xpath'] = arg elif opt in ("-k", "--key"): argu['key'] = arg elif opt in ("-c", "--change"): argu['change'] = arg return argu
class Person: def __init__(self,name,age,enrollno,branch): self.name=name self.age=age self.enrollno=enrollno self.branch=branch p1 = Person("Riddham" , "21" , "0832cs15128","cse") print("Name is "+p1.name) print("Age is "+p1.age) print("Enrollno is "+p1.enrollno) print("Branch is "+p1.branch)
""" Linear Regression """ import random import numpy as np import matplotlib.pyplot as plt # this function generates random data #sigma -> varience #n -> total number of instances #m -> number of columns def genrate_data(sigma, n, m): # e is unexplained error, it is normally distributed with mean = 0 and varience = 1 e = random.gauss(0, sigma) x = np.random.rand(n , m+1) #randomly generates x for i in range(0, len(x)): #makes the first column of x as 1 x[i][0] = 1 beta = np.random.rand(m+1) #randomly generates beta x_beta = x @ beta #matrix product of x with beta y = x_beta + e #adding the matrix product and e we get are original y, which can be comapared with the predicted y to calculate accuracy return(x, y, beta) def Linear_Regression(X, Y, k, tou, alpha): m = len(X[0]) # Step 1 -> Initialisation beta = np.random.rand(m) # randomly selected beta value E = Y - X @ beta #error between the original y and predicted y curr_cost = np.dot(E, E) #the initial cost differentiation_of_cost = - (2 * E @ X) # Step 2 -> iterate until the desired epochs has been reached or until the threshold. Upgrade the betas and minimise the cost for i in range (0, k): E = Y - X @ beta cost = np.dot(E,E) differentiation_of_cost = - (2 * E @ X) if abs(curr_cost- cost) < tou: #tou is the threshold on change in cost function from previous to current iteration # print(1) break else: beta = beta - alpha * differentiation_of_cost #update the beta value curr_cost = cost #updating the current cost return ( beta, curr_cost) X, Y, beta = genrate_data(10, 300, 2) x = np.array(X) #print(x.shape) y = np.array([Y]) x = np.transpose(x) #print(x.shape) #y = Y.reshape(-1,1) # scatter plot of X and Y for i in range(0, len(x)): plt.scatter(x[i], y) predicted_beta, cost = Linear_Regression(X, Y, 500, 0.0001, 0.001) #print("original beta ",beta) #print("predicted beta",predicted_beta) #print("cost",cost) Y_predicted = X @ predicted_beta y_predicted = np.array([Y_predicted]) # scatter plot for X and predicted Y #for i in range(0, len(x)): # plt.scatter(x[i], y_predicted) plt.show() #print(Y) print(Y[12], Y_predicted[12]) #print(Y[220], Y_predicted[220]) print(Y[37], Y_predicted[37]) print(Y[112], Y_predicted[112])
#tuples tuple1 = ("disk", 10, 1.5) print(tuple1) #tuple index print(tuple1[0]) print(tuple1[1]) print(tuple1[2]) #tuple negative index print(tuple1[-3]) print(tuple1[-2]) print(tuple1[-1]) #tuple line print(tuple1[1:3]) #tuple sixe print(len(tuple1)) #tuple sort tuple2 = (1, 3, 5, 8, 2) print(sorted(tuple2)) # LIST l = ["Michael Jackson", 10.1, 1982, "MJ", 1] print(l) # List contatenate l.extend(["pop", 10]) print(l) # modify element from index l[1] = 10 print(l) # Delete element del(l[1]) print(l) # Separete string to a list text = "Hello World".split print(text)
""" Ejercicio 1. Programa que Evalua la Función: y(x) = Σ [mi * e^(γ(x - xi)^2)] de i = 1 -> k Donde: x, xi ∈ a los ℝ^n mi ∈ ℝ r ∈ ℝ > 0 Creado por: José Fragoso, 22/03/2019. TODO: - Revisar el cambio que se hizo en la creación de arreglos. - Generar una mejor impresión en la terminal. """ import numpy as np import math # 1. Creamos los Datos. def get_params(): """ Genera matrices y vectores para ser utilizados en la evaluación del kernel RBF """ K = np.random.randint(5, 40) N = np.random.randint(2, 20) xi = np.random.normal( 0,1,(K,N) ) x = np.random.normal( 0,1, N ) mi = np.random.normal( 0,1, K ) gamma = np.random.normal( 0,1,1 ) return x,xi,mi,gamma def main(): x,xi,mi,gamma = get_params() if __name__ == "__main__": main() x,xi,mi,gamma = get_params() # 3. Declaramos variables, len() nos da el tamaño del arreglo. n = len(x) k = len(xi) elevado = 0 y = 0 # 4. Hacemos Operaciones. for i in range(k): elevado = np.dot(x, xi[i]) * gamma multiplicacion = np.exp(elevado) * mi[i] y = y + multiplicacion # 5. Terminamos Imprimiendo el Resultado print("El Resultado de la Función Evaluada es: %f" % (y))
#Let’s say I give you a list saved in a variable: #a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. #Write one line of Python that takes this list a and makes a new list that has only the even #elements of this list in it. a = [1,4,9,16,25,36,49,64,81,100] # example list a = [a for a in a if a % 2 == 0] # list comprehension to use one line of code print (a) # prints to console
class Employee(): def __init__(self, first, last, pay, car, shirt): self.first = first self.last = last self.pay = pay self.car = car self.shirt = shirt self.email = f"{first}.{last}@yahoooooo.com" def description(self): print (f"{self.first} {self.last} makes ${self.pay} dollars a year and drive a {self.car}") def give_pay_raise(self): self.pay = self.pay * 1.23 def get_email(self): print (f"You can contact {self.first} {self.last} at {self.email}") emp_1 = Employee("Robert", "Neuzil", 94000, "Ford", "Brown") emp_2 = Employee("Jessica", "Jones", 80000, "Nissan", "Blue") emp_3 = Employee("Jacob", "Cross", 5000000000000, "Honda", "Brown") emp_4 = Employee("Tony", "Soprano", 50000, "GM", "Red") emp_5 = Employee("Angela", "Mason", 2099999, "Toyota", "Yellow") emp_6 = Employee("James", "Smith", 444444, "Ford", "Blue") emp_7 = Employee("Jessica", "Long", 833849384, "Ford", "Grey") emp_8 = Employee("Robert", "Neuman", 58993849, "Ford", "Purple") all_employees = [emp_1, emp_2, emp_3, emp_4, emp_5, emp_6, emp_7, emp_8] for x in all_employees: x.description() for y in all_employees: y.give_pay_raise() y.description() emp_3.get_email() """ PRINTED TO THE CONSOLE: Robert Neuzil makes $94000 dollars a year and drive a Ford Jessica Jones makes $80000 dollars a year and drive a Nissan Jacob Cross makes $5000000000000 dollars a year and drive a Honda Tony Soprano makes $50000 dollars a year and drive a GM Angela Mason makes $2099999 dollars a year and drive a Toyota James Smith makes $444444 dollars a year and drive a Ford Jessica Long makes $833849384 dollars a year and drive a Ford Robert Neuman makes $58993849 dollars a year and drive a Ford -------------------------------AFTER PAY RAISE METHOD ----------------------- Robert Neuzil makes $115620.0 dollars a year and drive a Ford Jessica Jones makes $98400.0 dollars a year and drive a Nissan Jacob Cross makes $6150000000000.0 dollars a year and drive a Honda Tony Soprano makes $61500.0 dollars a year and drive a GM Angela Mason makes $2582998.77 dollars a year and drive a Toyota James Smith makes $546666.12 dollars a year and drive a Ford Jessica Long makes $1025634742.3199999 dollars a year and drive a Ford Robert Neuman makes $72562434.27 dollars a year and drive a Ford You can contact Jacob Cross at [email protected] """
""" Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? """ num = int(input("Please enter a number:")) if num % 2 == 0: #modulus op will see if there are any dividedends to this number print ("Your number is even") else: print ("Your number is odd")
# 给定两个数组,编写一个函数来计算它们的交集。 # 示例 # 1: # 输入:nums1 = [1, 2, 2, 1], nums2 = [2, 2] # 输出:[2] # 示例 # 2: # 输入:nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4] # 输出:[9, 4] # 说明: # # 输出结果中的每个元素一定是唯一的。 # 我们可以不考虑输出结果的顺序。 # class Solution(object): # def intersection(self, nums1, nums2): # """ # :type nums1: List[int] # :type nums2: List[int] # :rtype: List[int] # """ # ans = [] # len1 = len(nums1) # len2 = len(nums2) # if len1 <= len2: # for i in nums1: # if i in nums2: # if i not in ans: # ans.append(i) # else: # for i in nums2: # if i in nums1: # if i not in ans: # ans.append(i) # return ans class Solution: def intersection(self, nums1, nums2): set1 = set(nums1) print(type(set1)) set2 = set(nums2) return self.set_intersection(set1, set2) def set_intersection(self, set1, set2): if len(set1) > len(set2): return self.set_intersection(set2, set1) return [x for x in set1 if x in set2] if __name__ == '__main__': s = Solution() n1 = [1, 7, 2, 3, 4, 4, 5] n2 = [4, 5] # print(list(set(n1).intersection(set(n2)))) print(s.intersection(n1, n2))
# 206. 反转链表 # 反转一个单链表 # # 示例: # # 输入: 1->2->3->4->5->NULL # 输出: 5->4->3->2->1->NULL # 进阶: # 你可以迭代或递归地反转链表。你能否用两种方法解决这道题? # Definition for singly-linked list. # 没懂啊啊哈哈哈 class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ p, rev = head, None while p: rev, rev.next, p = p, rev, p.next return rev def reverseList2(self, head): # 递归终止条件是当前为空,或者下一个节点为空 if (head.next == None): return head # 这里的cur就是最后一个节点 cur = self.reverseList2(head.next) # print(cur, type(cur)) # 这里请配合动画演示理解 # 如果链表是 1->2->3->4->5,那么此时的cur就是5 # 而head是4,head的下一个是5,下下一个是空 # 所以head.next.next 就是5->4 head.next.next = head # 防止链表循环,需要将head.next设置为空 head.next = None # 每层递归函数都返回cur,也就是最后一个节点 return cur if __name__ == '__main__': n1 = ListNode(1) head = ListNode(0) n2 = ListNode(2) n3 = ListNode(3) n1.next = n2 n2.next = n3 n3.next = None head.next = n1 ans = Solution() l = ans.reverseList2(head) print(l.val, l.next.val, l.next.next.val) # class Node(object): # def __init__(self, elem, next_=None): # self.elem = elem # self.next = next_ # # # def reverseList(head): # if head == None or head.next == None: # 若链表为空或者仅一个数就直接返回 # return head # pre = None # next = None # while (head != None): # next = head.next # 1 # head.next = pre # 2 # pre = head # 3 # head = next # 4 # return pre # # if __name__ == '__main__': # l1 = Node(3) # 建立链表3->2->1->9->None # l1.next = Node(2) # l1.next.next = Node(1) # l1.next.next.next = Node(9) # l = reverseList(l1) # print(l.elem, l.next.elem, l.next.next.elem, l.next.next.next.elem)
"""Strategy randomly picks a slot machine to run.""" from random import randint from random import random from bandits import Environment def random_strategy_calculator(number_of_machines: int, number_of_trials: int, means: list, gaussian=False, ): """ Calculate value gained using random strategy. :param gaussian: whether to use gaussian or Bernoulli distribution :param number_of_machines: number of slot machines :param means: list of the means of the machine :param number_of_trials: total number of trials :return: random strategy environment """ if len(means) != number_of_machines: means = [random() for i in range(number_of_machines)] print("error with means in random strategy") # Initialise the environment. random_environment = Environment(number_of_machines, means, gaussian) # Randomly pick a machine for each trial. for i in range(number_of_trials): random_machine_number: int = randint(0, number_of_machines - 1) random_environment.machine_list[random_machine_number].run() random_environment.update() # Return environment return random_environment
import csv def get_questions(): get_questions = [] with open('data/questions.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') skip = False for row in csv_reader: if (skip): get_questions.append(row) else: skip = True return get_questions
def create_question(title, body, body_format, pseudocode, course): with open("seeds.rb", "a") as myfile: question_body = """ question""" + title + """text = %q{""" + remove_new_line(body) + """} """ pseudocode_body = """ question""" + title + """pseudocode = %q{""" + pseudocode + """} """ question_string = """ {0} = MultipleChoiceQuestion.create!( title: '{1}', body: question{2}text, pseudocode: question{3}pseudocode, body_format: 'mathjax', course: {4} ) """.format(str(title), str(title), str(title), str(title), str(course)) myfile.write(question_body) myfile.write(pseudocode_body) myfile.write(question_string) def remove_new_line(body): body = body[1:] body = body[:-1] return body.lstrip(' ')
# -*- coding: utf-8 -*- """ Created on Sat Sep 8 21:15:58 2018 @author: Darshan """ #!/usr/bin/env python2 import sys from datetime import datetime # Count # of pieces in given row def count_on_row(board, row): return sum( board[row] ) # Count # of pieces in given column def count_on_col(board, col): return sum( [ row[col] for row in board ] ) # Count # of pieces on both diagonals def count_on_diag(board, row, col): count = 0 for i in range(1, N): if((row - i) in range(0, N) and (col - i) in range(0, N) and board[row-i][col-i] == 1): count += 1 if((row - i) in range(0, N) and (col + i) in range(0, N) and board[row-i][col+i] == 1): count += 1 return count # Count # of pieces on plausible positions of knight from the input position def count_on_knight_pos(board, row, col): count = 0 if((row + 2) in range(0, N) and (col - 1) in range(0, N) and board[row+2][col-1] == 1): count += 1 if((row + 2) in range(0, N) and (col + 1) in range(0, N) and board[row+2][col+1] == 1): count += 1 if((row + 1) in range(0, N) and (col - 2) in range(0, N) and board[row+1][col-2] == 1): count += 1 if((row + 1) in range(0, N) and (col + 2) in range(0, N) and board[row+1][col+2] == 1): count += 1 return count # Count total # of pieces on board def count_pieces(board): return sum([ sum(row) for row in board ] ) # Return a string with the board rendered in a human-friendly format def printable_board(board): board_string = "" char = "" for r in range(0, N): for c in range(0, N): if (r,c) in blocks: char = "x" elif T == "nqueen" and board[r][c] == 1: char = "Q" elif T == "nrook" and board[r][c] == 1: char = "R" elif T == "nknight" and board[r][c] == 1: char = "K" else: char = "_" board_string = board_string + char + " " board_string = board_string + "\n" return board_string # Add a piece to the board at the given position, and return a new board (doesn't change original) def add_piece(board, row, col): return board[0:row] + [board[row][0:col] + [1,] + board[row][col+1:]] + board[row+1:] # Get list of successors of given board state as requirements mentioned in question 4 def successors(board): successor = [] if(count_pieces(board) < N): count = count_pieces(board) #for r in range(count, count+1): for r in range(0, N): for c in range(0, N): if T == "nrook" and board[r][c] != 1 and count_on_col(board, c) == 0 and count_on_row(board, r) == 0 and (r,c) not in blocks: successor.append(add_piece(board, r, c)) elif T == "nqueen" and board[r][c] != 1 and count_on_col(board, c) == 0 and count_on_diag(board, r, c) == 0 and (r,c) not in blocks: successor.append(add_piece(board, r, c)) elif T == "nknight" and board[r][c] != 1 and count_on_knight_pos(board, r, c) == 0 and (r,c) not in blocks: successor.append(add_piece(board, r, c)) else: continue return successor # check if board is a goal state def is_goal(board): if T == "nknight": return count_pieces(board) == N else: return count_pieces(board) == N and \ all( [ count_on_row(board, r) <= 1 for r in range(0, N) ] ) and \ all( [ count_on_col(board, c) <= 1 for c in range(0, N) ] ) # Solve n-rooks! def solve(initial_board): fringe = [initial_board] while len(fringe) > 0: successor = successors(fringe.pop()) # fringe.pop() means this is implementing DFS #successor = successors(fringe.pop(0)) # fringe.pop(0) means this is implementing BFS if successor != None : for s in successor: if is_goal(s): return(s) fringe.append(s) return False # This are inputs required to execute this program whcih are passed through command line arguments. inputs = sys.argv # N is size of board, T is type of execution, n is number of block positions of board N = inputs[0] T = inputs[1] n = inputs[2] if T not in ["nrook", "nqueen", "nknight"]: sys.exit("Entered type is invalid...") initial_board = [[0]*N]*N blocks = [] for i in range (0,n): x = input("Enter row number of block position " + str(i) + ": ") y = input("Enter column number of block position " + str(i) + ": ") # x = inputs[(2*i) + 3] # y = inputs[(2*i) + 4] if x in range(0, N) and y in range(0, N): blocks.append((x,y)) else: sys.exit("Entered block position is invalid...") # The board is stored as a list-of-lists. Each inner list is a row of the board. # A zero in a given square indicates no piece, and a 1 indicates a piece. print ("Starting from initial board:\n" + printable_board(initial_board) + "\n\nLooking for solution...\n") start = datetime.now() solution = solve(initial_board) time = datetime.now() - start time = time.seconds*1000 + time.microseconds/1000 print (printable_board(solution) if solution else "Sorry, no solution found. :(") print ("Time taken: "+ str(time) + " milliseconds")
import os, pickle, sys, struct # ----- FUNCTIONS ----- # # --- Read File Function --- # def hpwc(filename): """ Reads a binary file and prints the content to the stout in utf-8 coding """ with open(filename, 'rb') as inFile: str_ser = pickle.load(inFile) string = unpack_helper("I", str_ser) return(string[1].decode("utf-8")) def unpack_helper(fmt, data): ''' Helps the hpwc function by calculating the size of the binary to alocate the space needed by each data ''' size = struct.calcsize(fmt) return struct.unpack(fmt, data[:size]), data[size:] # ----- MAIN ----- # if __name__ == "__main__": # Variables are declared in "__main__" file_lst = sys.argv[1:] print(hpwc(file_lst[0]))
import sys import os import time # Python 3 program to find Majority # element in an array # Guardamos los argumentos con los que llamamos al programa en arg arg = sys.argv #Comprobamos si tenemos que mostrar el resultado if "-do" in arg: out=1 else: out=0 # Function to find Majority # element in an array def findMajority(arr, n): maxCount = 0 index = -1 # sentinels for i in range(n): count = 0 for j in range(n): if(arr[i] == arr[j]): count += 1 # update maxCount if count of # current element is greater if(count > maxCount): maxCount = count index = i # if maxCount is greater than n/2 # return the corresponding element if (out==1): if (maxCount > n//2): print(arr[index]) else: print("No Majority Element") def read(filename): if os.path.getsize(filename)>0 : return [int(i) for i in (open(filename).read()).split(",")] return [] def main(): if len(arg)==1 : print("Error, no has introducido parámetros") exit() elif ("-h" in arg): print('''Python MayorityElement help ------------------ Input switches -f filename : input data from file -a length : input initialized with ascending values Display switches -dt : Display time in seconds -di : Display input -do : Display output''') exit() else: global x1 if "-f" in arg: try: x=int(arg.index("-f")) if x+1 >= len(arg): print("Error, ningún fichero después de opción -f") exit() x1=read(arg[x+1]) except FileNotFoundError as ex: print("Fichero",ex.filename,"no encontrado") exit() elif "-a" in arg: x=int(arg.index("-a")) if x+1 >= len(arg): print("Error, ningún número después de opción -w") exit() x1=[i for i in range(0,int(arg[x+1]))] else: print("Error, no se encuentran los paŕametros para inicializar el vector") exit() if "-di" in arg : print("El array de sobre el que se realizará la operación es:",x1) # Driver code if __name__ == "__main__": main() # Function calling t= time.time() findMajority(x1, len(x1)) t= (time.time()-t) if "-dt" in arg: print("Time: \t",round(t,6), " s\n",sep="")
# Q1 a = int(input("Enter first number:")) b = int(input("Enter second number:")) print("Sum of the two given numbers is:%s"%(a+b)) # Q2 name = input("Please enter your name:") TP = input("Please enter your TP number:") marks = input("Please enter your marks:") grade = input("Please enter your grade:") CGPA = input("Please enter your CGPA:") print("Your details are as follows:") print(f"name:{name}\nTP number:{TP}\nMarks:{marks}\nGrade:{grade}\nCGPA:{CGPA}\nThanks for registration")
def HR(): again = "Yes" or "yes" while((again == "Yes")or(again == "yes")): print("Menu:") print("1.Create a Lectruer's profile") print("2.Create a Academic Leader's profile") print("3.Check the lecturer's profile") print("4.Check the employee leave status") print("5.Upload the yearly leaves") print("6.Upload the holyday") print("7.Upload the FAQs") x = int(input('Select the function you want to do : ')) if x == 1: L_name = input("Enter name: ") L_password = input("Enter password: ") f = open("Lectruer.txt","a") f.write(L_name) f.write(":") f.write(L_password) f.write("\n") f.write("\n") again = input("Do you want to use again? (Yes/No) :") elif x == 2: A_name = input("Enter name: ") A_password = input("Enter password: ") f = open("academic_leader","a") f.write(A_name) f.write(":") f.write(A_password) f.write("\n") f.write("\n") again = input("Do you want to use again? (Yes/No) :") elif x == 3: f = open("Lectruer.txt") y = f.read() print(y) again = input("Do you want to use again? (Yes/No) :") elif x == 4: f = open("Employee leave.txt") y = f.read() print(y) again = input("Do you want to use again? (Yes/No) :") elif x == 5: f = open("Yearly leave.txt") y = f.read() print(y) again = input("Do you want to use again? (Yes/No) :") elif x == 6: f = open("Holidays.txt","a") Holidays = input("Enter holidays: ") f.write(Holidays) f.write("\n") again = input("Do you want to use again? (Yes/No) :") elif x == 7: FAQs = input("Enter FAQs: ") f = open("FAQs.txt","a") f.write(FAQs) f.write("\n") f.write("\n") again = input("Do you want to use again? (Yes/No) :") def HR_Login() x = input("Enter your ID. ;") y = input("Enter your password :") f = open("HR_Login.txt") if x and y in f.read(): HR() else: print("Wrong ID or password.") def HR_register(): ch = "Yes"or"yes" print("Welcome to HR register system.") while((ch == "Yes")or(ch == "yes")): x = input("Please enter the register code. :") code = "123456789" if x == code: # register code for HR f1 = open("HR_Login.txt","a") f1.write("\n") f1.write("\n") y = input("Enter your ID :") z = input("Enter your password :") f1.write(y) f1.write(":") f1.write(z) else: print("Wrong register code.") ch = input("Do you want to use again? (Yes/No) :") print("Welcome to the Employees Leave Management System.") x = int(input("What is your profession? \n1.HR \n2.Lectruer \n3.Academic Leader \n4.HR register \nChoose one number :")) if x == 1: HR_Login() elif x == 4: HR_register() #这看起来不是很多行数
import time def upload_holiday(): """ HR's Function that used for Uploading Public and University Holidays, and store the holidays in dictionary of list data type afterward write it to plain text file. Note: Dictionary Key is holidays name and the value is a list consisting of only start date and end date, 2 elements """ PU_holidays = {} # initialize the empty FAQs dictionary n = 1 # Declare the holiday counting number while True: holiday_name = input(f"\nPls Enter the name for {n} Public and University Holidays and integer [-1] for exit:") # user input for holiday if holiday_name == str(-1): #Exit the Uploading print("Upload the Public and University Holidays and exit successfully!!! ") time.sleep(1) break else: # Enter the Leave holiday rule holiday_range = [] # initialize the empty list for storing holidays range start_date = input(f"Enter starting date for {holiday_name} in YYYY-MM-DD form:") holiday_range.append(start_date) end_date = input(f"Enter ending date for {holiday_name} in YYYY-MM-DD form:") holiday_range.append(end_date) PU_holidays[holiday_name] = holiday_range # add the key,value pair to holiday dictionary print(f"\nsuccessfully add the {holiday_name} holiday and the current Public and University holidays shown as below\n") time.sleep(1) print(PU_holidays) n += 1 continue with open("Public&University_Holidays.txt","w") as f: # write the policies to plain txt file for k,v in PU_holidays.items(): # iterate the holiday dictionary f.write(f"{k}:{v}\n") return PU_holidays
"""Lecturer 1. Can apply for leave. 2. Can check the status of the leave application. 3. Can view all public and University Holidays, also University’s Leave Policies.""" import time while True: lec_login_id = input("Enter login id:") #create user input lec_password = input("Enter password:") if lec_login_id != str(1) or lec_password != str(1) : # condition check on id and password print("Login id or password wrong, pls try again.......") time.sleep(1) continue else: print("\nLog in successfully, Welcome to Lecturer page\nSelect your lecturer opetion as below\n") time.sleep(1) while True: Lecturer_Choice = int(input("1.Apply for leave.\n2.check the status of the leave application.\n3.view all public and University Holidays, also University’s Leave Policies.\nSelect the lecturer's choice:")) if Lecturer_Choice == 1: # apply for leave break elif Lecturer_Choice == 2: # Can check the status of the leave application. with open('#.txt','r') as f: leave_application = f.read() print(leave_application) break elif Lecturer_Choice ==3: # Can view all public and University Holidays, also University’s Leave Policies. with open('#.txt','r') as f: holiday_policy = f.read() print(holiday_policy) break else: print("Pls enter correct number......") time.sleep(2) continue break
def fibo(n): a=0 b=1 d=0 while d<n: c=a+b a+=1 b+=1 print(c) #test x=int(input("enter no.:")) fibo(x)
""" deferred Deferred action wrapping Hans Buehler 2022 """ from .util import fmt_list from .logger import Logger _log = Logger(__file__) class Deferred(object): """ Defer an action such as function calls, item access, and attribute access to a later stage. This is used in dynaplot: fig = figure() # the DynanicFig returned by figure() is derived from Deferred ax = fig.add_subplot() # Deferred call for add_subplot() lns = ax.plot( x, y )[0] # This is a deferred call: plot() and then [] are iteratively deferred. fig.render() # renders the figure and executes first plot() then [0] lns.set_ydata( y2 ) # we can now access the resulting Line2D object via the Deferred wrapper fig.render() # update graph Typically, a code user would create a class which can defer actions by deriving from this class. For example assume there is a class A which we want to defer. class A(object): def __init__(self, x): self.x = x def a_function(self, y): return self.x * y def __getitem__(self, y): return self.x * y def __call__(self, y): return self.x * y class DeferredA( Deferred ): def __init__( self ): Deferred.__init__( info = "A" ) # give me a name def create( self, *kargs_A, **kwargs_A ): # deferred creation a = A(*kargs_A,**kwargs_A) self._dereference( a ) deferred_A = DeferredA() fx = deferred_A.a_function( 1. ) # will defer call to 'a_function' ix = deferred_A[2.] # will defer index access cl = deferred_A(3.) # will defer __call__ deferred_A.create( 1, x=2 ) # actually create A # This will trigger execution of all deferred actions # in order. Not that Deferred() works iteratively, e.g. all values returned from a function call, __call__, or __getitem__ are themselves deferred automatically. Deferred() is also able to defer item and attribute assignments. See cdxbasics.dynaplot.DynamicFig as an example. """ TYPE_SELF = 0 TYPE_CALL = 1 TYPE_ITEM = 2 TYPE_SET_ITEM = 4 TYPE_ATTR = 3 TYPE_SET_ATTR = 5 TYPES = [ TYPE_SELF, TYPE_CALL, TYPE_ITEM, TYPE_SET_ITEM, TYPE_ATTR, TYPE_SET_ATTR ] def __init__(self, info : str, *, typ : int = TYPE_SELF, ref = None): """ Initialize a deferred action. Typically, a code user would derive from this class and initialize __init__ with only the first 'info' argument giving their class a good name for error messages. See cdxbasics.dynaplot.DynamicFig as an example Parameters ---------- info : str Description of the underlying deferred parent operation/class for error messages. typ : int one of the TYPE_ values describing the type of action to be deferred. ref : argument for the action, e.g. TYPE_SELF: None TYPE_CALL: tuple of (argc, argv) TYPE_ITEM: key for [] TYPE_ATTR: string name of the attribute """ _log.verify( typ in Deferred.TYPES, "'type' must be in %s, found %ld", fmt_list(Deferred.TYPES), typ ) if typ == Deferred.TYPE_CALL: assert isinstance(ref,tuple) and len(ref) == 2, "Internal error: tuple of size 2 expected. Found %s" % str(ref) self._ref = ( list(ref[0]), dict(ref[1]) ) elif typ == Deferred.TYPE_ITEM: self._ref = ref elif typ == Deferred.TYPE_SET_ITEM: assert isinstance(ref, tuple) and len(ref) == 2, "Internal error: tuple of size 2 expected. Found %s" % str(ref) self._ref = ref elif typ == Deferred.TYPE_ATTR: self._ref = str(ref) elif typ == Deferred.TYPE_SET_ATTR: assert isinstance(ref, tuple) and len(ref) == 2, "Internal error: tuple of size 2 expected. Found %s" % str(ref) self._ref = ref else: _log.verify( ref is None, "'ref' must be none for TYPE_SELF") self._ref = None self._type = typ self._info = info self._live = None self._was_executed = False self._caught = [] @property def _result(self): """ Returns the result of the deferred action """ if not self._was_executed: _log.throw( "Deferred action %s has not been executed yet", self._info ) return self._live def _dereference(self, owner): """ Execute deferred action with 'owner' as the object the action is to be performed upon. If the current type is TYPE_SELF then the '_result' is simply 'owner' """ # execute the deferred action if self._was_executed: _log.throw("Deferred action %s has already been executed", self._info ) if self._type == Deferred.TYPE_CALL: try: live = owner( *self._ref[0], **self._ref[1] ) except Exception as e: _log.error("Error resolving deferred call to '%s': %s", self._info, e) raise e elif self._type == Deferred.TYPE_ITEM: try: live = owner[ self._ref ] except Exception as e: _log.error("Error resolving deferred item access to '%s', trying to access item '%s': %s", self._info, str(self._ref)[:100], e) raise e elif self._type == Deferred.TYPE_SET_ITEM: try: owner[ self._ref[0] ] = self._ref[1] live = None except Exception as e: _log.error("Error resolving deferred item assignment for '%s': tried to set item '%s' to '%s': %s", self._info, str(self._ref[0])[:100], str(self._ref[1])[:100], e) raise e elif self._type == Deferred.TYPE_ATTR: try: live = getattr( owner, self._ref ) except Exception as e: _log.error("Error resolving deferred attribute access to '%s', trying to read attribute '%s': %s", self._info, str(self._ref)[:100], e) raise e elif self._type == Deferred.TYPE_SET_ATTR: try: owner.__setattr__( self._ref[0], self._ref[1] ) live = None except Exception as e: _log.error("Error resolving deferred attribute assignment to '%s': tried to set attribute '%s' to '%s': %s", self._info, str(self._ref[0])[:100], str(self._ref[1])[:100], e) raise e else: # TYPE_SELF live = owner self._live = live self._was_executed = True # execute all deferred calls for this object for catch in self._caught: catch._dereference( live ) self._caught = None def __call__(self, *kargs, **kwargs): """ Deferred call () """ if self._was_executed: return self._result(*kargs, **kwargs) deferred = Deferred( typ=Deferred.TYPE_CALL, ref=(kargs,kwargs), info="%s(%s)" % (self._info, "..." if len(kwargs)+len(kargs)>0 else "") ) self._caught.append( deferred ) return deferred def __getitem__(self, key): """ Deferred reading item [] """ if self._was_executed: return self._result[key] deferred = Deferred( typ=Deferred.TYPE_ITEM, ref=key, info="%s[%s]" % (self._info, str(key))) self._caught.append( deferred ) return deferred def __setitem__(self, key, value): """ Deferred item assignment [] """ if self._was_executed: self._result[key] = value else: deferred = Deferred( typ=Deferred.TYPE_SET_ITEM, ref=(key, value), info="%s[%s] = %s" % (self._info, str(key), str(value)[:100])) self._caught.append( deferred ) def __getattr__(self, attr): """ Deferred attribute access """ attr = str(attr) if self._was_executed: return getattr(self._result,attr) deferred = Deferred( typ=Deferred.TYPE_ATTR, ref=attr, info="%s.%s" % (self._info,attr)) self._caught.append( deferred ) return deferred def __setattr_(self, attr, value): """ Deferred attribute access """ attr = str(attr) if self._was_executed: self._result.__setattr__(attr, value) else: deferred = Deferred( typ=Deferred.TYPE_SET_ATTR, ref=(attr,value), info="%s.%s = %s" % (self._info,attr,str(value)[:100])) self._caught.append( deferred )
#!/usr/bin/env python #wypelnienie list: lista1 = [x**2 for x in range(1,100000)] lista2 = [x**3 for x in range(1,50000)] #print(lista1, lista2) #print("dlugosc listy pierwszej to {}, a drugiej to {}".format(len(lista1), len(lista2))) #zadeklarowanie list wspolna = [] pierwiastki = [] #wypisywanie wspolnych elementow obu list: #for el in lista1: # if el in lista2: # wspolna.append(el) # else: # continue #rzutowanie list na sety: set1 = set(lista1) set2 = set(lista2) set3 = set1 & set2 #rzutowanie setu na liste: list3 = list(set3) #pierwiastkowanie kazdego elementu list3: for p in list3: pierwiastki.append((p**0.5)) #print(set3) #print(len(set3)) print(list3) print(pierwiastki) print(len(pierwiastki))
import numpy as np import random import math import matplotlib.pyplot as plot def SampleExp(rate): u = random.random() return - np.log(u) / rate def PoissonPmf(rate, t, limit): result = [] for k in range(limit): result.append(np.exp(-rate * t) * ((rate * t) ** k) / math.factorial(k)) return result def N(t, rate, sample_limit): count = 0 i = 1 X_sample_sum = 0.0 X_sample_hist = [] for i in range(sample_limit): X_sample_sum += SampleExp(rate) X_sample_hist.append(min(X_sample_sum, t)) if X_sample_sum < t: count += 1 return count, X_sample_hist rate = 2 t = 5 limit = 20 samples_a = [N(t, rate, limit)[1] for n in range(5)] # for sample in samples_a: # plot.plot(sample) # plot.show() # Weird stuff for a for samples in samples_a: plot.plot([len([s for s in samples if s < tau]) for tau in range (t + 1)]) plot.ylabel("N(t)") plot.xlabel("t") plot.show() samples_b = [N(t, rate, limit)[0] for n in range(1000)] expected_value_N = sum(samples_b)/1000.0 print("Expected value of N(t) for t = 5, rate = 2: " + str(expected_value_N)) variance_value_N = sum([(x - expected_value_N) ** 2 for x in samples_b]) / 1000.0 print("Variance value of N(t) for t = 5, rate = 2: " + str(variance_value_N)) theoretical = t * rate print("The theoretical expected value is " + str(theoretical)) poisson_pmf = PoissonPmf(rate, t, 20) fig,ax1 = plot.subplots() ax1.hist(samples_b) ax1.set_ylabel("# of N(t)") ax2 = ax1.twinx() ax2.plot(poisson_pmf, color='red') ax2.set_ylabel("P(N(t)=n") ax2.set_xlabel("N(t)") plot.show()
countries = {"Austria": "Vienna", "Croatia": "Zagreb", "Spain": "Madrid", "Slovenia": "Ljubljana"} correct = 0 incorrect = 0 for k in countries: # k stands for "key" in the dictionary, while the other thing is its "value" (v) capital = countries[k] print("\nWhat is the capital of:", k) # \n starts the string in a new line answer = input("Please type your answer: ") if answer.lower().upper() == capital.lower().upper(): print("Your answer is correct!") correct += 1 else: print("Sorry the answer is", capital + ".") incorrect += 1 print("Correct answers:", correct, "/ Incorrect answers:", incorrect)
import requests from bs4 import BeautifulSoup #connecting to the website and creating the beautiful soup object source = requests.get("https://www.dictionary.com/e/word-of-the-day/", timeout=5) #testing to see if connection can be established if source.status_code !=200: print("Couldn't connect to the website") exit() soup=BeautifulSoup(source.text,"html.parser") print("The Word of the Day\n") try: #printing the word of the day word = soup.find("div", class_="otd-item-headword__word") wod= word.h1.text print(wod.upper()) except: print("Couldn't get the word") try: #printing the type of the word wordType = soup.find("span", class_="luna-pos") print(wordType.text) except: print("Couldn't get the part of the speech") try: #printing the definition of the word d = soup.find("div", class_="otd-item-headword__pos") definition = d.find_all("p") try: print("\nDefinition of "+wod+": "+definition[2].text) except: print("\nDefinition of "+wod+": "+definition[1].text) except: print("Couldn't get the definition of the word") try: #printing examples of the word example = soup.find("div", class_="wotd-item-example__content") print("\nExample of "+wod+" in a sentence: "+"'"+example.p.text+"'\n") except: print("Couldn't get the example of the word")
"""This program is designed to take a csv formated spreadsheet of soccer players and distribute them evenly among three teams, ensuring that each team has the same number of experienced players. It then, based on a template file, generates form letters to the parents/guardians of each player, informing them of the team their child is on and the time of the first practice. """ import csv sharks = [] dragons = [] raptors = [] experienced = [] # Read in list of players with open('soccer_players.csv', newline='') as file: reader = csv.DictReader(file, delimiter=',') players = list(reader) # Sort experienced players into separate list for player in players[:]: if player['Soccer Experience'] == 'YES': experienced.append(players.pop(players.index(player))) # spread experienced players evenly between teams try: while True: sharks.append(experienced.pop()) raptors.append(experienced.pop()) dragons.append(experienced.pop()) except(IndexError): pass # spread inexperienced players evenly between teams try: while True: sharks.append(players.pop()) raptors.append(players.pop()) dragons.append(players.pop()) except(IndexError): pass # Read in template from file with open('template', 'r') as file: letter = file.read() # Write Sharks letters to files for player in sharks: with open(player['Name'].lower().replace(" ", "_") + ".txt", 'w') as file: file.write(letter.format(**player, league="Sharks", date="March 17 at 3PM")) # Write Dragons letters to files for player in dragons: with open(player['Name'].lower().replace(" ", "_") + ".txt", 'w') as file: file.write(letter.format(**player, league="Dragons", date="March 17 at 1PM")) # Write Raptors letters to file for player in raptors: with open(player['Name'].lower().replace(" ", "_") + ".txt", 'w') as file: file.write(letter.format(**player, league="Raptors", date="March 18 at 1PM"))
from linkedlist.linkedlist import Node, LinkedList def test_zipLists(): num=LinkedList() num.insert('1') num.insert_after('1','3') even_num=LinkedList() even_num.insert('2') even_num.insert_after('2','4') num.zipLists(even_num) assert str(num) =="{1} ->{2} ->{3} ->{4} ->Null"
from typing import Counter from stack_queue.stack_queue import Stack def validate_brackets(string): ls=[] open=Stack() for i in string: if i in ["(", "{", "[" ,")", "}", "]"]: ls.append(i) print(ls) for i in ls: if i in ["(", "{", "["]: open.push(i) else: if open.is_empty(): return False else: check=open.pop() if check =="{": if i != "}": return False elif check == '[': if i != ']': return False elif check== '(': if i !=')': return False return True # if __name__ == "__main__": # string = "(){}[[]]" # print(validate_brackets(string))
nombres=["juan", "ana", "marcos", "carlos", "luis"] cantidad=0 x=0 while x<len(nombres): if len(nombres[x])>=5: cantidad=cantidad+1 x=x+1 print("Todos los nombres son") print(nombres) print("Cantidad de nombres con 5 o mas caracteres") print(cantidad)
import random #importa un conjunto de datos aleatorios #=======================LISTA1============================================================ lisX=[] #definimos la lista #=========INGRESO DE VALORES============================================================== for x in range(10): #usamos el FOR para repetir 10 veces(10 valores) valor=random.randrange(100,1000)#ingresamos un valor lisX.append(valor) #añadimos el valor a la lista respectiva #=============PROCESO DE ORDENAMIENTO===================================================== def ordenamientoBurbuja(lisX): #definimos el tipo de ordenamiento for numPasada in range(len(lisX)-1,0,-1): #usamos FOR para repetir lo siguiente dependiendo del numero de elementos de la lista(en este caso 10) for i in range(numPasada): #usa FOR para que se repita tantas veces como numPasada if lisX[i]>lisX[i+1]: #agregamos el condicional, si un elemento x de la lista(ej:1) es mayor que el que le sigue x+1(1+1=2, el elemento 2): temp = lisX[i] #usamos la variable "temp" como un acumulador, en este caso acumula el elemento x de la lista lisX[i] = lisX[i+1] #hacemos un intercambio, donde el elemento que estaba en la posicion que sigue (osea, x+1) se ubica en la posicion en la que antes estaba el elemto x lisX[i+1] = temp #hacemos otro intercambio donde "temp"= elemento x, toma el lugar que dejo el elemento x+1 #=======TODO ESTE PROCESO SE REPITE HASTA QUE LA LISTA QUEDE EN ORDEN(MENOR A MAYOR)============ ordenamientoBurbuja(lisX) #=============FIN ORDENAMIENTO, AHORA LA IMPRESION DE LA LISTA(SALIDA)=================== print('lista sin ordenar') #imprime un aviso print(lisX) #imprime la lista #============Ordenamiento burbuja con cambio de sentido================================== def ordburbujaMayaMen(lisX): #definimos el tipo de ordenamiento for numPasada in range(len(lisX)-1,0,-1): #usamos FOR para repetir lo siguiente dependiendo del numero de elementos de la lista(en este caso 10) for i in range(numPasada): #usa FOR para que se repita tantas veces como numPasada if lisX[i]<lisX[i+1]: #agregamos el condicional, si un elemento x de la lista(ej:1) es mayor que el que le sigue x+1(1+1=2, el elemento 2): temp = lisX[i] #usamos la variable "temp" como un acumulador, en este caso acumula el elemento x de la lista lisX[i] = lisX[i+1] #hacemos un intercambio, donde el elemento que estaba en la posicion que sigue (osea, x+1) se ubica en la posicion en la que antes estaba el elemto x lisX[i+1] = temp #hacemos otro intercambio donde "temp"= elemento x, toma el lugar que dejo el elemento x+1 #=======TODO ESTE PROCESO SE REPITE HASTA QUE LA LISTA QUEDE EN ORDEN(MENOR A MAYOR)============ ordenamientoBurbuja(lisX) #=============FIN ORDENAMIENTO, AHORA LA IMPRESION DE LA LISTA(SALIDA)================== print ('ordenamiento burbuja menor a mayor') #imprime el titulo print(lisX) #imprime la lista ordburbujaMayaMen(lisX) #=============FIN ORDENAMIENTO, AHORA LA IMPRESION DE LA LISTA(SALIDA)================== print ('ordenamiento burbuja mayor a menor') #imprime el titulo print(lisX) #imprime la lista #================= ordenamiento con el metodo sort ==================================== print('ordenamiento utilizando el metodo sort (menor a mayor)') #imprime el titulo lisX.sort() #utilización de la funcion sort para ordenar print(lisX) #imprime la lista ordenada #================ordenamiento con el metodo sort (reverse) ============================ print('ordenamiento utilizando el metodo sort (mayor a menor)') #imprime la lista lisX.reverse() #utilizacion de la funcion reverse para cambiar el sentido del ordenamiento print(lisX) #imprime la lista
import sqlite3 from tkinter import * from tkinter import messagebox # PROGRAMADOR: JUAN PABLO MEZA GAZABÓN # -----------------------------------------FUNCIONES------------------------------------------ def limpiarCampos(): miId.set("") miNombre.set("") miApellido.set("") miEmail.set("") miTelefono.set("") def leer(): try: if (miBuscaId.get() != ""): miConexion = sqlite3.connect("CONTACTOS") miCursor = miConexion.cursor() miCursor.execute( "SELECT * FROM DATOS_CONTACTOS WHERE ID="+miBuscaId.get()) elContacto = miCursor.fetchall() if (not elContacto): messagebox.showwarning( "ERROR", "contacto no encontrado verifique el código del contacto") else: for contacto in elContacto: miId.set(contacto[0]) miNombre.set(contacto[1]) miApellido.set(contacto[2]) miTelefono.set(contacto[3]) miEmail.set(contacto[4]) miConexion.commit() else: messagebox.showerror( "ERROR", "Debe llenar el campo ID para buscar el contacto") except: messagebox.showwarning( "¡ATENCIÓN!", "Debe conectar la base de datos. \n Para conectarla diríjase a BBDD Y presione conectar") def mostrarContactos(): try: r = Text(root, width=80, height=15) miConexion = sqlite3.connect("CONTACTOS") miCursor = miConexion.cursor() miCursor.execute("SELECT * FROM DATOS_CONTACTOS") losContactos = miCursor.fetchall() if (losContactos): r.insert(INSERT, "ID\tNOMBRE \t\tAPELLIDO \t\tTELEFONO\t\tEMAIL\n") for contactos in losContactos: varId = str(contactos[0]) varNombre = str(contactos[1]) varApellido = str(contactos[2]) varTelefono = str(contactos[3]) varEmail = str(contactos[4]) r.insert(INSERT, varId+"\t"+varNombre+"\t\t" + varApellido+"\t\t"+varTelefono+"\t\t"+varEmail+"\t\n") r.place(x=20, y=240) r.config(state=DISABLED) else: messagebox.showwarning("ATENCIÓN","la lista de contactos está vacía") miConexion.commit() except: messagebox.showwarning( "¡ATENCIÓN!", "Debe conectar la base de datos. \n Para conectarla diríjase a BBDD Y presione conectar") def actualizar(): try: if (miBuscaId.get() != ""): miConexion = sqlite3.connect("CONTACTOS") miCursor = miConexion.cursor() datos = miId.get(), miNombre.get(), miApellido.get(), miTelefono.get(), miEmail.get() miCursor.execute( "UPDATE DATOS_CONTACTOS SET ID = ?, NOMBRE_CONTACTO = ?,APELLIDO =?,TELEFONO=?,EMAIL=?" + "WHERE ID="+miId.get(), (datos)) miConexion.commit() messagebox.showinfo("BBDD", "Usuario actualizado con éxito") limpiarCampos() else: messagebox.showerror( "ERROR", "Debe llenar el campo ID para actualizar el contacto") except: messagebox.showwarning( "¡ATENCIÓN!", "Debe conectar la base de datos. \n Para conectarla diríjase a BBDD Y presione conectar") def eliminar(): try: if (miBuscaId.get() != ""): miConexion = sqlite3.connect("CONTACTOS") miCursor = miConexion.cursor() miCursor.execute( "DELETE FROM DATOS_CONTACTOS WHERE ID="+miId.get()) messagebox.showinfo("BBDD", "Usuario eliminado con éxito") limpiarCampos() miConexion.commit() else: messagebox.showerror( "ERROR", "Debe llenar el campo ID para eliminar el contacto") except: messagebox.showwarning( "¡ATENCIÓN!", "Debe conectar la base de datos. \n Para conectarla diríjase a BBDD Y presione conectar") def AcercaDe(): messagebox.showinfo("Acerca de","Desarrollado por Juan Pablo Meza Gazabón \n"+ "Correo: [email protected]") def ayuda(): messagebox.showinfo("Ayuda","Implemente el Ejercicio de la Agenda de Contactos\n"+ "del Taller de Archivos, utilizando la base de datos\n"+ "SQLite y la libreria Tkinter." ) # -----------------------------------------GUI---------------------------------------------------- root = Tk() # -----------------------------------------BARRA DE MENÚ------------------------------------------ barraMenu = Menu(root) root.config(menu=barraMenu, width=300, height=300) root.resizable(0, 0) root.geometry("700x500") bbddMenu = Menu(barraMenu, tearoff=0) bbddMenu.add_command(label="Conectar", command=conexionBBDD) bbddMenu.add_command(label="Salir", command=salirAplicacion) borrarMenu = Menu(barraMenu, tearoff=0) borrarMenu.add_command(label="Borrar campos", command=limpiarCampos) crudMenu = Menu(barraMenu, tearoff=0) crudMenu.add_command(label="Guardar", command=guardar) crudMenu.add_command(label="leer", command=leer) crudMenu.add_command(label="Actualizar", command=actualizar) crudMenu.add_command(label="Eliminar", command=eliminar) ayudaMenu = Menu(barraMenu, tearoff=0) ayudaMenu.add_command(label="Ayuda",command=ayuda) ayudaMenu.add_command(label="Acerca de...",command=AcercaDe) barraMenu.add_cascade(label="BBDD", menu=bbddMenu) barraMenu.add_cascade(label="Borrar", menu=borrarMenu) barraMenu.add_cascade(label="CRUD", menu=crudMenu) barraMenu.add_cascade(label="Ayuda", menu=ayudaMenu) miframe = Frame(root) miframe.pack() colorFondo = "#006" colorLetra = "#FFF" root.config(background=colorFondo) miId = StringVar() miNombre = StringVar() miApellido = StringVar() miTelefono = StringVar() miEmail = StringVar() miBuscaId = StringVar() # -----------------------------------------CAJAS DE TEXTO------------------------------------------ cuadroId = Entry(root, textvariable=miId, fg="BLACK").place(x=150, y=50) cuadroNombre = Entry(root, textvariable=miNombre, fg="BLACK").place(x=150, y=80) cuadroApellido = Entry(root, textvariable=miApellido, fg="BLACK").place(x=150, y=110) cuadroTelefono = Entry(root, textvariable=miTelefono, fg="BLACK").place(x=150, y=140) cuadroEmail = Entry(root, textvariable=miEmail, fg="BLACK").place(x=150, y=170) buscaId = Entry(root, textvariable=miBuscaId).place(x=450, y=50) # -----------------------------------------LABELS------------------------------------------ etiquetaTitulo = Label(root, text="AGENDA DE CONTACTOS", bg="#006", fg=colorLetra).place(x=270, y=10) etiquetaId = Label(root, text="ID:", bg=colorFondo, fg=colorLetra).place(x=50, y=50) etiquetaNombre = Label(root, text="NOMBRE:", bg=colorFondo, fg=colorLetra).place(x=50, y=80) etiquetaApellido = Label(root, text="APELLIDO:", bg=colorFondo, fg=colorLetra).place(x=50, y=110) etiquetaTelefono = Label(root, text="TELEFONO:", bg=colorFondo, fg=colorLetra).place(x=50, y=140) etiquetaEmail = Label(root, text="EMAIL:", bg=colorFondo, fg=colorLetra).place(x=50, y=170) etiquetaConsultaId = Label( root, text="ID: ", bg=colorFondo, fg=colorLetra).place(x=430, y=50) # ---------------------------------------BOTONES................................................... botonVerContactos = Button(root, text="Ver contactos", bg="#009", fg="white", command=mostrarContactos).place(x=70, y=200) botonGuardar = Button(root, text="Guardar", bg="#009", fg="white", command=guardar).place(x=170, y=200) botonLimpiarCampos = Button(root, text="Limpiar", bg="#009", fg="white", command=limpiarCampos).place(x=240, y=200) botonBuscar = Button(root, text="Buscar", bg="#009", fg="white", command=leer).place(x=450, y=80) botonActualizar = Button(root, text="Actualizar", bg="#009", fg="white", command=actualizar).place(x=500, y=80) botonEliminar = Button(root, text="Eliminar", bg="#009", fg="white", command=eliminar).place(x=570, y=80) root.mainloop()
# Ejercicio Herencia POO # Archivo 1 class vehiculo: def __init__(self): self.nombre = input('Digite nombre de vehículo: ') self.marca = input('Digite la marca del vehículo: ') self.velocidad = int(input('Digite la velocidad del vehículo: ')) self.color = input('Digite el color del vehículo: ') self.canPas = input('Digite la cantidad máxima de pasajeros: ') def imprimir(self): print('Nombre vehículo: ' + self.nombre) print('Marca: ' + self.marca) print('Velocidad: ' + str(self.velocidad)) print('Color: ' + self.color) print('Cantidad pasajeros: ' + self.canPas)
#============Definir las listas============ listAlum=[] #lista de alumnos listPes=[] #lista de pesos listAlt=[] #lista de alturas listGen=[] #lista de generos #==========Ingreso de valores============= for x in range(3): #usamos el ciclo for para repertir las instrucciones siguientes 5 veces nom=input("Ingrese el nombre del alumno: ") #Ingresamos el nombre listAlum.append(nom) #añadimos el valor de la variable "nom" a la lista de nombres alt=float(input("Ingrese la altura de dicho alumno: ")) #ingresamos el valor de la altura listAlt.append(alt) #agregamos el valor de "alt" a la lista de alturas pes=int(input("ingrese el peso de dicho alumno: ")) #ingresamos el valor del peso listPes.append(pes) #agregamos el valor de "pes" a la lista de pesos gen=input("Ingrese el genero del alumno: ") #Ingresamos el genero listGen.append(gen) #agregamos el valor de "gen" a la lista de generos #===============INICIO DE ORDENAMIENTO DE DATOS================================= for k in range(2): #usamos FOR para que repita lo siguiente se repita 4 veces for x in range(2-k): #usa FOR,haciendo que se repita 4 veces menos la posicion que tome k if listAlt[x]<listAlt[x+1]: #colocamos un condicional,si el elemento de posicion x de la lista de alutra es menor que el elemento siguiente(elemento x+1) en la misma lista de altura auxAlt=listAlt[x] #usamos "auxAlt" como una variable que acumula el elemento x de la lista de altura listAlt[x]=listAlt[x+1] #ahora la posicion del elemento cambia con la del elemento anterior listAlt[x+1]=auxAlt #se hace lo mismo para el resto de listas (nombres,peso, genero) auxAlum=listAlum[x] listAlum[x]=listAlum[x+1] listAlum[x+1]=auxAlum auxPes=listPes[x] listPes[x]=listPes[x+1] listPes[x+1]=auxPes auxGen=listGen[x] listGen[x]=listGen[x+1] listGen[x+1]=auxGen #Ordenamiento de las listas en formato de tabla print("NOMBRE","ALTURA","PESO","SEX",sep="\t") for i in range(len(listAlum)): #for que se repite tantas veces como elementos tenga la lista de nombres print(listAlum[i],listAlt[i],listPes[i],listGen[i],sep="\t") nome="" #variable que almacena el nombre a eliminar print("A quien desea eleminar?") nome=input("Ingrese el nombre del alumno: ") index=listAlum.index(nome) #variable que almacena la posicion en la lista del nombre que se va a eliminar if listAlum[index]==nome: #si el nombre almacenado en la lista es igual al nombre a eliminar, borrar todos los registro relacionados a dicho nombre listAlum.pop(index) #eliminar el nombre en la lista de alumnos en la posicion correspondiente listPes.pop(index) #eliminar el peso en la lista de peso en la posicion correspondiente listAlt.pop(index) #eliminar la altura en la lista de altura en la posicion correspondiente listGen.pop(index) #eliminar el genero en la lista de genero en la posicion correspondiente #====================Ordenamiento de la lista sin el elemento eliminado ======================= for k in range(1): #se realizan los mismos procedimientos del ordenamiento anterior for x in range(1-k): if listAlt[x]<listAlt[x+1]: auxAlt=listAlt[x] listAlt[x]=listAlt[x+1] listAlt[x+1]=auxAlt auxAlum=listAlum[x] listAlum[x]=listAlum[x+1] listAlum[x+1]=auxAlum auxPes=listPes[x] listPes[x]=listPes[x+1] listPes[x+1]=auxPes auxGen=listGen[x] listGen[x]=listGen[x+1] listGen[x+1]=auxGen #Lista ordenada en formato de tablas sin el elemento eliminado print("Lista de alumnos, sus alturas y sus pesos ordenados de mayor a menor") print("NOMBRE","ALTURA","PESO","SEX",sep="\t") for y in range(len(listAlum)): print(listAlum[y],listAlt[y],listPes[y],listGen[y],sep="\t")
import multiprocessing import time #시작시간 start_time = time.time() #멀티쓰레드 사용 하는 경우 (20만 카운트) #Pool 사용해서 함수 실행을 병렬 def count(name): for i in range(1,50001): print(name," : ",i) num_list = ['p1', 'p2', 'p3', 'p4'] if __name__ == '__main__': #멀티 쓰레딩 Pool 사용 pool = multiprocessing.Pool(processes=2) # 현재 시스템에서 사용 할 프로세스 개수 pool.map(count, num_list) pool.close() pool.join() print("--- %s seconds ---" % (time.time() - start_time))
#Generator 예제2 #list comprehension 사용 리스트 생성 my_nums3 = [x for x in [1, 2, 3, 4, 5]] #타입 확인 print (type(my_nums3)) #for문 사용 출력 for i in my_nums3: print (i) #List comprehension 사용 제네레이터 생성 my_nums4 = (x for x in [1, 2, 3, 4, 5]) #my_nums4 = [x for x in [1, 2, 3, 4, 5]] #리스트 생성 #타입 확인 print (type(my_nums4)) #리스트 변환 출력 #print(list(my_nums4)) #제네레이터 출력 print (next(my_nums4)) print (next(my_nums4)) print (next(my_nums4)) print (next(my_nums4)) print (next(my_nums4)) #print (next(my_nums4)) #주석 해제 시 StopIteration 예외 발생
def BMI(h, w): bmi = w/((h/100)**2) return bmi bmi = BMI(180, 75) print("%.2f" % bmi) bmi = BMI(150, 30) print(bmi) bmi = BMI(160, 50) print("%.3f" % bmi)
# num = (input('Enter a list of numbers: ')).split(' ') # # list_num = list(num) # print(list_num) a = (input('Enter a list of numbers: ')).split(' ') list_a = list(a) even = 0 odd = 0 for i in range(0, len(list_a)): if i % 2 == 0: even += 1 else: odd += 1 print("Even: %d, odd: %d" % (even, odd))
nombre = input("¿como te llamas?") edad = int(input("que edad tiene?")) print("Hola", nombre) print("edad", edad)
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 18:38:53 2019 @author: jakej """ repeat = 6 while repeat == 6: string = input("Please enter a word or phrase: ") string = string.replace(" ","") string = string.lower() string = string.replace('?','') string = string.replace('!','') string = string.replace('-','') string = string.replace('.','') string = string.replace(',','') string = string.replace("'","") new_string = string[::-1] if string == new_string: print("this is indeed a palinome, very cool") else: print("this is not a palinome, you're done") again = input('want to go again? (n for no, y for yes): ') if again == 'y': repeat = 6 elif again == 'n': print('ok man') repeat = 0 else: print('invalid answer') repeat = 0
def calc(expr): array = expr.split() if len(array) == 0: return 0 index = 0 while index < len(array): if array[index] in "+-*/": num1 = float(array.pop(index-2)) num2 = float(array.pop(index-2)) index -= 2 result = 0 if array[index] == "+": result = num1 + num2 elif array[index] == "-": result = num1 - num2 elif array[index] == "*": result = num1 * num2 elif array[index] == "/": result = num1 / num2 else: print ("HOW!1!") array[index] = result index += 1 return float(array[len(array)-1])
class Lift(object): direction = 0 capacity = 0 people = [] floor = 0 floorsToVisit = [] listOfVisitedFloors = [] @classmethod def __init__(cls, capacity): cls.direction = -1 # "1" for up and "-1" for down. it is assigned -1 at the beginning because we treat as if Lift just arrived from the top and ready to start it's movement up cls.capacity = capacity cls.people = [] cls.floor = 0 cls.floorsToVisit = [] cls.listOfVisitedFloors = [0] # function that seeks floors that Lift needs to visit. # we assume that function is called right before Lift is switching its direction @classmethod def FindFloorsToVisit(cls, queues): cls.direction = -cls.direction cls.floorsToVisit = list(cls.people) floorsPossibleToVisit = [] if (cls.direction > 0): floorsPossibleToVisit = range(cls.floor, len(queues)) else: floorsPossibleToVisit = range(cls.floor, -1, -1) for floor in floorsPossibleToVisit: peopleOnIthFloor = queues[floor] if (cls.direction > 0): # lift goes up if (len([person for person in peopleOnIthFloor if person > floor]) > 0): # there are people going up from the current floor cls.floorsToVisit.append(floor) if (cls.direction < 0): # lift goes down if (len([person for person in peopleOnIthFloor if person < floor]) > 0): # there are people going down from the current floor cls.floorsToVisit.append(floor) cls.floorsToVisit = list(set(cls.floorsToVisit)) cls.floorsToVisit.sort() if (cls.direction < 0): cls.floorsToVisit.reverse() # At this point we have a list of floors that asked for the lift that are going in the same direction as the lift. # we are missing floors that are past the maximum (minimum when going down) floor, that are going the opposite direction. if (cls.direction > 0) : floorsPossibleToVisit = range(len(queues)-1, max(cls.floorsToVisit or [cls.floor]),-1) else : floorsPossibleToVisit = range(0,min(cls.floorsToVisit or [cls.floor])) for floor in floorsPossibleToVisit: peopleOnIthFloor = queues[floor] if (cls.direction > 0): if (len([person for person in peopleOnIthFloor if person < floor]) > 0): cls.floorsToVisit.append (floor) break else: if (len([person for person in peopleOnIthFloor if person > floor]) > 0): cls.floorsToVisit.append (floor) break @classmethod def AddFloorToVisit(cls, newFloor): cls.floorsToVisit.append(newFloor) cls.floorsToVisit = list(set(cls.floorsToVisit)) cls.floorsToVisit.sort() if (cls.direction < 0): cls.floorsToVisit.reverse() # this method will move lift through the list of floors in one direction and collect people @classmethod def MoveThroughAllFloors(cls ,queues): while (len(cls.floorsToVisit) > 0): cls.MoveToTheNextNeededFloor(queues) # Let's collect people from the last floor that lift stopped at peopleOnFloor = queues[cls.floor] #print ("Collecting: ",peopleOnFloor) while len(peopleOnFloor) > 0: if cls.capacity > len(cls.people): #print (cls.people) cls.people.append(peopleOnFloor[0]) peopleOnFloor.pop(0) else: break #print (cls.people) #print (self.) #print (queues) @classmethod def MoveToTheNextNeededFloor(cls, queues): visitingFloor = cls.floorsToVisit.pop(0) cls.floor = visitingFloor if (cls.listOfVisitedFloors[len(cls.listOfVisitedFloors)-1] != visitingFloor): cls.listOfVisitedFloors.append(visitingFloor) # First, let people exit indexOfLeavingPeople = [i for i,person in enumerate(cls.people) if person == visitingFloor] cls.removeElementsFromList(cls.people, indexOfLeavingPeople) # Now, let new people enter indexOfEnteredPeople = [] for i,personNeedsFloor in enumerate(queues[visitingFloor]): if cls.capacity > len(cls.people): if cls.direction > 0: if personNeedsFloor > visitingFloor: cls.people.append(personNeedsFloor) cls.AddFloorToVisit(personNeedsFloor) indexOfEnteredPeople.append(i) #print (self.people) else: if personNeedsFloor < visitingFloor: cls.people.append(personNeedsFloor) cls.AddFloorToVisit(personNeedsFloor) indexOfEnteredPeople.append(i) else: break cls.removeElementsFromList(queues[visitingFloor], indexOfEnteredPeople) @classmethod def removeElementsFromList(cls, listWithElements, indices): #print (listWithElements, indices) indices.reverse() for index in indices: listWithElements.pop(index) class Dinglemouse(object): def __init__(self, queues, capacity): self.lift = Lift(capacity) self.queues = queues def tupleToList(self, queues): result = [] for element in queues: result.append(list(element)) return result def theLift(self): result = [0] newQueues = self.tupleToList(self.queues) self.lift.FindFloorsToVisit(newQueues) print (newQueues) while len(self.lift.floorsToVisit) > 0: self.lift.MoveThroughAllFloors(newQueues) self.lift.FindFloorsToVisit(newQueues) result = self.lift.listOfVisitedFloors if (len(result) == 0): result.insert(0,0) if (result[len(result)-1] != 0): result.append(0) print result return result def testing(value1, value2): if (value1 == value2): print "Yep!" else: print "Nah." # Floors: G 1 2 3 4 5 6 Answers: tests = [#[ ( (), (), (5,5,5), (), (), (), () ), [0, 2, 5, 0] ], #[ ( (), (), (1,1), (), (), (), () ), [0, 2, 1, 0] ], #[ ( (), (3,), (4,), (), (5,), (), () ), [0, 1, 2, 3, 4, 5, 0] ], #[ ( (), (0,), (), (), (2,), (3,), () ), [0, 5, 4, 3, 2, 1, 0] ], #[ ( (5,), (), (), (), (), (), () ), [0, 5, 0] ], [ ((2,), (6,), (3, 7, 6, 8, 6), (8, 5, 8, 8), (), (8, 0), (), (), (5,)), [0, 1, 2, 3, 5, 6, 8, 5, 0, 2, 3, 5, 6, 7, 2, 3, 5, 6, 8, 3, 5, 8, 3, 8, 0] ] ] for queues, answer in tests: lift = Dinglemouse(queues, 2) testing(lift.theLift(), answer)
class Pong: def __init__(self, max_score): self.max_score = max_score self.scores = [0, 0] self.paddle_length = 7 self.current_player = 0 # 0 and 1 for 1st and 2nd player respectively def play(self, ball_pos, player_pos): print self.scores solution = "" if (self.max_score not in self.scores): if ball_pos >= player_pos - int(self.paddle_length / 2) and ball_pos <= player_pos + int(self.paddle_length / 2) : solution = "Player " + str(self.current_player + 1) + " has hit the ball!" self.current_player = (self.current_player + 1) % 2 else : self.current_player = (self.current_player + 1) % 2 self.scores[self.current_player] += 1 if (self.max_score in self.scores) : solution = "Player " + str(self.current_player +1 ) + " has won the game!" else : solution = "Player " + str((self.current_player + 1) % 2 + 1) + " has missed the ball!" else: solution = "Game Over!" return solution def testing(value1, value2): if (value1 == value2): print "Yep!" else: print "Nah." game = Pong(2) tests = [[ [50, 53], "Player 1 has hit the ball!" ], [ [100, 97], "Player 2 has hit the ball!" ], [ [0, 4], "Player 1 has missed the ball!" ], [ [25, 25], "Player 2 has hit the ball!" ], [ [75, 25], "Player 2 has won the game!" ], [ [50, 50], "Game Over!"] ] for indx, [task, answer] in enumerate(tests): print ("Step #%d :" % indx) testing(game.play(task[0], task[1]), answer)
#Various Data Types: #int - integer data type, only whole nos with no decimal #float - a number with decimals #str - string or combining all character like abc, blah a = 2 #integer variable b = 2.5 #float variable c = 'two' #string variable print (a, type(a)) print (b, type (b)) print (c, type(c)) #Type Conversion: When you put an integer and floating point like implicitly converting it d = 2.0 int (d) #float --> integer print (d, type(a)) e = 9 e = float (e) #integer --> float print (e, type(e)) f = 17 f = str(f) #integer --> string print (f, type(f)) g = 24.6 g = str(g) #float --> sting print (g, type(g))
guests_1 = [ "Bethaney Bain", "Kacey Johns", "Manpreet Saunders" ] guests_2 = [ "Elwood Curtis", "Diya Griffin", "Kacey Johns" ] guests_3 = [ "Tobey Weiss", "Kadie Barnes", "Diya Griffin" ] guests_total = guests_1 +guests_2 + guests_3 for x in sorted(set(guests_total)): print(x)
""" This file contains some useful binary_search questions """ def find_the_first_equal(sorted_list, search_val): """ find the fist equal value :param sorted_list: :param search_val: :return: """ left = 0 right = len(sorted_list) - 1 while left <= right: mid = left + ((right - left) >> 1) if search_val < sorted_list[mid]: right = mid - 1 elif search_val > sorted_list[mid]: left = mid + 1 else: if mid == 0 or sorted_list[mid - 1] != search_val: return mid else: right = mid - 1 return False def find_the_last_equal(sorted_list, search_val): """ find the last equal value :param sorted_list: :param search_val: :return: """ left = 0 right = len(sorted_list) - 1 while left <= right: mid = left + ((right - left) >> 1) if search_val < sorted_list[mid]: right = mid - 1 elif search_val > sorted_list[mid]: left = mid + 1 else: if mid == 0 or sorted_list[mid + 1] != search_val: return mid else: left = mid + 1 return False def find_the_first_big_or_equal(sorted_list, search_val): """ find the first big or equal :param sorted_list: :param search_val: :return: """ left = 0 right = len(sorted_list - 1) while left <= right: mid = left + ((right - left) >> 1) if search_val <= sorted_list[mid]: if mid == 0 or sorted_list[mid - 1] > search_val: return mid else: right = mid - 1 else: left = mid + 1 return False def the_last_small_or_equal(sorted_list, search_val): """ find the last small or equal :param sorted_list: :param search_val: :return: """ left = 0 right = len(sorted_list) - 1 while left <= right: mid = left + ((right - left) >> 1) if search_val >= sorted_list[mid]: right = mid - 1 else: if mid == len(sorted_list) - 1 or search_val < sorted_list[mid]: return mid else: left = mid + 1 return False if __name__ == '__main__': print(find_the_first_equal([1, 2, 4, 7, 9], 5))
# Question 20 # Define a class with a generator which can iterate the numbers,which are divisible by 7, between a given range 0 and n. # Hints: # Consider use yield # https://docs.python.org/3/reference/expressions.html?highlight=yield #Solution: from audioop import reverse def putNumbers(n): i = 0 while i < n: j = i i = i + 1 if j % 7 == 0: yield j for i in reverse(100): print(i)
# importing tkinter from tkinter import * root = Tk() root.title("Tkinter calculator") # adding title # getting input from user num_input= Entry(root,width=45, borderwidth= 2) num_input.grid(row =0 , column =0, columnspan=4,pady=10,ipady=8) global input_operator ip_op = '+' global first_number f_num=0 # displaying seleted numbers on the text box def input_num(num): if num != 'clear_all': current = num_input.get() num_input.delete(0, END) num_input.insert(0, str(current)+str(num)) # fnum = num_input.insert(0, str(current)+str(num)) return else: num_input.delete(0, END) return # defining function to perform basic mathematical operations def add_function(): global first_number first_num = num_input.get() first_number = first_num num_input.delete(0,END) global input_operator input_operator = '+' def multiply_function(): first_num = num_input.get() global first_number first_number = first_num num_input.delete(0,END) global input_operator input_operator = 'x' def divide_function(): first_num = num_input.get() global first_number first_number = first_num num_input.delete(0,END) global input_operator input_operator = '/' def substract_function(): first_num = num_input.get() global first_number first_number = first_num num_input.delete(0,END) global input_operator input_operator = '-' # function for equal button def equal(input_operator): if input_operator == '+': second_num = num_input.get() num_input.delete(0,END) num_input.insert(0, int(first_number)+int(second_num)) if input_operator == 'x': second_num = num_input.get() num_input.delete(0,END) num_input.insert(0, int(first_number)*int(second_num)) if input_operator == '/': second_num = num_input.get() num_input.delete(0,END) num_input.insert(0, int(first_number)/int(second_num)) if input_operator == '-': # if the second_num = num_input.get() num_input.delete(0,END) num_input.insert(0, int(first_number)-int(second_num)) # declaring buttons for numbers button_1 = Button(root, text="1", padx=30, pady=15, command=lambda: input_num(1), bg='#add8e6').grid(row=1, column=0) # 1 button_2 = Button(root, text="2", padx=30, pady=15, command=lambda: input_num(2), bg='#add8e6').grid(row=1, column=1) # 2 button_3 = Button(root, text="3", padx=30, pady=15, command=lambda: input_num(3), bg='#add8e6').grid(row=1, column=2) # 3 button_4 = Button(root, text="4", padx=30, pady=15, command=lambda: input_num(4), bg='#add8e6').grid(row=2, column=0) # 4 button_5 = Button(root, text="5", padx=30, pady=15, command=lambda: input_num(5), bg='#add8e6').grid(row=2, column=1) # 5 button_6 = Button(root, text="6", padx=30, pady=15, command=lambda: input_num(6), bg='#add8e6').grid(row=2, column=2) # 6 button_7 = Button(root, text="7", padx=30, pady=15, command=lambda: input_num(7), bg='#add8e6').grid(row=3, column=0) # 7 button_8 = Button(root, text="8", padx=30, pady=15, command=lambda: input_num(8), bg='#add8e6').grid(row=3, column=1) # 8 button_9 = Button(root, text="9", padx=30, pady=15, command=lambda: input_num(9), bg='#add8e6').grid(row=3, column=2) # 9 button_0 = Button(root, text="0", padx=30, pady=15, command=lambda: input_num(0), bg='#add8e6').grid(row=4, column=0) # 0 # declaring buttons for operators add_button = Button(root, text="+", padx=30,pady=42, command=add_function,bg='#ffffa1') add_button.grid(row=2, column=3,rowspan=2) divide_button = Button(root, text="/", padx=30,pady=15, command=divide_function,bg='#ffffa1') divide_button.grid(row=4, column=1) multiply_button = Button(root, text="x", padx=30,pady=15, command=multiply_function,bg='#ffffa1') multiply_button.grid(row=4, column=2) substract_button = Button(root, text="-", padx=31, pady=15, command=substract_function,bg='#ffffa1') substract_button.grid(row=4, column=3) # declaring equal button and clear all button clear_button = Button(root, text="C", padx=30,pady=15, command=lambda: input_num('clear_all'),bg='#ff9a9a') clear_button.grid(row=1, column=3) equal_button= Button(root, text='=', padx=142, pady=15,command=lambda: equal(input_operator),bg='#9affcc') equal_button.grid(row=5, column=0, columnspan=4) root.mainloop()
import tkinter as tk import traceback from tkinter import * from tkinter import messagebox from datetime import date from Budget import Budget # TODO: create GUI for budgets after creation # TODO: functionality for entering paycheck # TODO: delete budget class GUI(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.grid() self.lbl_hello = tk.Label(text="Welcome to the Budget Console") self.lbl_name = tk.Label(text="Name") self.lbl_type = tk.Label(text="Type") self.lbl_amount = tk.Label(text="Amount") self.lbl_field_name = tk.Label(text="Name") self.lbl_field_saved = tk.Label(text="Saved") self.lbl_field_amount = tk.Label(text="Amount") self.lbl_field_type = tk.Label(text="Type") self.lbl_paycheck = tk.Label(text="Paycheck") self.lbl_date = tk.Label(text="Date") self.lbl_total = tk.Label(text="Total") self.lbl_free = tk.Label(text="Free Cash") self.txt_name = tk.Entry() self.txt_amount = tk.Entry() self.txt_paycheck = tk.Entry() self.txt_date = tk.Entry() self.txt_total = tk.Entry() self.txt_free = tk.Entry() self.types = StringVar() self.types.set("Amount") self.opt_type = tk.OptionMenu(self.master, self.types, "Amount", "Percentage") self.btn_create = tk.Button(text="Create Budget", command=lambda: self.create_budget()) self.btn_save = tk.Button(text="Save Budget", command=lambda: self.save_budget()) self.btn_print = tk.Button(text="Print Budgets", command=lambda: self.print_budgets()) self.btn_calculate = tk.Button(text="Calculate", command=lambda: self.insert_calculations()) self.budgets = [] self.budget_fields = [[]] self.create_widgets() def create_widgets(self): self.lbl_hello.grid(row=0) self.btn_save.grid(row=0, column=2) self.btn_print.grid(row=0, column=3) self.lbl_name.grid(row=1) self.txt_name.grid(row=1, column=1) self.lbl_type.grid(row=2) self.opt_type.grid(row=2, column=1) self.lbl_amount.grid(row=3) self.txt_amount.grid(row=3, column=1) self.lbl_paycheck.grid(row=3, column=2) self.txt_paycheck.grid(row=3, column=3) self.btn_create.grid(row=4, column=1) self.btn_calculate.grid(row=4, column=3) self.lbl_field_name.grid(row=5) self.lbl_field_saved.grid(row=5, column=1) self.lbl_field_amount.grid(row=5, column=2) self.lbl_field_type.grid(row=5, column=3) self.lbl_date.grid(row=6) self.lbl_total.grid(row=6, column=1) self.lbl_free.grid(row=6, column=2) self.txt_date.grid(row=7) self.txt_total.grid(row=7, column=1) self.txt_free.grid(row=7, column=2) def create_budget(self): budget = Budget() try: budget_name = str(self.txt_name.get()) budget.set_name(budget_name) try: budget_type = self.types.get() budget.set_type(budget_type) if budget.is_fixed(): budget.set_amount(float(self.txt_amount.get())) else: budget.set_percentage(float(self.txt_amount.get())) self.budgets.append(budget) self.insert_budget_field() self.clear_create_fields() except ValueError: messagebox.showwarning("Invalid Fields", "Amount field must be a decimal value.") except TypeError: self.txt_name.insert(0, "Enter Name Here") # traceback.print_exc(file=sys.stdout) def insert_budget_field(self): num = len(self.budgets) print(num) budget = self.budgets[num-1] row = num + 6 budget_name = tk.Label(text=budget.get_name()) budget_save = tk.Entry() budget_amount = tk.Entry() if budget.is_fixed(): budget_amount.insert(0, budget.get_amount()) else: budget_amount.insert(0, budget.get_percentage()) budget_type = tk.Label(text=budget.get_type()) self.budget_fields.append([]) self.budget_fields[num-1].append(budget_name) self.budget_fields[num-1].append(budget_save) self.budget_fields[num-1].append(budget_amount) self.budget_fields[num-1].append(budget_type) self.lbl_date.grid(row=row+1) self.lbl_total.grid(row=row+1, column=1) self.lbl_free.grid(row=row+1, column=2) self.txt_date.grid(row=row + 2) self.txt_total.grid(row=row + 2, column=1) self.txt_free.grid(row=row + 2, column=2) # TODO: Make this prettier for i in range(0, len(self.budget_fields[num-1])): self.budget_fields[num-1][i].grid(row=row, column=i) # TODO: Exceptions # TODO: Can this calculation be separate? Separate controller where budgets are stored def insert_calculations(self): try: total = 0.0 paycheck = float(self.txt_paycheck.get()) for budget, budget_field in zip(self.budgets, self.budget_fields): budget.set_saved(budget.calculate_budget(paycheck)) total += budget.get_saved() budget_field[1].delete(0, END) budget_field[1].insert(0, budget.get_saved()) self.txt_date.delete(0, END) self.txt_date.insert(0, date.today()) self.txt_total.delete(0, END) self.txt_total.insert(0, total) self.txt_free.delete(0, END) self.txt_free.insert(0, paycheck - total) except ValueError: messagebox.showwarning("Invalid Fields", "Paycheck field must be a decimal value.") def clear_create_fields(self): self.txt_name.delete(0, END) self.txt_amount.delete(0, END) self.types.set("Amount") def save_budget(self): filename = "Budget-" + str(date.today()) + ".txt" file = open(filename, 'w') file.write(str(self.budgets)) file.close() def print_budgets(self): print(self.budgets) def main_window(): root = Tk() root.title("Budget Console") gui = GUI(master=root) gui.mainloop()
#!/bin/python3 def displayShopItems(): print(""" 1. Cool Sword (100g) 2. Cool Spear (150g) 3. Cool Shield (210g) 4. Cool School (1000g) 5. Cool Armour (200g) 6. Cool Glock 19 (500g) 7. Cool Roger (1g) """) def buyItem(number): global totalMoney number = int(number) if number == 1 and totalMoney >= 100: # we have to subtract money spent totalMoney -= 100 print("Sword bought!") print("Money left: " + str(totalMoney)) bag = [] # starting gold totalMoney = 1000 print(""" Welcome to the cool shop :) What would you like to do in my cool shop? 1. View All Items in the shop 2. View All Items you have 3. Buy item 4. Sell item 5. Exit shop """) while True: userChoice = int(input("Enter a number: ")) if userChoice == 1: displayShopItems() elif userChoice == 2: print(bag) elif userChoice == 3: itemToBuy = input("Enter an item to buy: ") if len(bag) == 5: print("Bag is full!") else: buyItem(itemToBuy) elif userChoice == 4: itemToDelete = input("Enter the item to sell: ") for x in range(len(bag)): if itemToDelete == bag[x]: print(bag[x] + " removed.") bag.remove(bag[x]) break else: print("Item not found!") elif userChoice == 5: break else: print("Invalid")
from tkinter import * from dice import DiceSet from score_pad import ScorePads def read_int(prompt): while True: print("%s: " % prompt, end='') try: value = int(input()) except: pass else: if value >= 0: return value def dice_game(nplayers, ndice): root = Tk() button_frame = Frame(root) button_frame.pack() dice = DiceSet(root, ndice) dice.pack() dice.roll_all() score_pads = ScorePads(root, nplayers) score_pads.pack(); def restart() : score_pads.reset() Button(button_frame, text="Roll unheld", command=dice.roll_unheld).pack(side=LEFT) Button(button_frame, text="Roll all", command=dice.roll_all).pack(side=LEFT) Button(button_frame, text="Reset", fg="red", command=restart).pack(side=LEFT) Button(button_frame, text="Quit", fg="red", command=root.quit).pack(side=LEFT) # Bring to top root.lift() root.attributes("-topmost", True) root.attributes("-topmost", False) root.mainloop() root.destroy() if __name__ == "__main__" : dice_game( nplayers=read_int("Number of players"), ndice=read_int("Number of dice") )
class my_defaultdict: def __init__(self, **kwargs): self.elements = dict(kwargs) def __repr__(self): return str(self.elements) def __getitem__(self, key): return self.elements[key] def __setitem__(self, key, elem): self.elements[key] = elem if __name__ == '__main__': test = my_defaultdict(a = 1, b = 2, c = 3) print(test) print(test['a']) test['d'] = 4 print(test) test['d'] = 5 print(test) print(str(test))
import math def main(): print("This program approximates pi by summing the terms of a series.") print() n = int(input("How many terms should be used? ")) total = 0.0 sgn = 1.0 for denom in range(1, 2*n, 2): total = total + sgn * 4.0/denom sgn = -sgn print("Approximation to pi is:", total) print("Difference from math.pi:", math.pi - total) main()
def main(): print("Fill in the words to play MadLibs!") noun = input("Enter a noun: ") verb = input("Enter a verb: ") adverb = input("Enter a adverb: ") place = input("Enter a place: ") print("The", noun, "needed to", verb, adverb, "into the", place)