text
stringlengths
37
1.41M
x = "python is the best choice" #f포맷형식으로 문자열 출력하기 print(f'{x:!^30}') #포맷형식으로 문자열 출력하기 print('{0:!^30}'.format(x)) #기본 함수 count print(x.count('p')) #
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): lca = None def Lowest_Common_Ancestor_of_bst(self, root, val1, val2): if root == None: return False lres = False rres = False self_check = (root == val1) or (root == val2) lres = self.Lowest_Common_Ancestor_of_bst(root.left, val2, val1) if self.lca == None: rres = self.Lowest_Common_Ancestor_of_bst(root.right, val1, val2) if (self_check and lres) or (self_check and rres) or (rres and lres): self.lca = root return self_check or lres or rres def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ self.Lowest_Common_Ancestor_of_bst(root, p, q) return self.lca
""" 百分制成绩转换为等级制成绩 如果输入的成绩在90分以上(含90分)输出A;80分-90分(不含90分)输出B;70分-80分(不含80分)输出C;60分-70分(不含70分)输出D;60分以下输出E。 """ grade = int(input("your grade is ")) if grade < 60 : print("E") elif grade < 70 : print("D") elif grade < 80 : print("C") elif grade < 90 : print("B") else : print("A")
#输出100以内所有的素数 for i in range(1,101) : test = i #test = int(input("输入一个正整数")) #if test <= 1 : #print("输入一个正整数") flag=1 for i in range(2,test) : if test % i ==0 : flag = 0 break """ if flag == 0 : print("no") else : print("yes") """ if flag != 0 : print(test,end=" ")
# Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв. # https://drive.google.com/file/d/1JbdCQuVEjihRc3hV-QbY97-2hAA5VbPa/view?usp=sharing import string a = input('Введите первую букву: ') b = input('Введите вторую букву: ') first_pos = string.ascii_letters.find(a) second_pos = string.ascii_letters.find(b) print(first_pos + 1) # т.к. счет позиций начинается с 0, прибавляем 1 print(second_pos + 1) print(abs(first_pos - second_pos) - 1) # используется модуль, чтоб получить положительное число, если первая введеная буква в алфавите стоит вначале второй
from cs50 import SQL import sys import csv # Check numbers of arguments if len(sys.argv) != 2: print("Usage: python roster.py houseName") sys.exit(1) # Connection to the DB db = SQL("sqlite:///students.db") # Name of the house to look for house = sys.argv[1] # Query the DB rows = db.execute("SELECT * FROM students WHERE house=? ORDER BY last, first", house) # For each row we print full name and birth for row in rows: print(row["first"] + " " + (row["middle"] + " " if row["middle"] != None else "") + row["last"] + ", " + "born " + str(row["birth"]))
#!/usr/bin/env python2 import numpy as np import os import sys ''' This function takes a list of North-East-Down (NED) coordinates from a specified file and rotates them in 2D space so that the North direction is aligned with the specified heading. The Down coordinates are unchanged by this function. Usage: python rotate_mission.py des_bearing ''' def calculate_new_coords(brg,orig_coords): ''' Rotates each coordinate in 2D space to be aligned with the specified bearing from North. Altitude (Down) is unchanged. ''' # Extract arrays N = orig_coords[0] E = orig_coords[1] D = orig_coords[2] # Convert to radians brg = float(brg) brg = brg*np.pi/180 # Create rotation matrix R = [[np.cos(brg),-np.sin(brg)],[np.sin(brg),np.cos(brg)]] R = np.matrix(R) # Rotate NE parts and assign to new array new_coords = [[],[],list(D)] for i in range(0,len(N)): arr = np.array([[N[i]],[E[i]]]) new_N,new_E = R*arr new_N = round(new_N,5) new_E = round(new_E,5) new_coords[0].append(new_N) new_coords[1].append(new_E) return new_coords def write2py(alt_takeoff,wp_offset,coords,filename): ''' Writes coords to specified filename. To match desired format of a mission file for Aerowake project, this function will write the new file as: # This mission file created from rotate_mission.py, a part of the Creare AeroWake project. wp_N = [#,#,#,...] wp_E = [#,#,#,...] wp_D = [#,#,#,...] num_wp = # ''' write_str = '# This mission file created using rotate_mission.py, a part of the Creare AeroWake project.\n\n' write_str = write_str + 'alt_takeoff = %s\n' %(alt_takeoff) write_str = write_str + 'wp_offset = %s\n' %(wp_offset) write_str = write_str + 'wp_N = %s\n' %(coords[0]) write_str = write_str + 'wp_E = %s\n' %(coords[1]) write_str = write_str + 'wp_D = %s\n' %(coords[2]) write_str = write_str + 'num_wp = len(wp_N)' with open(filename, 'w') as output: output.write(write_str) def rotate(orig_coords, bearing): return calculate_new_coords(bearing,orig_coords)
#!/usr/bin/env python3 """ Show Foreign Currency/PLN pair. It is based on Polish Central Bank (NBP) fixing exchange rate. """ import argparse from exchange_rate.helpers.version import package_version from exchange_rate.exchange_rate_to_pln import ExchangeRateToPLN _DESCRIPTION = "Shows Foreign Currency/PLN pair based on Polish \ Central Bank (NBP) fixing exchange rate." def _parse_program_argv(): parser = argparse.ArgumentParser(description=_DESCRIPTION) parser.add_argument('currency', metavar='currency', nargs='?', type=str, default='USD', help='currency code to compare with PLN') parser.add_argument('-v', '--version', action='version', version=package_version('exchange-rate')) args = parser.parse_args() return args.currency def main(): """Enter the program.""" currency = _parse_program_argv() rate_to_pln = ExchangeRateToPLN().get_exchange_rate_to_pln(currency) print('1 {0} = {1} PLN'.format(currency, rate_to_pln)) if __name__ == "__main__": main()
''' This is a program for a simple BlackJack game A deck of 52 cards will be used and a single player plays against the dealer (computer) The player may place a bet For simplicity, only features like hit and stand are available features like split, double, and insurance will be added in later versions ''' import random suits = ('Spades', 'Hearts', 'Clubs', 'Diamonds') # The four suits of cards in a deck ranks = ('Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King') # The thirteen ranks of cards values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} # Values of all ranks for the game playing = True class Card: ''' A class for making cards objects. These 52 unique cards are added to a deck. Note : There is no use of Jokers in BlackJack so those cards are omitted. ''' def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return self.rank + ' of ' + self.suit class Deck: ''' A class for putting together a deck of cards. The Card class is used to make the unique cards to put into the deck. ''' def __init__(self): self.deck = [] for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) def __str__(self): deck = '' for card in self.deck: deck += '\n' + card.__str__() return deck def shuffle(self): random.shuffle(self.deck) def deal(self): single_card = self.deck.pop() return single_card class Hand: ''' A class for building a hand with values for proceeding the game and deciding the winner. The Card class is used. ''' def __init__(self): self.cards = [] self.value = 0 self.aces = 0 def add_card(self, card_): self.cards.append(card_) self.value += values[card_.rank] def adjust_for_aces(self): if self.value > 21 and self.aces: self.value -= 10 self.aces -= 1 class Chips: ''' Chips are used to bet. This is currency of this game. A user gets 500 chips by default. ''' def __init__(self): self.total = 500 self.bet = 0 def show_chips(self): return self.total def win_bet(self): self.total = self.total + self.bet def lose_bet(self): self.total = self.total - self.bet def take_bet(chips): ''' Takes input : an object of chips type Output : sets a value for the bet attribute of Chips class Function to take input of bet by the player and check if it exceeds the chips the player has ''' while True: try: bet = int(input('Place your bet: ')) except ValueError: print('Invalid bet! Try again!') else: if bet > chips.total: print('You don\'t have enough chips for that much bet. Please try again!') else: chips.bet = bet break def hit(deck, hand): ''' Takes input arguments : an object of deck type, an object of hand type Output : Calls functions of Hand class Function to perform the hit action in a game of BlackJack (hit is when a player demands for a card from the dealer) ''' hand.add_card(deck.deal()) hand.adjust_for_aces() def stand(): ''' Takes no input argument Output : boolean value Function to operate on the global variable - playing. Function to perform the stand action in a game of BlackJack (stand is when the player wants no more cards) ''' global playing playing = False def hit_or_stand(deck, hand): ''' Takes input : an object of Deck type, an object of Hand type Output : calls hit or stand function as per user's request Function to perform one of the actions of BlackJack as pepr user's request ''' while True: hit_stand = input('Press H to hit\nPress S to stand: ') if hit_stand.lower() == 'h': hit(deck, hand) elif hit_stand.lower() == 's': stand() else: print('Sorry. Please try again!') continue break def show_some(player, dealer): ''' Takes input : an object - player of Hand type, an object - dealer of Hand type Output : prints the cards as per the need Function to show some cards while the player plays ''' print('Dealer\'s Hand: ') print('<Hidden Card>', dealer.cards[1]) print('Player\'s Hand: ') print(*player.cards, sep='\t') def show_all(player, dealer): ''' Takes input : an object - player of Hand type, an object - dealer of Hand type Output : prints the cards as per the need Function to show all cards when the player stands ''' print('Dealer\'s Hand: \n', *dealer.cards, sep='\t') print('Dealer Value : ', dealer.value) print('\nPlayer\'s Hand: \n', *player.cards, sep='\t') print('Player Value : ', player.value) def player_busts(player, dealer, chips): ''' Takes input : object of Hand type - player, object of Hand type - dealer, object of Chips type - chips Output : calls funtion from Chips class Function performs bust action if the player is busted (player loses) ''' print('Busted! Better Luck Next Time!!') chips.lose_bet() def player_wins(player, dealer, chips): ''' Takes input : object of Hand type - player, object of Hand type - dealer, object of Chips type - chips Output : calls funtion from Chips class Function performs the player winning action (player wins) ''' print('You win! Congratulations!!') chips.win_bet() def dealer_busts(player, dealer, chips): ''' Takes input : object of Hand type - player, object of Hand type - dealer, object of Chips type - chips Output : calls funtion from Chips class Function performs the player winning action if the dealer is busted (player wins) ''' print('Dealer Busted! Congratulations!!') chips.win_bet() def dealer_wins(player, dealer, chips): ''' Takes input : object of Hand type - player, object of Hand type - dealer, object of Chips type - chips Output : calls funtion from Chips class Function performs the lose action (player loses) ''' print('You Lose! Better Luck Next Time!!') chips.lose_bet() def pushed(player, dealer): ''' Takes input : object of Hand type - player, object of Hand type - dealer Output : prints the outcome as per the situation Function performs the push action of the game when the dealer ties with the player ''' print('Pushed!') # now to play the game if __name__ == '__main__': while True: print('Welcome to BlackJack!') # Making and Shuffling new deck to play game new_deck = Deck() new_deck.shuffle() # Defining player and dealer hands and dealing cards one by one player = Hand() dealer = Hand() player.add_card(new_deck.deal()) dealer.add_card(new_deck.deal()) player.add_card(new_deck.deal()) dealer.add_card(new_deck.deal()) # Giving Chips to player to play player_chips = Chips() print('You have %d chips' % player_chips.show_chips()) take_bet(player_chips) show_some(player, dealer) print(player.value) while playing: hit_or_stand(new_deck, player) show_some(player, dealer) print(player.value) if player.value > 21: player_busts(player, dealer, player_chips) break if player.value <= 21: while dealer.value < 17: hit(new_deck, dealer) show_all(player, dealer) if player.value > dealer.value: player_wins(player, dealer, player_chips) elif dealer.value > player.value: dealer_wins(player, dealer, player_chips) elif dealer.value > 21: dealer_busts(player, dealer, player_chips) else: pushed(player, dealer) print('You have %d chips' % player_chips.show_chips()) play_again = input('Do you want to play again? Y/N: ') if play_again.lower() == 'y': playing = True continue else: print('Thank You for playing!') break
class MessageBroker(object): """ This class represents broker for the messages of a simulation """ def __init__(self, messages_to_be_transmitted = None): """ Constructor. messages_to_be_transmitted -- The message that are to be transmitted """ self.to_be_transmitted = messages_to_be_transmitted or [] def add_to_be_transmitted(self, event): """Adds a message to be transmitted""" self.to_be_transmitted.append(event) def reset_messages_to_transmit(self): """Resets (clears) the messages to be transmitted""" self.to_be_transmitted = [] def get_message_to_be_transmitted(self): """Get a message to be transmitted""" if not self.to_be_transmitted: return None return self.to_be_transmitted.pop() def still_msgs_to_be_transmitted(self): """Ask if there are still messages to be transmitted""" return not self.to_be_transmitted def __str__(self): """Returns the string representation of the message broker""" return "Messages To be transmitted\n" + str(self.to_be_transmitted) class Message(object): def __init__(self, sender, emit_location, function_to_call, arguments): """Constructor""" self.sender = sender self.emit_location = emit_location self.function_to_call = function_to_call self.arguments = arguments class DirectMessage(Message): """Message with a specific node list destination""" def __init__(self, sender, emit_location, function_to_call, destination_list, arguments): """Constructor""" Message.__init__(self, sender=sender, emit_location=emit_location, function_to_call=function_to_call, \ arguments=arguments) self.destination_list = destination_list def run(self, plane, all_nodes): """Sends the message to the respective nodes which could hear it""" event_and_messages = {'messages': [], 'asynchronous': [], 'simulator': []} for node_id in self.destination_list: new_events_and_messages = self.function_to_call(all_nodes[node_id], **self.arguments) event_and_messages['messages'] += new_events_and_messages['messages'] event_and_messages['simulator'] += new_events_and_messages['simulator'] event_and_messages['asynchronous'] += new_events_and_messages['asynchronous'] return event_and_messages class BroadcastMessage(Message): """Message sent by a node which the neighbours for that node receive""" def __init__(self, sender, emit_location, function_to_call, arguments): """Constructor""" Message.__init__(self, sender=sender, emit_location=emit_location, function_to_call=function_to_call, arguments=arguments) #In the future, possibly include a power on the message signal self.power = sender.power def run(self, plane, all_nodes): """Sends the message to the respective nodes which could hear it""" power = self.sender.power #Get the nodes that heard the message node_ids_that_heard_message = plane.get_neighbours_ids_at_distance(self.emit_location, distance=power) event_and_messages = {'messages': [], 'asynchronous': [], 'simulator': []} #For each one of the neighbours for node_id in node_ids_that_heard_message: new_events_and_messages = self.function_to_call(all_nodes[node_id], **self.arguments) event_and_messages['messages'] += new_events_and_messages['messages'] event_and_messages['simulator'] += new_events_and_messages['simulator'] event_and_messages['asynchronous'] += new_events_and_messages['asynchronous'] return event_and_messages
i= int(input("Por favor, introduzca un número:")) if i < 20 : print("El número",i,"se encuentra en el rango < 20") elif i >= 20 and i < 40: print("El número",i,"se encuentra en el rango de 20 a 39") elif i >= 40 and i < 60: print("El número",i,"se encuentra en el rango de 40 a 59") elif i >= 60: print("El número",i,"se encuentra en el rango >= 60")
# 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специальный символ, выполнение программы завершается. Если специальный символ введен после нескольких чисел, то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу. sum = 0 flag = True while flag: numbers = input("Enter your number/numbers and separate it with spaces: ").split() for el in numbers: try: el = int(el) sum = sum + el except ValueError: print("Non number symbol detected. Program is terminated") flag = False break print(sum)
# 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. #Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в степень с помощью оператора **. Второй — более сложная реализация без оператора **, предусматривающая использование цикла. def power_func(x, y): if isinstance(x, float) and x > 0 and isinstance(y, int) and y < 0: #easy way # return x ** y #main way with cycle res = x while y < -1: res = res * x y += 1 return 1 / res else: print("Wrong input") print(power_func(6.7,-5))
"""Closed form expression, Binet's formula. .. seealso:: https://en.wikipedia.org/wiki/Fibonacci_number """ import math SQRT_5 = math.sqrt(5) def fib(nmax, sqrt_5=SQRT_5): """Compute a fibonacci number, Fib(n).""" kvar = 1 / sqrt_5 return kvar * (((1 + sqrt_5) / 2) ** nmax - ((1 - sqrt_5) / 2) ** nmax) def fibs(nmax): """Compute fibonacci number.""" acc = [0, 1] # Fib(0), Fib(1) return acc + [int(fib(n)) for n in range(2, nmax + 1)]
smallLetters = raw_input("Unesite bilo koju rijec pritisnite enter pa vidite sto se desava: ") print("\n Vasa prva rijec: " + smallLetters.upper()) capitalLetters = raw_input("\n Unesite jos jednu rijec: ") for letter in capitalLetters: if letter != capitalLetters.lower() : print ("\n Vasa druga rijec prvi nacin: " + capitalLetters.upper() + "\n Vasa druga rijec drugi nacin: " + capitalLetters.capitalize()) break else: print ("Pogreska, pokrenite program ponovno!") break
msgbox = ''' ******************************************************* 欢迎使用20级计院13班蜡笔3小新的的恺撒密码系统 ******************************************************* ''' print(msgbox) def jiami(): wz = input("请输入需要加密的英文:") k = int(input('请输入偏移值(默认为3):') or 3) for c in wz: if "a"<=c<="z": print(chr(ord("a")+(ord(c)-ord("a")+k)%26),end="") elif "A"<=c<="Z": print(chr(ord("A")+(ord(c)-ord("A")+k)%26),end="") else: print(c,end="") print() pass def jiemi(): wz = input("请输入需要解密的英文:") k = int(input('请输入偏移值(默认为3):') or 3) for c in wz: if "a"<=c<="z": print(chr(ord("a")+(ord(c)-ord("a")-k)%26),end="") elif "A"<=c<="Z": print(chr(ord("A")+(ord(c)-ord("A")-k)%26),end="") else: print(c,end="") print() pass while True: print ("1. 加密") print ("2. 解密") print ("3. 退出") a = input("请选择:") if a == "1": jiami() elif a == "2": jiemi() elif a == "3": break else: print ("您的输入有误!")
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Dec 7, 2014 @author: Guilin ''' import re def getValue(s,key): key=key+':' list1= re.split(key, s) for i in range(len(list1)): if list1[i][-1]==',' or list1[i][-1]=='{': list2=re.split(r',|}',list1[i+1]) return list2[0] return 'Nokey' if __name__=='__main__': key='value' s='{name:Login,value: ,operation:Login,username:HE Guilin,password:hgladmin}' print getValue(s, key)
# 파이썬연습 -딕셔너리 # {Key1:Value1,Key2:Value2,...} # dic = {'name':'shin','phone':'01012348808','birth':'0312'} a= { 1: 'hi'} # a={'a':[1,2,3]} # 딕셔너리 쌍 추가하기 a[2]='b' a['name']='pey' a[3]=[1,2,3] print(a) # 딕셔너리 요소 삭제하기 del a[1] print(a) grade ={'shin': 30, 'june': 24} print(grade['shin']) dic = {'name':'shin','phone':'01012348808','birth':'0312'} print(dic['phone']) print(dic.keys()) for k in dic.keys(): print(k) # Key 리스트 만들기(keys) print(list(dic.keys())) # Value 리스트 만들기(values) print(dic.values()) # Key, Value 쌍 얻기 print(dic.items()) # Key: Value 쌍 모두 지우기(clear) print(dic.clear()) print(dic) # Key로 Value얻기(get) dic = {'name':'shin','phone':'01012348808','birth':'0312'} print(dic.get('name')) # key값으로 default값 얻기 print(dic.get('foo','bark')) # 해당 Key가 딕셔너리 안에 있는지 조사하기(in) print('name' in dic)
# 파이썬 연습 - 집합 자료형 s1 =set([1,2,3]) print(s1) s2 = set("Hello") print(s2) # set의 특징 1. 중복을 허용하지 않는다. 2. 순서가 없다 l1=list(s1) print(l1) t1=tuple(s1) print(t1) # 집합 자료형 활용하는 방법 s1= set([1,2,3,4,5,6]) s2= set([3,4,5,6,7,8]) # 1. 교집합 & print(s1&s2) print(s1.intersection(s2)) # 2. 합집합 | print(s1|s2) print(s1.union(s2)) # 3. 차집합 (-) print(s1-s2) print(s2.difference(s1)) # 집합 자료형 관련 함수 # 값 1개 추가하기(add) s1.add(77) print(s1) # 값 여러 개 추가하기(update) s1.update([99,88]) print(s1) # 특정 값 제거하기(remove) s1.remove(77) print(s1) # 자료형 숫자, 문자열, 리스트, 튜플, 딕셔너리, 집합에 대해서 알아보았다. # 자료형은 중요하고 프로그램의 근간이 되기 때문에 확실하게 해놓지 않으면 좋은 프로그램을 만들 수 없다.
# pandas : 표, 데이터를 다루기 위한 Series 클래스 # DataFrame 클래스를 제공 # 파이썬에서 사용하는 엑셀 # 시리즈 데이터 : 데이터를 1차원 배열이나 리스트의 형식으로 표현한 것을 # 시리즈 클래스 생성자에 넣어 주면 시리즈 클래스 객체 생성 import pandas as pd # 2017년 지역별 인구수 city = pd.Series([9857426, 1502227, 2475231, 3470635], index=["서울","대전","대구","부산"]) # index : 인덱스 라벨(문자, 정수, 시간, 날짜) print(type(city)) print("시리즈 데이터\n", city) print("인덱스 :",city.index) print("값 :",city.values) city.name="지역별 인구수" # city.index.name="도시" print(city)
import pandas as pd # csv 파일 읽기 # pandas 에 read_csv() 를 사용하면 DataFrame 으로 값을 가져옴 print("----- 행 인덱스가 없는 csv 파일 읽기 ------") csv_data1=pd.read_csv('sample1.csv', sep=",", dtype='unicode') # 행 인덱스는 지정하지 않으면 자동으로 부여 0~정수로 print(csv_data1) # --------------------------------------------------------- csv_data1=pd.read_csv('sample1.csv',index_col='c1') print(csv_data1) print("----- 열 인덱스가 없는 csv 파일 읽기-------") csv_data2=pd.read_csv('sample2.csv', names=['c1','c2','c3']) print(csv_data2) print('----- 구분자가 다른 csv 파일 읽기 -------') csv_data3=pd.read_csv('sample3.csv',sep='\s+') print(csv_data3) print('----- 읽을 때 행 스킵이 필요한 경우 -------') csv_data4=pd.read_csv('sample4.csv',skiprows=[0,1]) print(csv_data4) # ---------------------------------------------------- csv_data5=pd.read_csv('sample5.csv',na_values=['누락',' ']) print(csv_data5) print('--------- 웹 csv 파일 읽기 --------------') titanic_csv=pd.read_csv('http://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv') print(titanic_csv) print(titanic_csv.head()) print(titanic_csv.tail(8))
""" import tkinter as tk window=tk.Tk() def open(): pass def exit(): window.quit() menubar = tk.Menu(window) filemenu=tk.Menu(menubar) filemenu.add_command(label="열기",command=open) filemenu.add_command(label="종료",command=exit) #quit menubar.add_cascade(label="파일", menu=filemenu) window.config(menu=menubar) window.mainloop() """ from tkinter import filedialog from tkinter import * from tkinter import messagebox def open(): file=filedialog.askopenfile(parent=window, mode="r") if file !=None: lines=file.read() text.insert("1.0",lines) file.close() def save(): file = filedialog.asksaveasfile(parent=window, mode="w") if file !=None: lines=text.get("1.0",END+"-1c") file.write(lines) file.close() def info(): file = messagebox.showinfo("about, 메모장프로그램") def exit(): pass window = Tk() text=Text(window, height=30, width=80) text.pack() menu=Menu(window) window.config(menu=menu) filemenu=Menu(menu) menu.add_cascade(label="파일", menu=filemenu) filemenu.add_command(label="열기", command=open) filemenu.add_command(label="저장", command=save) filemenu.add_command(label="종료", command=exit) helpmenu=Menu(menu) menu.add_cascade(label="도움말",menu=helpmenu) helpmenu.add_command(label="도움말 정보",command=info) window.mainloop()
#!/usr/bin/env python # coding=utf-8 # import numpy as np # import matplotlib.pyplot as plt # x = np.arange(0, 5, 0.1); # y = np.sin(x) # plt.plot(x, y) # plt.show() import numpy as np import matplotlib.pyplot as mpl from TFANN import MLPR from sklearn.preprocessing import scale pth = 'yahoostock.csv' A = np.loadtxt(pth, delimiter=",", skiprows=1, usecols=(1, 4)) A = scale(A) #y is the dependent variable y = A[:, 1].reshape(-1, 1) #A contains the independent variable A = A[:, 0].reshape(-1, 1) # Stock predictor #Number of neurons in the input layer i = 1 #Number of neurons in the output layer o = 1 #Number of neurons in the hidden layers h = 32 #The list of layer sizes layers = [i, h, h, h, h, h, h, h, h, h, o] mlpr = MLPR(layers, maxIter = 1000, tol = 0.70, reg = 0.001, verbose = True) #Length of the hold-out period nDays = 5 n = len(A) #Learn the data mlpr.fit(A[0:(n-nDays)], y[0:(n-nDays)]) #Begin prediction yHat = mlpr.predict(A) #Plot the results mpl.plot(A, y, c='#b0403f') mpl.plot(A, yHat, c='#5aa9ab') mpl.show()
import re text = "name=Milk;amount=200;unit_price=0.9\nname=Bread;amount=134;" \ "unit_price=3.48\nname=Butter;amount=58;unit_price=1.65\nname=Cheese;" \ "amount=260;unit_price=4.35" products = re.split("\n", text) #print(products) sum = 0 for i in products: product = re.split(";",i) print(product) amount = product[1].split('=')[1] unit_price = product[2].split('=')[1] sum += eval(amount) * eval(unit_price) print("Total sum of all products: " + str(sum))
months = {'January': 31, 'February': 28, 'March': 31, 'April': 30, 'May': 31, 'June': 30, 'July': 31, 'August': 31, 'September': 30,'October': 31, 'November': 30, 'December': 31} #Months which have 30 days print("Months which have 30 days") for key in months.keys(): if months.get(key) == 30: print(key)
print('Enter n greater than 1\n') n = eval(input(':')) print('Enter m greater than 1\n') m = eval(input(':')) def sum_values(n, m): #sum = 0 if n == m: return n return n + sum_values(n+1,m) print(str(sum_values(n,m))) #print(str(sum_values(2,100)))
text = "name=Milk;amount=200;unit_price=0.9\n" \ "name=Bread;amount=134;unit_price=3.48\n" \ "name=Butter;amount=58;unit_price=1.65\n" \ "name=Cheese;amount=260;unit_price=4.35" products=text.split("\n") price_sum = 0 for p in products: print(p) product_info = p.split(";") amount_str = product_info[1].split("=")[1] price_str = product_info[2].split("=")[1] price_sum+=eval(amount_str)*eval(price_str) print("The total price of all products is: ") print(str(price_sum))
import turtle import time screen = turtle.Screen() s=turtle.Screen() t=turtle.Turtle() t.hideturtle() t.penup() t.setx(-20) t.sety(-120) t.pendown() t.pensize(3) t.circle(100) t.penup() t.setx(0) t.sety(0) t.setx(-50) t.setheading(150) t.pendown() t.circle(50, 60) t.penup() #Here we set coordinates for left eye t.setx(-75) t.sety(-10) t.pendown() #Here we draw left eye t.dot(10) t.penup() #Here we draw the right eyebrow t.setx(50) t.sety(0) t.setheading(150) t.pendown() t.circle(50, 60) #Here we draw the right eye t.penup() t.setx(25) t.sety(-10) t.pendown() t.dot(10) #Here we draw the nose t.penup() t.setx(-20) t.sety(-20) t.pendown() t.pensize(5) t.goto(-20,-50) #Here we draw the mouth t.penup() t.setx(-27) t.sety(-80) t.setheading(0) t.pendown() t.circle(90, 10) #Animation control for i in range(1000): turtle.stamp() turtle.update() time.sleep(3)
class Car(): def __init__(self, name, speed): self.__name = name if(speed >= 250): self.__speed = 250 else: self.__speed = speed self.__gear = 1 def get_name(self): return self.__name def set_speed(self, speed): if(speed >= 250): self.__speed = 250 else: self.__speed = speed def get_speed(self): return self.__speed def gear_up(self): if(self.__gear <= 6): self.__gear += 1 else: self.__gear = 6 def gear_down(self): if(self.__gear <= 1): self.__gear -= 1 else: self.__gear = 1 def get_gear(self): return self.__gear if __name__=="__main__": bmw = Car("BMW M5", 250) bmw.gear_up() print(bmw.get_gear())
import math class SquareManager: def __init__(self, side): self.side = side self.area = side*side self.perimeter = side * 4 self.diagonal = math.sqrt(2) * side if __name__=="__main__": sm=SquareManager(3) print(f"The area of the square with side {sm.side} = {sm.area}") print(f"The perimeter of the square with side {sm.side} = {sm.perimeter}") print(f"The diagonal of the square with side {sm.side} = {sm.diagonal}")
# Program to find product of numbers in a list: def product(x): s=1 for i in x: s = s * i return s print product([1,2,3,3,4])
class BankAccount: def __init__(self): self.balance=0 def deposit(self,amount): self.balance += amount return self.balance def withdraw(self,amount): self.balance -= amount return self.balance a=BankAccount() b=BankAccount() print a.deposit(100) print b.deposit(50) print b.withdraw(10) print a.withdraw(10)
def cumulative_product(s): p=1 l=[] for i in s: p=p*i l.append(p) return l print cumulative_product([4,3,2,1])
import re def make_slug(): a=re.findall(r'\w+',s) print '-'.join(a) s=raw_input('Enter the string:\n') make_slug()
def unique(x): y=[] for i in x: if i.lower() not in y: y.append(i) return y print unique(["python", "java", "Python", "Java"])
#Implement a function product to multiply 2 numbers recursively using + and - operators only. def product(x,y): if x<0 and y<0: if y==0: return 0 else: return abs(x)+product(abs(x),abs(y)-1) elif x<0 and y>0: if y==0: return 0 else: return x+product(x,abs(y)-1) elif x>0 and y<0: if y==0: return 0 else: return -x+product(-x,abs(y)-1) else: if y==0: return 0 else: return x+product(x,y-1) print product(45,-20)
# Comment peut-on permettre à l'utilisateur de sortir de la boucle # en modifiant les lignes de code dans la boucle while ? continuer = "o" while continuer == "o": print("On continue !") test = input("Voulez-vous continuer ? o/n ") if (test == "o" or test == "Oui" or test == "OUI"): break else: continue
#!/usr/bin/env python3 # # Use extended Euclid's algorithm to solve Diophantine equations efficiently. # # Given three numbers a>0, b>0, and c, the algorithm should return some x and y such that # # ax+by=c #============================================================================================================ def gcd(a, b): assert a >= 0 and b >= 0 and a + b > 0 while a > 0 and b > 0: if a >= b: a = a % b else: b = b % a return max(a, b) def extended_gcd(a, b): assert a >= b and b >= 0 and a + b > 0 if b == 0: # The deepest level - the algorithm has finished. # The current a is the gcd. (1, 0) are the starting # values for x and y respectively. d, x, y = a, 1, 0 else: # Run another iteration - the new a is the old b, # the new b is the old remainder (i.e. a % b). # Because this is a recursive function call, we # continue to call extended_gcd() from within until # b == 0 (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) def diophantine(a, b, c): assert c % gcd(a, b) == 0 d, x, y = extended_gcd(a, b) q = c/d x *= q y *= q # return (x, y) such that a * x + b * y = c # Solve a * x0 + b * y0 = d # Where d = gcd(a,b) # (x, y, d) = extended_euclid(a, b) # print((x, y, d)) return (x, y) def main(): # (x, y) = diophantine(391, 299, -69) (x, y) = diophantine(10, 6, 14) print(x, y) if __name__ == '__main__': main()
#!/usr/bin/env python3 def square(x): return x * x def mod_exp(x, n, mod): if n == 0: return 1 if (n % 2 == 0): return square(mod_exp(x, n / 2, mod)) % mod else: return (x * mod_exp(x, n - 1, mod)) % mod def main(): print("Raise an integer to an exponent.") a = int(input("Enter a: ")) e = int(input("Enter exponent: ")) mod = int(input("Enter modulus: ")) ans = mod_exp(a, e, mod) print("{} ^ {} ≡ {} (mod {}).".format(a, e, ans, mod)) if __name__ == '__main__': main()
# print a pyramid like this # level = 5 # * # * * # * * * # * * * * # * * * * * def print_pyramid(levels): # notice the pattern itself has SPACES # cells per row = number of pattern in last row # 1 -> 3 -> 5 -> 7 ->....which is an A.P, nth term=a+(n-1)*d cells_per_row = 1 + (levels - 1) * 2 for level in range(1, levels+1): # form pattern first length_of_pattern = 1 + (level - 1) * 1 pattern = '' for i in range(length_of_pattern): pattern += "*_" pattern = pattern.rstrip('_') l = len(pattern) spaces_per_row = cells_per_row - l # start to print print('_' * (spaces_per_row // 2), end='') print(pattern, end='') print('_' * (spaces_per_row // 2), end='') print() print_pyramid(5)
# --- Directions # Given a string, return the character that is most # commonly used in the string. # --- Examples # maxChar("abcccccccd") === "c" # maxChar("apple 1231111") === "1" import pytest def max_char(s): max_count, max_char = 0, None char_counter = {} for c in s: if c in char_counter: char_counter[c] += 1 else: char_counter[c] = 1 if char_counter[c] > max_count: max_count, max_char = char_counter[c], c return max_char def test_max_char_letters(): assert max_char("abcccccccd") == "c" def test_max_char_numbers(): assert max_char("apple 1231111") == "1"
class sintaxys_try: #diferentes casos para aplicar el TRY def suma(self, num1,num2): try: if num1<0: raise Exception ('quiero este if') except: return 'No aplica el if' else: return num1+num2 def multipli(self, num1, num2): try: if not type(num1) is int: raise TypeError('solo integers') #levantame este mensaje except TypeError: return ('no puedo hacer la opercion') else: return num2*num1 def divid(self,num2,num1): try: #este es el mas sencillito return num2/num1 except ZeroDivisionError: return'Mensaje de error' except TypeError: return 'Tipea otro error' #else: # pass finally:# cuando hay un finally se ejecuta siempre lo que él contenga print('Pase lo que pase este se ejecuta') total = sintaxys_try() #creo mi objeto con el cual hago traigo los metodos que quiero utilizar #print(total.divid(4,0)) #print(total.multipli(2,'a')) print(total.suma(-1,2))
"""Program greets user and describes what's the purpose of the program Program asks user to enter number of kilometers. User enters the amount of kilometers. Program converts these kilometers into miles and prints them. Program asks user if they'd want to do another conversion. If yes, repeat the above process (except the greeting). If not, program says goodbye and stops. """ print "Hallo! Ich rechne fuer dich gerne Kilometer in Meilen um." while True: print "Bitte gib die Anzahl der Kilometer die ich fuer dich umrechnen soll, hier ein:" km = raw_input("Kilometer: ") try: km = float (km.replace(",", ".")) miles = km * 0.621371 print "{0} Kilometer sind {1} Meilen.".format(km, miles) except Exception as e: print "Please enter a number, not text!" choice = raw_input("Soll ich noch eine weitere Distanz fuer dich berechnen? j/n: ") if choice.lower() != "j" and choice.lower() != "ja": print "Schoen, dass du da warst und ich helfen konnte." break
# https://www.youtube.com/watch?v=J4wbwvkY4lM import sys from Tkinter import * import time def tick(): time_string = time.strftime("%H:%M:%S") clock.config(text=time_string) clock.after(200,tick) global time1 global time2 global time3 if time_string == time1: time.sleep(0.99) print("wake up") if time_string == time2: time.sleep(0.99) print("time for lunch") if time_string == time3: time.sleep(0.99) print("time for bed") #popup window for clock root = Tk() #putting multiple frames on one blank window, root topFrame = Frame(root) topFrame.pack() bottomFrame = Frame(root) bottomFrame.pack(side=BOTTOM) clock = Label(topFrame, font = ("times", 200, "bold"), bg= "white") alarms = Label(bottomFrame, text = "Hello", font = ("times", 100,)) clock.pack() alarms.pack() #bg = background color #int = size of clock #These are user inputted values time1 = "18:54:10" time2 = "18:54:15" time3 = "18:54:20" tick() root.mainloop() #TEST2
''' def IsPrime(num): if num < 2: return False divisor = 2 while divisor < num: if num % divisor == 0: return False else: divisor = divisor + 1 return True ''' import math def IsPrime(num): if num < 2: return False divisor = 2 temp = int(math.sqrt(num)) + 1 while divisor < temp: if num % divisor == 0: return False else: divisor = divisor + 1 return True ''' print(IsPrime(5)) for n in range (3,101): if IsPrime(n): print(n, "is prime") else: print(n, "is not prime") ''' def primesInRange(a,b): l = [] for n in range(a,b): if IsPrime(n): l.append(n) return l ''' print(primesInRange(1,10)) print(primesInRange(1,103)) print(primesInRange(-100,100)) ''' def ListPrime(n): l = [] x = 2 while len(l) < n: if IsPrime(x): l.append(x) x = x + 1 return l """ print(ListPrime(10)) print(IsPrime(7917)) """
import operator def clean(s): word = "" for letter in s: if letter.isalpha(): word = word+letter #print(word) return word.lower() input_file = open("a-study-in-scarlet.txt", "r") count_dict = {} for line in input_file: #print(line, end="") split_line = line.split(" ") #print(split_line) for word in split_line: word = clean(word) if not word: continue if word in count_dict: count_dict[word] = count_dict[word] + 1 else: count_dict[word] = 1 #print(count_dict) #print(count_dict["spending"]) sorted_count = sorted(count_dict.items(), key=operator.itemgetter(1)) sorted_count.reverse() #print(sorted_count[:20]) output_file = open("top-words.csv", "w") for word, count in sorted_count: output_file.write(word + "," + str(count) + "\n")
zoo = ("lions", "tigers", "bears", "sheep", "zebra", "donkey", "monkey", "snake", "turkey", "gerbil") print(zoo) print(zoo.index("tigers")) animal_to_find = "gerbil" if animal_to_find in zoo: print("Animal found") animal_to_find = "hampster" if animal_to_find in zoo: print("Animal found") zoo1 = ("lions", "tigers", "bears", "sheep") (first_child, second_child, third_child, fourth_child) = zoo1 print(first_child) # Output is "lions" print(second_child) # Output is "tigers" print(third_child) # Output is "bears" print(fourth_child) # Output is "sheep" zoo2 = list(zoo1) print(zoo1) zoo2.extend(["hippo", "giraffe", "cricket"]) print("new list", zoo2) newTup = tuple(zoo2) print("new Tuple", newTup)
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): l1 = list(tuple_a) + [0, 0] l2 = list(tuple_b) + [0, 0] l3 = [l1[0] + l2[0]] + [l1[1] + l2[1]] return tuple(l3)
#!/usr/bin/python3 def islower(c): val = ord(c) if val >= 97 and val <= 122: return (True) else: return (False)
#!/usr/bin/python3 def search_replace(my_list, search, replace): new_matrix = my_list[:] for i in range(len(new_matrix)): if search == new_matrix[i]: new_matrix[i] = replace return new_matrix
#!/usr/bin/python3 def multiply_by_2(a_dictionary): new_dict = dict(a_dictionary) liste = sorted(a_dictionary.keys()) for item in liste: new_dict[item] = a_dictionary[item] * 2 return new_dict
#!/usr/bin/python3 """Class that inherits from list""" class MyList(list): """Class MyList""" # method def print_sorted(self): """method print list in ascending sort""" print(sorted(self))
from random import randint import time def selection_sort(array): start = 0 for i in range(len(array)): min_index = start for j in range(start, len(array)): if array[j] < array[min_index]: min_index = j array[min_index], array[i] = array[i], array[min_index] start += 1 return array """ ==================================== Test sort ==================================== """ array = [randint(1,100) for i in range(10)] sorted_array = selection_sort(array) print('Sort is working correctly:', sorted_array == sorted(array)) ss_time = 0 for i in range(20): array = [randint(0, 100) for j in range(1000)] start = time.time() selection_sorted = selection_sort(array) end = time.time() ss_time += end-start print('Mean execution time for quick sort: ', ss_time/20)
def exp_sum(n,n): if n == 1: return 1 if start > n: return exp_sum(n,n) sum = 0 for i in xrange(1,start): sum += exp_sum(n-i, i) print sum return sum exp_sum(3,1)
#Required Code # 1. import servo_angles #Imports Module # 2. Servo = servo_angles.servo #Call the class variable anything you want but adapt the bellow building blocks #'Do the Action' Code #Bellow assumes you called the class variable (Required 2.) to Servo. If you did not: Adapt the bollow where says Servo.the_feature. # 1. Servo.angle(angle, pin number) #Sets the servo angle to the first positional argument(angle), for the pin number in the seccond positional argument (pin number) ** See Bottom # 2. A_Variable = (Servo.convert_pwm(90)) #(Servo.convert_pwm(angle)) returns the required Pwm value to reach the required variable. # 3. Servo.pwm(pwm_value, pin number) #Sets the servo in the given pin number to the given pwm value. import servo_angles Servo = servo_angles.servo() Servo.angle(180, 2) import utime pin = 2 while True: #x = 0 # Set Variable X #Servo.angle(x, 2) # Set Servo Angle to 0 utime.sleep(0.5) #Wait for it to move (If on 180degrees already) for x in range(180): #Loop and increment x by 1 Servo.angle(x, pin) # Set servo angle to X utime.sleep(0.05)# Sleep 0,05s between movements
#匿名函数的应用 li=[[1,2],[3,33],[3,4553,6]] li.sort(key=lambda x: x[0]) print(li) #过滤数据 # filter() # # # 处理数据 # map() # # #识别数据类型,执行 # eval() #执行python代码 data = """ def login(): print('1111111111')""" exec(data) #聚合函数 title=['a','b','c'] value=[1,2,3,4] data=zip(title,value) print(dict(data))
# _*_coding:utf-8_*_ from cal_time import cal_time @cal_time def linear_search(li, val): for index, v in enumerate(li): if v == val: return index return None @cal_time def binary_search(li, val): left = 0 right = len(li) - 1 while left <= right: mid = (left + right) // 2 if li[mid] == val: return mid elif li[mid] > val: right = mid - 1 else: # li[val] < val left = mid + 1 return None if __name__ == '__main__': li = list(range(100000000)) print(linear_search(li, 38900000)) print(binary_search(li, 38900000))
# Implementation of classic arcade game Pong import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGHT = PAD_HEIGHT / 2 LEFT = False RIGHT = True PADDLE_VEL = 4 ball_pos = [0,0] ball_vel = [0,0] paddle1_pos = HEIGHT/2 - HALF_PAD_HEIGHT paddle2_pos = HEIGHT/2 - HALF_PAD_HEIGHT paddle1_vel = 0 paddle2_vel = 0 score1 = 0 score2 = 0 # initialize ball_pos and ball_vel for new bal in middle of table # if direction is RIGHT, the ball's velocity is upper right, else upper left def spawn_ball(direction): global ball_pos, ball_vel # these are vectors stored as lists ball_pos = [WIDTH/2, HEIGHT/2] ball_vel[0] = random.randrange(120, 240) / 60 ball_vel[1] = -random.randrange(60, 180) / 60 if not direction: ball_vel[0] = -ball_vel[0] # define event handlers def new_game(): global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers global score1, score2 # these are ints score1 = 0 score2 = 0 leftright = [LEFT,RIGHT] random.shuffle(leftright) spawn_ball(leftright[0]) def collision(direction): if direction: #ball has collided with left gutter if (ball_pos[1] + BALL_RADIUS >= paddle1_pos) and (ball_pos[1] - BALL_RADIUS <= paddle1_pos + PAD_HEIGHT): ball_vel[0] = - 1.1 * ball_vel[0] ball_vel[1] = 1.1 * ball_vel[1] return 0; else: spawn_ball(direction) return 1 else: if (ball_pos[1] + BALL_RADIUS >= paddle2_pos) and (ball_pos[1] - BALL_RADIUS <= paddle2_pos + PAD_HEIGHT): ball_vel[0] = -1.1 * ball_vel[0] ball_vel[1] = 1.1 * ball_vel[1] return 0; else: spawn_ball(direction) return 1 def button_handler(): new_game() def draw(canvas): global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel # draw mid line and gutters canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White") canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White") canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White") # update ball ball_pos[0] += ball_vel[0] ball_pos[1] += ball_vel[1] #Collision detection in vertical direction if ball_pos[1] <= BALL_RADIUS - 1: ball_vel[1] = - ball_vel[1] ball_pos[1] = BALL_RADIUS -1 if ball_pos[1] >= HEIGHT - BALL_RADIUS + 1: ball_vel[1] = - ball_vel[1] ball_pos[1] = HEIGHT - BALL_RADIUS + 1 #Collision detection with gutters in horizental direction if ball_pos[0] <= BALL_RADIUS + PAD_WIDTH +1: tmp = collision(RIGHT) score2 += tmp if ball_pos[0] >= WIDTH - PAD_WIDTH - BALL_RADIUS + 1: tmp = collision(LEFT) score1 += tmp # draw ball canvas.draw_circle(ball_pos, BALL_RADIUS-1, 1, 'White', 'White') # update paddle's vertical position, keep paddle on the screen paddle1_pos += paddle1_vel paddle2_pos += paddle2_vel if paddle1_pos <= 1: # 1 (not 0) to account fot line paddle1_pos = 1 elif paddle1_pos >= HEIGHT - (PAD_HEIGHT+1): paddle1_pos = HEIGHT - (PAD_HEIGHT+1) if paddle2_pos <= 1: # 1 (not 0) to account fot line paddle2_pos = 1 elif paddle2_pos >= HEIGHT - (PAD_HEIGHT+1): paddle2_pos = HEIGHT - (PAD_HEIGHT+1) # draw paddles canvas.draw_polygon([[1, paddle1_pos],[PAD_WIDTH-1, paddle1_pos], [PAD_WIDTH-1, paddle1_pos+PAD_HEIGHT], [1, paddle1_pos+PAD_HEIGHT]], 1, 'White', 'White') canvas.draw_polygon([[WIDTH-1, paddle2_pos],[WIDTH-PAD_WIDTH+1, paddle2_pos], [WIDTH-PAD_WIDTH+1, paddle2_pos+PAD_HEIGHT], [WIDTH-1, paddle2_pos+PAD_HEIGHT]], 1, 'White', 'White') # draw scores scoredraw = str(score1)+' '+str(score2) canvas.draw_text(scoredraw, (WIDTH/2-10*len(scoredraw), 120), 60, 'Green') def keydown(key): global paddle1_vel, paddle2_vel if (key == simplegui.KEY_MAP['s']): paddle1_vel = PADDLE_VEL elif (key == simplegui.KEY_MAP['w']): paddle1_vel = -PADDLE_VEL if (key == simplegui.KEY_MAP['down']): paddle2_vel = PADDLE_VEL elif (key == simplegui.KEY_MAP['up']): paddle2_vel = -PADDLE_VEL def keyup(key): global paddle1_vel, paddle2_vel if (key == simplegui.KEY_MAP['s']) or (key == simplegui.KEY_MAP['w']): paddle1_vel = 0 if (key == simplegui.KEY_MAP['up']) or (key == simplegui.KEY_MAP['down']): paddle2_vel = 0 # create frame frame = simplegui.create_frame("Pong", WIDTH, HEIGHT) frame.set_draw_handler(draw) frame.set_keydown_handler(keydown) frame.set_keyup_handler(keyup) button2 = frame.add_button('Reset', button_handler, 150) # start frame new_game() frame.start()
import cv2 import numpy as np img = cv2.imread('book.PNG') #Theresholding using THRESH_BINARY on the RGB image _, RGB_binary_threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY) #Gray Scaling the RGB Image grayscaled = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Theresholding using THRESH_BINARY on the Gray Scaled image _, grayscale_binary_threshold = cv2.threshold(grayscaled, 10, 255, cv2.THRESH_BINARY) #Theresholding using ADAPTIVE_THRESH_GAUSSIAN_C on the Gray Scaled image grayscaale_adaptive_binary_threshold = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) #OUTPUTS: #Showing the orignal image cv2.imshow('original',img) #Showing the RGB_binary_threshold image cv2.imshow('RGB_binary_threshold', RGB_binary_threshold) #Showing the grayscale_binary_threshold image cv2.imshow('grayscale_binary_threshold', grayscale_binary_threshold) #Showing the grayscaale_adaptive_binary_threshold image cv2.imshow('grayscaale_adaptive_binary_threshold', grayscaale_adaptive_binary_threshold) #Setting the wait key to "ESC" cv2.waitKey(0) cv2.destroyAllWindows() #Press escape to exit the program
import numpy as np import sys """This script implements a two-class logistic regression model. """ class logistic_regression(object): def __init__(self, learning_rate, max_iter): self.learning_rate = learning_rate self.max_iter = max_iter def fit_GD(self, X, y): """Train perceptron model on data (X,y) with GD. Args: X: An array of shape [n_samples, n_features]. y: An array of shape [n_samples,]. Only contains 1 or -1. Returns: self: Returns an instance of self. """ n_samples, n_features = X.shape ### YOUR CODE HERE self.assign_weights(np.zeros(n_features)) for i in range(self.max_iter): w_add = np.zeros(n_features) for j in range(n_samples): w_add += self.learning_rate * (- self._gradient(X[j],y[j])) w_add = w_add / n_samples self.W +=w_add ### END YOUR CODE return self def fit_BGD(self, X, y, batch_size): """Train perceptron model on data (X,y) with BGD. Args: X: An array of shape [n_samples, n_features]. y: An array of shape [n_samples,]. Only contains 1 or -1. batch_size: An integer. Returns: self: Returns an instance of self. """ ### YOUR CODE HERE n_samples, n_features = X.shape self.assign_weights(np.zeros(n_features)) for i in range(self.max_iter): w_add = np.zeros(n_features) if batch_size<=n_samples: mini_batch = np.random.choice(n_samples, batch_size) else: mini_batch = np.linspace(0,n_samples,n_samples-1) for j in mini_batch: w_add += self.learning_rate * (- self._gradient(X[j],y[j])) w_add = w_add / n_samples self.W +=w_add ### END YOUR CODE return self def fit_SGD(self, X, y): """Train perceptron model on data (X,y) with SGD. Args: X: An array of shape [n_samples, n_features]. y: An array of shape [n_samples,]. Only contains 1 or -1. Returns: self: Returns an instance of self. """ ### YOUR CODE HERE n_samples, n_features = X.shape self.assign_weights(np.zeros(n_features)) for i in range(self.max_iter): j = np.random.randint(n_samples) w_add = self.learning_rate * (- self._gradient(X[j],y[j])) self.W +=w_add ### END YOUR CODE return self def _gradient(self, _x, _y): """Compute the gradient of cross-entropy with respect to self.W for one training sample (_x, _y). This function is used in fit_*. Args: _x: An array of shape [n_features,]. _y: An integer. 1 or -1. Returns: _g: An array of shape [n_features,]. The gradient of cross-entropy with respect to self.W. """ ### YOUR CODE HERE c_exp = np.exp(-_y*np.dot(self.W,_x)) _g = c_exp/(1+c_exp)*(-_y)*_x return _g ### END YOUR CODE def get_params(self): """Get parameters for this perceptron model. Returns: W: An array of shape [n_features,]. """ if self.W is None: print("Run fit first!") sys.exit(-1) return self.W def predict_proba(self, X): """Predict class probabilities for samples in X. Args: X: An array of shape [n_samples, n_features]. Returns: preds_proba: An array of shape [n_samples, 2]. Only contains floats between [0,1]. """ ### YOUR CODE HERE n_samples = X.shape[0] preds_proba = np.zeros((n_samples,2)) _s = np.matmul(X, self.W) # array operation _logit = 1 / (1 + np.exp(-_s)) preds_proba[:,0] = _logit preds_proba[:, 1] = 1-_logit return preds_proba ### END YOUR CODE def predict(self, X): """Predict class labels for samples in X. Args: X: An array of shape [n_samples, n_features]. Returns: preds: An array of shape [n_samples,]. Only contains 1 or -1. """ ### YOUR CODE HERE n_samples = X.shape[0] preds = np.ones(n_samples) _s = np.matmul(X,self.W) # array operation _logit = 1/(1+np.exp(-_s)) preds[_logit<0.5] = -1 ### END YOUR CODE return preds def score(self, X, y): """Returns the mean accuracy on the given test data and labels. Args: X: An array of shape [n_samples, n_features]. y: An array of shape [n_samples,]. Only contains 1 or -1. Returns: score: An float. Mean accuracy of self.predict(X) wrt. y. """ ### YOUR CODE HERE preds = self.predict(X) score = np.sum(preds ==y)/y.shape[0] ### END YOUR CODE return score def assign_weights(self, weights): self.W = weights return self
from sklearn.model_selection import train_test_split import data import greedySubset as gs import project as pr import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd def run(F): # Load encoded data X, y = data.load() # Split data into Test-Train Sets X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.6, random_state=42 ) # Get subset of features S, theta = gs.run(F, X_train.values, y_train) # Print S, theta print(S) print(theta) # Create a dataframe of features and weights df = pd.DataFrame({ 'feature' : S, 'weight' : theta, 'weightabs': np.abs(theta) }) # Plot Greedy Subset plt.figure() # Filter only those features with weights more than 1/2 the mean weight m = (np.mean(df['weightabs'].values)/2) df = df[df['weightabs'] > m] # Sort features by weights result = df.groupby(["feature"])['weightabs'].aggregate(np.median).reset_index().sort_values('weightabs') # Plot features and weights sns.barplot(x='feature', y="weight", data=df, order=result['feature']) plt.xlabel('Feature') plt.ylabel('Weight') plt.title('Greedy Subset') plt.show() run(107)
""" playgame.py Contains the Connect 3 game playing application. This file forms part of the assessment for CP2410 Assignment 2 ************** ENTER YOUR NAME HERE **************************** """ from connect3board import Connect3Board from gametree import GameTree def main(): print('Welcome to Connect 3 by Luke Maclean') mode = get_mode() while mode != 'Q': if mode == 'A': run_two_player_mode() elif mode == 'B': run_ai_mode() mode = get_mode() def run_two_player_mode(): game_not_done = True board = Connect3Board(3, 3) while game_not_done: print(board) whose_turn = board.get_whose_turn() token_choice = int(input("Choose a row to place a {}: ".format(whose_turn))) board.add_token(token_choice) if board.get_winner() is not None: winner = board.get_winner() game_not_done = False print(board) print("Player {} won".format(winner)) # for you to complete... pass def run_ai_mode(): # for you to complete... pass def get_mode(): mode = input("A. Two-player mode\nB. Play against AI\nQ. Quit\n>>> ") while mode[0].upper() not in 'ABQ': mode = input("A. Two-player mode\nB. Play against AI\nQ. Quit\n>>> ") return mode[0].upper() def get_int(prompt): result = 0 finished = False while not finished: try: result = int(input(prompt)) finished = True except ValueError: print("Please enter a valid integer.") return result if __name__ == '__main__': main()
import json from time import sleep import pyperclip with open('./dictionary.json', 'r+') as dictfile: dictionary = json.load(dictfile) print("What do you want to convert to Qorraxish? Note that this program does not currently support plural words.\nYou can convert a Qorraxish word to a plural by adding the suffix '-M'.") english = input() result = '' for w in english.split(): if w.lower() in dictionary.keys(): result += dictionary[w.lower()] + ' ' else: result += f'[{w.lower()}] ' print(result) try: pyperclip.copy(result) print('Result copied to clipboard') except: print('Tried to copy the result to your clipboard, but something went wrong.') sleep(60)
import numpy as np import nnfs from nnfs.datasets import spiral_data import matplotlib.pyplot as plt nnfs.init() X, y = spiral_data(100,3) class Layer_Dense: def __init__(self, n_inputs, n_neurons): self.weights = 0.1*np.random.randn(n_inputs, n_neurons) #Random Gauss ian Distributions of numbers self.biases = np.zeros((1,n_neurons)) def forward(self, inputs): self.output = np.dot(inputs, self.weights) + self.biases class Activation_ReLU: def forward(self, inputs): self.output = np.maximum(0,inputs) layer1 = Layer_Dense(n_inputs = 2, n_neurons = 5) # Inital inputs are number of features activation1 = Activation_ReLU() layer1.forward(X) activation1.forward(layer1.output) print(activation1.output)
# Jiayao Zhou # 2021/5/21 # This is the code applies our Unary Linear Regression import pandas as pd import numpy as np import pylab def plot_data(data, b, m,datax,datay): x = datax y = datay y_predict = m*x + b print(y_predict) data['Date']=pd.to_datetime(data['Date']) pylab.plot(data['Date'], y_predict, '-b') pylab.plot(data['Date'], data["Close"], '-r') pylab.show() def linear_regression(data, learning_rate, times,datax,datay): b = 0.0 m = 0.0 #The datax and datay means two values from the data x = datax y = datay n = float(len(data)) for i in range(times): db = -(1/n)*(y - m*x-b) db = np.sum(db, axis=0) dw = -(1/n)*x*(y - m*x - b) dw = np.sum(dw) sb = b - (learning_rate*db) sw = m - (learning_rate*dw) b = sb m = sw if i % 100 == 0: j = (np.sum((y - m*x - b)**2))/n #the return values b and m means the line y=mx+b return [b, m] if __name__ == '__main__': data = pd.read_csv("AMC.csv") x=data["Open"] y=data['Close'] learning_rate = 0.001 times = 1000 b, m = linear_regression(data, learning_rate, times,x,y) plot_data(data, b, m,x,y)
print('Print Character Pertama') def digitAwal(x, y): dasar = x eksponen = y pangkat = (x ** y) strPangkat = str(pangkat) #menguhbah output "pangkat" menjadi sring print('Character Pertamanya Adalah :', strPangkat[0]) x = int(input('Masukkan Angka : ')) y = int(input('Masukkan Angka : ')) digitAwal(x, y) #masih bingung untuk membuat bukan user input print('==========================================================') print('Print Character Terakhir') def digitAkhir(m, n): dasar = m eksponen = n pangkat = (m ** n) strPangkat = str(pangkat) #menguhbah output "pangkat" menjadi sring print('Character Akhirnya Adalah :', strPangkat[-1]) m = int(input('Masukkan Angka : ')) n = int(input('Masukkan Angka : ')) digitAkhir(m, n)
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * from random import choice from string import ascii_uppercase class Welcome(Controller): def __init__(self, action): super(Welcome, self).__init__(action) """ This is an example of loading a model. Every controller has access to the load_model method. self.load_model('WelcomeModel') """ """ This is an example of a controller method that will load a view for the client """ def index(self): """ A loaded model is accessible through the models attribute self.models['WelcomeModel'].get_all_users() """ if 'count' in session: session['count'] += 1 else: session['count'] = 0 return self.load_view('index.html', count = session['count']) def generate(self): num = ''.join(choice(ascii_uppercase) for i in range(14)) session['num'] = num return redirect('/')
import nltk paragraph = """If you observe some people then you will notice that human life is a series of tension and problems. Also, they have a variety of concerns relating to their life. Sport is something that makes us free from these troubles, concerns, and tensions. Moreover, they are an essential part of life who believe in life are able to face the problems. They help in the proper operation of various organs of the body. Furthermore, they refresh our mind and the body feel re-energized. They also make muscle strength and keep them in good shape. In schools and colleges, they consider sports as an important part of education. Also, they organize sports competitions of different kinds. In schools, they organize annual sports events. And on a daily basis, they have a specific period for sports and games. In this period teachers teach them the ways to play different sports and games. These sports and games teach students new things and they have a bond with them. In addition, sports help them develop self-confidence and courage. Also, they become active and swift. And success fills them with motivation and eagerness. We all knew the importance of games in the world. Consequently, now the Olympics (one of the biggest sports events) held in different countries. They held every fourth year. Moreover, the Asian Games is the biggest sports event on the Asian continent. Over, the year the interest of people in sports have increased many folds.""" #Cleaning the text import re from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer wordnet = WordNetLemmatizer() sentences = nltk.sent_tokenize(paragraph) corpus = [] for i in range(len(sentences)): review = re.sub('[^a-zA-Z]', ' ',sentences[i]) review = review.lower() review = review.split() review = [wordnet.lemmatize(word) for word in review if not word in set(stopwords.words('english'))] review = ' '.join(review) corpus.append(review) print(corpus) # TF-IDF model from sklearn.feature_extraction.text import TfidfVectorizer cv = TfidfVectorizer() x = cv.fit_transform(corpus).toarray() print(x.shape)
diccionario={ "Nombre":"luis", "Apellido":"Gutierrez", "Edad":16 } for x in diccionario: print (diccionario[x])
from random import randint #Create By: ClausRB github.com/loget007 print("Bienvenido al juego Piedra, Papel o Tijera") opciones= ['piedra', 'papel', 'tijera'] computadora = opciones[randint(0,2)] jugador= input("Selecciona una opcion: 'Piedra', 'Papel' ó 'Tijera'\n-----> ").lower() if jugador == computadora: print("Rayos, ambos han empatado\n") #Create By: ClausRB github.com/loget007 elif jugador == 'piedra': if computadora == 'papel': print("Perdiste tont@") else: print("Haz ganadoooooo!!!!!!") #Create By: ClausRB github.com/loget007 elif jugador == 'papel': if computadora == 'tijera': print("Perdiste tont@") else: print("Haz ganadoooooo!!!!!!") #Create By: ClausRB github.com/loget007 elif jugador == 'tijera': if computadora == 'piedra': print("Perdiste tont@") else: print("Haz ganadoooooo!!!!!!") else: print("Esta opcion es invalida, seguro agregaste un caracter que no es -.-!!!!\n")
# _*_ coding: utf-8 _*_ # Find all emails in the file "datos.txt" # Cannoical mode # matches = re.findall(pattern, text) # Optimized mode # prog = re.compile(pattern) # matches = prog.findall(pattern) # Find all matches (non-overlapping) # findall(text) # Find all one-by-one # finditer(text) # Best simple-way # for match in re.finditer(pattern, text): # print match.group(0) import re f = open("datos.txt", "r") text = f.read() f.close() pattern = "[\w\.-]+@[\w]{3,}\.([\w\.]{2,})+" for match in re.finditer(pattern, text): print match.group(0)
a = [1,2,3,6,2,5,7,9,2,3,7,9,10,25,89] b = [1,2,6,8,3,1,7,0,00,335,247,21,681,146] a = set (a) b = set (b) print(a) print(b) temp=[] for numbers in a: if numbers in b: temp.append(numbers) print(temp)
#https://www.hackerrank.com/challenges/diagonal-difference/problem def diagonalDifference(arr): primary_diagonal = 0 for x in range(len(arr)): primary_diagonal += arr[x][x] secondary_diagonal = 0 reverse_index = len(arr)-1 for x in arr: secondary_diagonal += x[reverse_index] reverse_index -= 1 return abs(primary_diagonal-secondary_diagonal) if __name__ == '__main__': n = int(input()) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(arr) print (result)
words = str(input('Enter word')) first = words[0] pyg = [] for x in range(1,len(words)): pyg.append(words[x]) pyg.insert(len(words),first) pyg.append('ay') words = ''.join(pyg) print (words)
# https://www.algoexpert.io/questions/Reverse%20Linked%20List def reverseLinkedList(head): p1 = None p2 = head while p2 is not None: p3 = p2.next p2.next = p1 p1 = p2 p2 = p3 return p1
def ActualChecker(s,n,lastHalf): firstHalf = s[:n] lastHalfReverse = lastHalf[::-1] b = False if firstHalf == lastHalfReverse: return True else: return False def palChecker(s): #preprocessing begins filteredText = [] for x in s: x = x.lower() if x not in "!@#$%^&*(){}|:<>? []\',./": if x not in " ": filteredText.append(x) s = "".join(filteredText) #preprocessing end n = len(filteredText)/2 n = int(n) if len(filteredText)%2==0: lastHalf = s[n:] return(ActualChecker(s,n,lastHalf)) else: lastHalf = s[n+1:] return(ActualChecker(s,n,lastHalf)) s=input("Enter Sentence to check if palindrome or not:\n") print(palChecker(s))
# https://www.hackerrank.com/challenges/nested-list/problem n = int(input()) storage = {} for x in range(n): name = input() mark = str(float(input())) if mark in storage: names = storage[mark] names.append(name) storage[mark] = names else: names = [] names.append(name) storage[mark] = names marks_list = list(map(float,storage.keys())) marks_list.sort() second_lowest = marks_list[1] names = storage[str(second_lowest)] names.sort() for name in names: print(name)
def is_member(): lis = [] n = int(input('Enter Number of elements in list:')) for x in range(n): lis.append(input('Enter Members of list:')) print('Members of the club:') print(lis) if input('Enter Something to check if in club or not:\n') in lis: return ('True') else: return ('False') print(is_member())
# https://www.algoexpert.io/questions/Nth%20Fibonacci def getNthFib(n,counter=0, n1=0, n2=1): response = n1 if n<counter: return n1 counter+=1 nth_fib = n1+n2 n1 = n2 n2 = nth_fib if n>counter: response = getNthFib(n,counter, n1, n2) return response
"""Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} and use it to translate your Christmas cards from English into Swedish. That is, write a function translate() that takes a list of English words and returns a list of Swedish words.""" pyDic = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"} lis = [] n = int(input('Enter Number of elements in list:')) for x in range(n): lis.append(input('Enter Values:'))
""" "99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows: 99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall. The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero. Your task here is write a Python program capable of generating all the verses of the song. """ x = 99 while x!=0: print('{} bottles of beer on the wall, {} bottles of beer.'.format(x,x)) x-=1 print('Take one down, pass it around, {} bottles of beer on the wall.\n'.format(x))
https://www.algoexpert.io/questions/Suffix%20Trie%20Construction # Do not edit the class below except for the # populateSuffixTrieFrom and contains methods. # Feel free to add new properties and methods # to the class. class SuffixTrie: def __init__(self, string): self.root = {} self.endSymbol = "*" self.populateSuffixTrieFrom(string) def insert_substring(self,i, string): node = self.root for letter in string[i:]: if letter not in node: node[letter] = {} node = node[letter] node[self.endSymbol] = True def populateSuffixTrieFrom(self, string): for i in range(len(string)): self.insert_substring(i,string) print(self.root) def contains(self, string): node = self.root for letter in string: if letter not in node: return False else: pass node = node[letter] return self.endSymbol in node
#!/bin/python3 # https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): sock_count = 0 ar.sort() while len(ar)>0: if ar[0] in ar[1:]: if ar[0] == ar[1]: sock_count += 1 del ar[0:2] else: del ar[0] return sock_count if __name__ == '__main__': n = int(input()) ar = list(map(int, input().rstrip().split())) result = sockMerchant(n, ar) print(result)
listPal = input("Enter word: ") if listPal == listPal[::-1]: print("String is palindrome") else: print("String is not palindrome")
"""Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, capitalization, and spacing are usually ignored.""" s = "Step on no pets" def reverse(s): rev = [] for x in range(1,len(s)+1): rev.append(s[-x]) return ''.join(rev) def removePunc(s,temp): """Removes punctuation, capitalization, and spacing""" for x in range(len(s)): if s[x] not in " ,?.''": temp.append(s[x].lower()) def spliter(temp,split1,split2): """splits given string into half""" for x in range(len(temp)): if x<len(temp)/2: split1.append(temp[x]) else: split2.append(temp[x]) split1 = [] split2 = [] temp = [] removePunc(s,temp) spliter(temp,split1,split2) split1 = str(''.join(split1)) split2 = str(reverse(''.join(split2))) if split1 == split2: print ('True') else: print ('False')
# https://www.hackerrank.com/challenges/frequency-queries/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps&h_r=next-challenge&h_v=zen #!/bin/python3 # copied from discussions. couldn't come up with solution that didn't timeout. import math import os import random import re import sys from collections import defaultdict # Complete the freqQuery function below. def freqQuery(queries): ds = {} print_list = [] freqs = defaultdict(set) for query in (queries): qtype,val = query[0],query[1] freq = ds.get(val, 0) if qtype == 1: ds[val] = freq + 1 freqs[freq].discard(val) freqs[freq+1].add(val) elif qtype == 2: ds[val] = max(0,freq - 1) freqs[freq].discard(val) freqs[freq-1].add(val) else: print_list.append(1 if freqs[val] else 0) return print_list if __name__ == '__main__': q = int(input().strip()) queries = [] for _ in range(q): queries.append(list(map(int, input().rstrip().split()))) ans = freqQuery(queries) print('\n'.join(map(str, ans)))
mealCost = float(input()) tipPercent = int(input()) taxPercent = int(input()) totalCost = mealCost + (mealCost*(tipPercent/100)) + (mealCost*(taxPercent/100)) totalCost = round(totalCost) print("The total meal cost is {} dollars.".format(int(totalCost)))
# **************************************************************************** # # # # ::: :::::::: # # Main.py :+: :+: :+: # # +:+ +:+ +:+ # # By: vdaviot <[email protected]> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2016/11/21 22:23:02 by vdaviot #+# #+# # # Updated: 2016/11/21 22:23:06 by vdaviot ### ########.fr # # # # **************************************************************************** # #!/usr/bin/python import curses, locale, random, time, curses from curses import KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT from Mapp import Map_generator from Player import Player from Monster import Monster from Monster_table import Monster_table from Status import Status import sys class Main_game(): def __init__(self, win): self.win = win self.level = Map_generator(win) self.player = Player(self.level) self.monster_table = Monster_table(self.level) self.action = False self.event = 0 Main_game.turn = 1 self.run() def run(self): self.run = True; while self.run == True: if self.event == 127: self.run = False self.win.addnstr(7, 20, "Game Closed!", len("Game Closed!")) self.win.refresh() time.sleep(3) curses.endwin() sys.exit() if self.event in [KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT]: self.player.move(self.event) self.action = True self.win.addnstr(0, 0, str(self.event), len(str(self.event))) if self.event == 32: self.player.actions(self.event, self.monster_table) self.action = True if self.action == True: self.monster_table.monster_movement() Main_game.turn += 1 self.action = False run = self.refresh(self.monster_table, self.player, self.run) if run == False: break # self.level.print_map(self.player, self.monster_table, Main_game.turn) self.event = win.getch() self.win.clear() self.win.addnstr(7, 20, "You died!", len("You died!")) self.win.refresh() time.sleep(3) curses.endwin() def refresh(self, monster_table, player, run): for i in range(len(monster_table.table)): monster_table.table[i].status.refresh_status(monster_table.table[i], run) return player.status.refresh_status(player, run) if __name__ == '__main__': locale.setlocale(locale.LC_ALL,'fr_FR.UTF-8') stdscr = curses.initscr() win = curses.newwin(400, 400, 0, 0) win.keypad(1) game = Main_game(win)
from builtins import object #kindly borrowed from http://www.acooke.org/cute/ASCIIDispl0.html class Tree(object): def __init__(self, name, *children): self.name = name self.children = children def __str__(self): return '\n'.join(self.tree_lines()) def __unicode__(self): return u'\n'.join(self.tree_lines()) def tree_lines(self): yield self.name last = self.children[-1] if self.children else None for child in self.children: prefix = '`-' if child is last else '+-' for line in child.tree_lines(): yield prefix + line prefix = ' ' if child is last else ' ' # an alternative without generators def tree_lines_2(self): lines = [] lines.append(self.name) last = self.children[-1] if self.children else None for child in self.children: prefix = '`-' if child is last else '+-' for line in child.tree_lines(): lines.append(prefix + line) prefix = ' ' if child is last else '| ' return lines
print('Enter any two numbers to divide') print('Enter q to quit') while True: n = input('first number:') if n == 'q': break m = input('second number:') if m == 'q': break try: answer = int(n)/int(m) except ZeroDivisionError: print('You cant divide this') else: print(answer)
import json username = input('Enter your name ?') filename = 'username.json' with open(filename,'w') as f_obj: json.dump(username,f_obj) print('We\'ll remember you ' + username.title() )
import json def greet_user(): '''greet the user by name''' filename = 'username.json' try: with open(filename)as f_obj: user = json.load(f_obj) except FileNotFoundError: username = input('Enter your name?') with open(filename,'w')as f_obj: json.dump(username,f_obj) print('We\'ll remember you ' + username.title()) else: print('WELCOME BACK ' + user.title()) greet_user()
import turtle import random turtle.Screen() turtle.hideturtle() turtle.speed(1000) turtle.penup() class Sierpinski: def __init__(self): self.d1x = random.randint(-300, 300) self.d1y = random.randint(-300, 300) self.d2x = random.randint(-300, 300) self.d2y = random.randint(-300, 300) self.d3x = random.randint(-300, 300) self.d3y = random.randint(-300, 300) self.dRx = random.randint(-300, 300) self.dRy = random.randint(-300, 300) def triangle(self): turtle.goto(self.d1x, self.d1y) turtle.dot(5) turtle.goto(self.d2x, self.d2y) turtle.dot(5) turtle.goto(self.d3x, self.d3y) turtle.dot(5) def random_dot(self): turtle.goto(self.dRx, self.dRy) turtle.dot(5) def sierpinski(self): while True: corner = random.randint(0, 2) if corner == 0: self.dRx = (self.d1x + self.dRx) / 2 self.dRy = (self.d1y + self.dRy) / 2 turtle.goto(self.dRx, self.dRy) turtle.dot(5) elif corner == 1: self.dRx = (self.d2x + self.dRx) / 2 self.dRy = (self.d2y + self.dRy) / 2 turtle.goto(self.dRx, self.dRy) turtle.dot(5) elif corner == 2: self.dRx = (self.d3x + self.dRx) / 2 self.dRy = (self.d3y + self.dRy) / 2 turtle.goto(self.dRx, self.dRy) turtle.dot(5) sierpinskiTriangle = Sierpinski() sierpinskiTriangle.triangle() sierpinskiTriangle.random_dot() sierpinskiTriangle.sierpinski() turtle.done()
class student: def __init__(self,name,age,rollno,std): self.name=name self.age=age self.rollno=rollno self.std=std s1=student('yaqoob',16,157,10) '''print("name=",s1.name) print("Age=",s1.age) print("rollno=",s1.rollno) print("Standard=",s1.std)''' print(s1.__dict__)
#concatinating two string s1=input('Enter String 1:') s2=input('Enter String 2:') print('Conactinating two string using + operator') s3=s1+' '+s2 print('Concatinated String:',s3) i,j=0,0 s4='' while i<len(s1): s4=s4+s1[i] i=i+1 s4=s4+' ' while j<len(s2): s4=s4+s2[j] j=j+1 print('Concatinated String:',s4)
class Engine: a=90 def __init__(self): self.b=30 def m1(self): print('We are checking engine functionality') class Car: def __init__(self): self.engine=Engine() def m2(self): print('**The Car**') print("The Engine functionality") print(self.engine.a) print(self.engine.b) self.engine.m1() car=Car() car.m2()
def print_formatted(number): w = int(len(str("{0:b}".format(number))))+1 for i in range(1,number+1): d = str("{0:d}".format(i)) o = str("{0:o}".format(i)) h = str("{0:X}".format(i)) b = str("{0:b}".format(i)) print("{:>}{:>{w}}{:>{w}}{:>{w}}".format(d,o,h,b,w=w)) print_formatted(10) print(5)
x = 23 x += 1 print(x) # 24 x -= 4 print(x) # 20 x *= 5 print(x) # 100 x //= 4 print(x) # 25 x /= 5 print(x) # 5.0 - note conversion from int to float x **= 2 print(x) # 25.0 - x still represents a float x %= 5 print(x) # 0.0 - 25 is exactly divisible by 5 greeting = "Good " greeting += "morning" print(greeting) greeting *= 5 print(greeting)
from contents import recipes # Write a function that takes a dictionary as an argument, return a deep # copy of the dictionary. def my_deepcopy(d: dict) -> dict: """Copy a dictionary, creating copies of the `list` or `dict` values. The function will crash with an AttributeError if the values aren't lists or dictionaries. :param d: The dictionary to copy. :return: A copy of `d`, with the values being copies of the original values. """ # Create an empty dictionary. copy_dict = {} # Iterate over keys and values of dict being copied. copy_dict.update() # For each key, copy the value, add value to new dict. # copy_dict = d.copy() # Won't work. Makes shallow copy. return my_deepcopy(copy_dict) # Function only has to handle values that are dicts or lists. Both have # a `copy` method ;) # TO TEST FUNCTION recipes_copy = my_deepcopy(recipes) print(recipes_copy) recipes_copy["Butter chicken"]["ginger"] = 300 print(recipes_copy["Butter chicken"]["ginger"]) print(recipes["Butter chicken"]["ginger"]) print(id(recipes_copy)) print(id(recipes))
print("Today is a good day to learn Python") print('Python is fun') print("Python's strings are easy to use") print('We can even include "quotes" in strings') print("hello" + " world") greeting = "Hello" name = "Joe" print(greeting + name) # if we want a space, we can add that too print(greeting + ' ' + name) age = 24 print(age) print(type(greeting)) print(type(age)) age_in_words = "2 years" print(name + f" is {age} years old") print(type(age)) print(f"Pi is approximately {22 / 7:12.50f}") # enter whole equation pi = 22/7 print(f"Pi is approximately {pi:12.50f}") # or reference a variable. first_name = "John" last_name = "Cleese" age = 78 print(first_name + " " + last_name + f" {age}")