text
stringlengths
37
1.41M
def display(number_list,n): number_list.sort() for number in number_list: if number > n: print(number) def main(): number_list=[1,4,10,200,30,5,6,33,77,8,88,99,9] n=10 display(number_list,n) main()
#!/usr/bin/python from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor import time class motors(): def __init__(self): self.mh = Adafruit_MotorHAT(addr=0x70) #note stopping this program DOES NOT stop the motor #we COULD make this an array but for programming simplicity, have 4 variables self.upperLeft=self.mh.getMotor(1) self.upperRight=self.mh.getMotor(2) self.lowerLeft=self.mh.getMotor(3) self.lowerRight=self.mh.getMotor(4) self.motorSpeed=[0,0] #might have it work similarly to forward def back(self,speed =100,accel=20): ''' Input: speed: a number from 1-255 which sends a signal to the motor hat to the DC motor to a certain speed accel: how fast do you want to reach the max speed NOTE: -1 is a special code that tells me that you want to get to maximum speed immediately, it was a hack Output: The motors move that speed ''' if speed > 255 or speed < 0: return # do nothing for now, write error message at some point #initialize the direction of the motors self.upperLeft.run(Adafruit_MotorHAT.FORWARD) self.upperRight.run(Adafruit_MotorHAT.FORWARD) self.lowerLeft.run(Adafruit_MotorHAT.FORWARD) self.lowerRight.run(Adafruit_MotorHAT.FORWARD) #slowly accellerate the motors so they aren't jerky, #think of someone constantly stopping and starting car for i in range(speed)[::accel]: self.upperLeft.setSpeed(i) self.upperRight.setSpeed(i) self.lowerLeft.setSpeed(i) self.lowerRight.setSpeed(i) #these are assumed to be at a full stop def turnRight(self,speed =5, angle=30, accel=20): ''' Input: speed: a number from 1-255 which sends a signal to the motor hat to the DC motor to a certain speed accel: how fast do you want to reach the max speed Output: The motors move that speed ''' if speed > 255 or speed < 0: return # do nothing for now, write error message at some point self.upperLeft.run(Adafruit_MotorHAT.BACKWARD) self.upperRight.run(Adafruit_MotorHAT.FORWARD) self.lowerLeft.run(Adafruit_MotorHAT.BACKWARD) self.lowerRight.run(Adafruit_MotorHAT.FORWARD) #make sure the library is imported from the compass for i in range(speed)[::accel]: self.upperLeft.setSpeed(i) self.upperRight.setSpeed(i) self.lowerLeft.setSpeed(i) self.lowerRight.setSpeed(i) def turnLeft(self,speed =5,accel=10): ''' Input: speed: a number from 1-255 which sends a signal to the motor hat to the DC motor to a certain speed accel: how fast do you want to reach the max speed NOTE: -1 is a special code that tells me that you want to get to maximum speed immediately, it was a hack Output: The motors move that speed ''' #same as turn left, figure out Radians or Degrees if speed > 255 or speed < 0: return # do nothing for now, write error message at some point self.upperLeft.run(Adafruit_MotorHAT.FORWARD) self.upperRight.run(Adafruit_MotorHAT.BACKWARD) self.lowerLeft.run(Adafruit_MotorHAT.FORWARD) self.lowerRight.run(Adafruit_MotorHAT.BACKWARD) if accel != -1: for i in range(speed)[::accel]: self.upperLeft.setSpeed(i) self.upperRight.setSpeed(i) self.lowerLeft.setSpeed(i) self.lowerRight.setSpeed(i) else: self.upperLeft.setSpeed(speed) self.upperRight.setSpeed(speed) self.lowerLeft.setSpeed(speed) self.lowerRight.setSpeed(speed) def forward(self,speed =255,accel=10,driftRatio=1): ''' Input: speed: a number from 1-255 which sends a signal to the motor hat to the DC motor to a certain speed accel: how fast do you want to reach the max speed NOTE: -1 is a special code that tells me that you want to get to maximum speed immediately, it was a hack driftRatio: a number between 1 and 2, honestly it could be larger but the math is hacky that essentially says Move right motors faster than the others Output: The motors move that speed ''' if speed > 255 or speed < 0: return # do nothing for now, write error message at some point self.upperLeft.run(Adafruit_MotorHAT.BACKWARD) self.upperRight.run(Adafruit_MotorHAT.BACKWARD) self.lowerLeft.run(Adafruit_MotorHAT.BACKWARD) self.lowerRight.run(Adafruit_MotorHAT.BACKWARD) if driftRatio ==1: #note that the Math for i in range(motorSpeed[0],speed*driftRatio)[::accel]: self.upperRight.setSpeed(i) self.lowerRight.setSpeed(i) for i in range(motorSpeed[1],speed)[::accel]: self.upperLeft.setSpeed(i) self.lowerLeft.setSpeed(i) #for now, just for left/right control self.motorSpeed=[speed,speed] else: #make sure values are valid if speed*driftRatio > 255: return #hacky solution, try to have one set of wheels accellerate slightly faster than the other wheels for i in range(motorSpeed[0],speed*driftRatio)[::accel]: self.upperRight.setSpeed(i) self.lowerRight.setSpeed(i) for i in range(motorSpeed[1],speed)[::accel]: self.upperLeft.setSpeed(i) self.lowerLeft.setSpeed(i) self.motorSpeed=[speed*driftRatio,speed] def stop(self,speed=0): ''' Input: speed: a number from 1-255 which sends a signal to the motor hat to the DC motor to signify what speed it was moving Output: The motors stop ''' #decellerates, then stops for i in range(speed)[::-1]: self.upperLeft.setSpeed(i) self.upperRight.setSpeed(i) self.lowerLeft.setSpeed(i) self.lowerRight.setSpeed(i) self.upperLeft.run(Adafruit_MotorHAT.RELEASE) self.upperRight.run(Adafruit_MotorHAT.RELEASE) self.lowerLeft.run(Adafruit_MotorHAT.RELEASE) self.lowerRight.run(Adafruit_MotorHAT.RELEASE) # optional sleep to make reduce jerkiness #time.sleep(1.0) def redirect(self,direction): # quick 90 degree turn (will need some code to figure out which one) need to enable sensors for detection # back max speed (unless a collision # another quick 90 degree Turn to rorganise then zoom past to get behind it self.turnRight(speed=50, angle=90) self.back(speed=90) self.turnRight(speed=50, angle=90) self.forward(speed=50) def movementTest(): try: forward(25) time.sleep(1) stop() #back(255) #stop() #turnLeft(255) #stop() #slow and smooth #turnRight(speed=255, accel=1) #fast and jerky #turnRight(speed=255, accel=-1) #oneWheelTime(speed=255, accel=10) #time.sleep(1) #stop() finally: stop() #movementTest()
from time import sleep from threading import * class Hello(Thread): def run(self): for i in range(5): print("Hrello") class Hi(Thread): def run(self): for i in range(5): print("Hi") sleep(1) t1=Hello() t2=Hi() t1.start() sleep(0.2) t2.start() t1.join() t2.join() print("Byee")
#!/usr/bin/env python import sys, math r = float(sys.argv[1]) s = math.sin(r) #print ('Hello, World! sin(%g)=%g') % (r, s) print ('Hello, World! sin({0!r})={1!s}'.format(r, s))
''' Erich Chu CS 1122 hw04client.py Echo Server : Client Code The way I created an echo server in Python was by creating server code to start the server and client code to pass the message to the server. This is the server portion. ''' import socket import sys #Creates a socket clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Address and port of the server user wants to connect to s_address = ('localhost', 10000) print "Connecting to " + s_address[0] + "port " + str(s_address[1]) #Connects user to the server clientsock.connect(s_address) #Inputs message user wants to have echo back message = raw_input("Enter message \n") #Sends message to the server clientsock.sendall(message) #Receives the echo from the server and prints it data = clientsock.recv(4096) print(data)
import fractions n = int(input()) As = list(map(int, input().split(" "))) largest = 1 for i in range(n): gcd = 0 for idx, j in enumerate(As): if idx == i: continue gcd = j if gcd==0 else fractions.gcd(gcd, j) if gcd <= largest: break if gcd > largest: largest = gcd print(largest)
driving = input('你有開過車嗎?') if driving != '有' and driving!='沒有': print('只能輸入 有/沒有') raise SystemExit age = input('今年幾歲?') age = int(age) if driving == '有': if age >= 18: print(age , '歲了,行車注意安全,安心上路') else: print('為什麼你開過車了?!') elif driving == '沒有': if age >= 18: print('要試著考看看嗎?會方便很多喔!') else: print('等你18歲就可以考了') else: print('只能輸入 有/沒有')
import datetime class Address(): def __init__(self, addr, port, timestamp): self.addr = addr self.port = port self.timestamp = timestamp addrs = [] def learnAddr(src, input_port): global addrs now = datetime.datetime.now() addrs = [addr for addr in addrs if (now - addr.timestamp).total_seconds() < 10 and addr.addr != src] addrs = addrs + [Address(src, input_port, now)] def getAddr(dest): global addrs record = next((addr for addr in addrs if addr.addr == dest), None) if record != None: return record.port return None
from random import * #Default prompts for words adj_prompt = "Input adjective: " verb_prompt = "Input verb: " noun_prompt = "Input noun: " #Default stories if user does not want to make their own default_story = "One day, while *VERB my way down the street, I ran across a *ADJE *NOUN. I was very surprised, but I kept going. I then saw a *ADJE *NOUN who was *VERB. Must have been a weird day. But finally the oddest of all, I saw a *ADJE, *ADJE *NOUN *VERB a *NOUN at me, so I decided it was time to leave.\n" #Unused default order for default story default_order = ["verb","adj","noun", "adj","noun","verb","adj","adj","noun","verb","noun"] #Gets user input based on type of word def user_input(prompt, num_left): user_input = input(str(num_left)+" words of this type left to enter, "+prompt) return user_input #Gets words from user def get_words(number_adj,number_noun,number_verb): words = list() for x in range(number_adj): words.append(user_input(adj_prompt,number_adj-x)) for x in range(number_noun): words.append(user_input(noun_prompt,number_noun-x)) for x in range(number_verb): words.append(user_input(verb_prompt,number_verb-x)) return words #To create a story object class Story: def __init__(self,number_adj,number_noun,number_verb,text,order): self.number_noun=number_noun self.number_adj=number_adj self.number_verb=number_verb self.text=text self.order=order #Creates an ordered list for the words to be added to the story def order_words(words,order,number_adj,number_noun,number_verb): adj_words=words[0:number_adj] noun_words=words[number_adj:number_noun+number_adj] verb_words=words[number_noun+number_adj:number_noun+number_adj+number_verb] index = 0 for word in words: if(order[index] == "adj"): words[index] = adj_words[0] adj_words.pop(0) elif(order[index] == "noun"): words[index] = noun_words[0] noun_words.pop(0) elif(order[index] == "verb"): words[index] = verb_words[0] verb_words.pop(0) index += 1 return words #Takes a user story and cleans it so it works with other helper functions def clean_user_story(text): clean_story=text num_adj=0 num_noun=0 num_verb=0 order = list() x=0 while x >= 0: x = clean_story.find("*",x) if(x>=0): if(clean_story[x+1:x+5] == "ADJE"): num_adj+= 1 order.append("adj") elif(clean_story[x+1:x+5] == "NOUN"): num_noun+= 1 order.append("noun") elif(clean_story[x+1:x+5] == "VERB"): num_verb+= 1 order.append("verb") else: print("Input Error, * is not followed by type of word") selection() clean_story=clean_story[0:x+1]+clean_story[x+5:] x += 1 story = Story(num_adj,num_noun,num_verb,clean_story,order) return story #Displays story to user, either with blanks on command or after inputting words as the complete story def display_story(story,words): sectioned_story=story.split('*') final_story = list() for x in range(len(words)): final_story.append(sectioned_story[x]) final_story.append(words[x]) if(len(sectioned_story)>len(words)): final_story.append(sectioned_story[len(sectioned_story)-1]) for word in final_story: print(word,end='') print("\n\n") def randomize_words(story,words): random_adj = list() random_noun = list() random_verb = list() index = 0 for x in range (0,story.number_adj): index = int(random() * (story.number_adj-x)) random_adj.append(words[index]) words.pop(index) for x in range (0,story.number_noun): index = int(random() * (story.number_noun-x)) random_noun.append(words[index]) words.pop(index) for x in range (0,story.number_verb): index = int(random() * (story.number_verb-x)) random_verb.append(words[index]) words.pop(index) random_words = random_adj + random_noun + random_verb return random_words #Menu for user def selection(): text = 0 print("1: Use default story") print("2: Use own story") print("3: Display default story with blanks: ") print("4: Quit") choice = int(input("Input choice: ")) print(choice) if choice == 1: print("Using default story") text=default_story elif choice == 2: text = input("Write your story. Write *ADJE, *NOUN or *VERB to replace later. Press RETURN when finished: ") if(text.find('*') == -1): print("Story has no words to replace!") return True elif choice == 3: print(default_story) return True elif choice == 4: raise SystemExit else: print("Error, input is not within valid range") return True story = clean_user_story(text) words=get_words(story.number_adj,story.number_noun,story.number_verb) #Test words for default story #words=['blue', 'polka-dotted', 'hairy', 'ugly', 'turtle', 'bear', 'hot-dog', 'king', 'talking', 'swimming', 'throwing'] choice = 0 while(choice == 0): choice = input("Would you like to randomize the words that appear in the story? (y/n): ") if(choice == "Y" or choice == "y"): words=randomize_words(story,words) elif(choice == "N" or choice == "n"): print("Replaced words will not be randomized") else: print("Error, choice is not y or n, please try again.") choice=0 words=order_words(words,story.order,story.number_adj,story.number_noun,story.number_verb) display_story(story.text,words) return True running=True while(running): running = selection()
def Calculate(a,b): print(a+b) Calculate(int(input("enter a number")),int(input("enter a number"))) def Calculate1(a,b): print(a*b) Calculate1(int(input("enter a number")),int(input("enter a number")))
a={} b=input("the last number of the sequence") for i in range(0,int(b)+1): a[i]=int(i)**2 print(a)
from collections import Counter dict1={'a':200,'b':150,'c':300} dict2={'a':250,'b':100,'c':200} dictS={} dictS=dict1+dict2 print(dictS)
with open('mulcam.txt','r') as text: lines = text.readlines() #읽어왔음 lines.sort(reverse=True) for line in lines: print(line.strip()) #lines.reverse() with open('mulcam.txt','w') as text: for line in lines: f.write(line)
# Author: Timothy Hubbard # Version 1.0 # Formula Written by: Danish Raza aquired from geeksforgeeks.org # Formula Website: https://www.geeksforgeeks.org/program-to-find-lcm-of-two-numbers/ def welcome(): print("Welcome to Finding the LCM Calculator\nVersion 1.0\nType exit to exit the program") start() # Function to process the LCM of more than two numbers def getlcmofthree(numarray): num1 = numarray[0] num2 = numarray[1] num3 = numarray[2] # Calculates the GCF def gcd(num1, num2): if num1 == 0: return num2 return gcd(num2 % num1, num1) # Calculates the LCM after the GCF is found def lcm(num1, num2): return (num1 / gcd(num1, num2))* num2 # Returns the LCM to the main function start() return lcm(num1, lcm(num2, num3)) # Function to process the LCM of the input given in start() def getlcmNums(numarray, greater): num1 = numarray[0] num2 = numarray[1] # Filter to identify if there are two or three numbers if greater == True: return getlcmofthree(numarray) elif greater == False: def gcd(num1, num2): if num1 == 0: return num2 return gcd(num2 % num1, num1) def lcm(num1, num2): return (num1 / gcd(num1, num2))* num2 return lcm(num1, num2) # Main Function where inputs are taken def start(): numbers = input("Enter Numbers >>> ") if numbers == "exit": exit else: # For Error Handling try: numarray = [int(i) for i in numbers.split(' ')] length = len(numarray) except: print("Enter a number not a string.") print("Exit code 0") start() # Filter for figuring out how many numbers there are and where they go if length == 1: print("Enter more than one number.") start() elif length == 2: getlcmNums(numarray, greater = False) print("The LCM is", getlcmNums(numarray, greater = False)) start() elif length == 3: getlcmNums(numarray, greater = True) print("The LCM is", getlcmNums(numarray, greater = True)) start() elif length <= 4: print("Can only process 3 numbers at a time") start() # Main Function Call welcome()
print ("This is a programme to check the vadility of dates\n") x=0 try : year = int(input("please enter a year : ")) month = int(input("please enter a month : ")) day = int(input("please enter a day : ")) except : print ("invalid input") else : if year > 2020 or year < 0: print("invalid year") x=1 if year % 4 == 0: print("leap year يعني سنة كبيسة") if month > 12 or month < 0: print("invalid month") x = 1 if day > 31 or day < 0: print("invalid day") x = 1 else : if month == 2: if year % 4 == 0 : if day > 29 or day < 0: print("invalid day in this month") x = 1 elif day > 28 or day < 0: print("invalid day in this month") x = 1 if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12: if day > 31 or day < 0: print("invalid day in this month") x = 1 if month == 4 or month == 6 or month == 9 or month == 11: if day > 30 or day < 0: print("invalid day in this month") x = 1 if x== 0 : print ("valid date")
import unittest from Calculator import Calculator from CsvReader import CsvReader class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.calculator = Calculator() def test_instantiate_claculator(self): self.assertIsInstance(self.calculator, Calculator) def test_add_method_calculatorr(self): self.assertEqual(self.calculator.add(2, 2), 4) def test_subtract_method_calculator(self): self.assertEqual(self.calculator.subtract(2, 2), 0) def test_multiply_method_calculator(self): self.assertEqual(self.calculator.multiply(2, 2), 4) def test_divide_method_calculator(self): self.assertEqual(self.calculator.divide(4, 2), 2) def test_sqr_method_calculator(self): self.assertEqual(self.calculator.sqr(2), 4) def test_sqrRoot_method_calculator(self): self.assertEqual(self.calculator.sqrRoot(4), 2) # testing from file def test_AdditionFromFile(self): test_data = CsvReader('./src/Addition.csv').data for row in test_data: result = float(row['Result']) self.assertEqual(self.calculator.add(row['Value 1'], row['Value 2']), result) def test_subtractionFromFile(self): test_dataS = CsvReader('./src/Subtraction.csv').data for row in test_dataS: result = float(row['Result']) print("hello") print(result) self.assertEqual(self.calculator.subtract(row['Value 2'], row['Value 1']), result) def test_MultiplicationFromFile(self): test_dataM = CsvReader('./src/Multiplication.csv').data for row in test_dataM: result = float(row['Result']) self.assertEqual(self.calculator.multiply(row['Value 1'], row['Value 2']), result) def test_DividisionFromFile(self): test_dataD = CsvReader('./src/Division.csv').data for row in test_dataD: result = float(row['Result']) self.assertEqual(round(self.calculator.divide(row['Value 2'], row['Value 1']),9),result) def test_sqrFromFile(self): test_dataQ = CsvReader('./src/Square.csv').data for row in test_dataQ: result = float(row['Result']) self.assertEqual(self.calculator.sqr(row['Value 1']), result) def test_sqrRootFromFile(self): test_dataR = CsvReader('./src/Square Root.csv').data for row in test_dataR: result = float(row['Result']) self.assertEqual(round(self.calculator.sqrRoot(row['Value 1']),7), round(result,7)) if __name__ == '__main__': unittest.main()
import difflib import xmlParser import time def main(): inp = input("Make sure to run phase1 with the xml file you wish to test before testing for correctness.\nThe test uses difflib to test differences and time to test speed.\n\nType 1 to test for 10 entries correctness and 2 to test for 1k entries correctness\nand type 3 to test for speed: ") if inp == str(1): test_10() elif inp == str(2): test_1k() elif inp == str(3): test_speed() def test_speed(): inp = input("type the number of times you wanna multiple 10.xml (enteries = 10 times that): ") content = open('10.xml').read() file = open('file.xml', 'w+') for i in range(0,int(inp)): file.write(content) start = time.time() print("Type 'file.xml' below to test") xmlParser.main() end = time.time() print("time taken to parse xml : " + str(end - start)) def test_10(): # testing dates.txt print('testing dates') inp = 'dates.txt' inp2 = 'result-10-dates.txt' text1 = open(inp).readlines() text2 = open(inp2).readlines() for line in difflib.unified_diff(text1, text2): print(line) print('testing terms.txt') inp = 'terms.txt' inp2 = 'result-10-terms.txt' text1 = open(inp).readlines() text2 = open(inp2).readlines() for line in difflib.unified_diff(text1, text2): print(line) print('testing recs.txt') inp = 'recs.txt' inp2 = 'result-10-recs.txt' text1 = open(inp).readlines() text2 = open(inp2).readlines() for line in difflib.unified_diff(text1, text2): print(line) print('testing emails.txt') inp = 'emails.txt' inp2 = 'result-10-emails.txt' text1 = open(inp).readlines() text2 = open(inp2).readlines() for line in difflib.unified_diff(text1, text2): print(line) def test_1k(): # testing dates.txt print('testing dates') inp = 'dates.txt' inp2 = 'result-1k-dates.txt' text1 = open(inp).readlines() text2 = open(inp2).readlines() for line in difflib.unified_diff(text1, text2): print(line) print('testing terms.txt') inp = 'terms.txt' inp2 = 'result-1k-terms.txt' text1 = open(inp).readlines() text2 = open(inp2).readlines() for line in difflib.unified_diff(text1, text2): print(line) print('testing recs.txt') inp = 'recs.txt' inp2 = 'result-1k-recs.txt' text1 = open(inp).readlines() text2 = open(inp2).readlines() for line in difflib.unified_diff(text1, text2): print(line) print('testing emails.txt') inp = 'emails.txt' inp2 = 'result-1k-emails.txt' text1 = open(inp).readlines() text2 = open(inp2).readlines() for line in difflib.unified_diff(text1, text2): print(line) main()
from abc import ABC, abstractmethod class AbstractController(ABC): """ Abstract base class for controllers to control different phases of the game. """ @abstractmethod def frame_update(self): """ Called each frame when this controller is active. Should run game logic. """ raise NotImplementedError('This is an abstract method!') @abstractmethod def frame_render(self, screen): """ Called each frame when this controller is active. Should render graphics. """ raise NotImplementedError('This is an abstract method!') @abstractmethod def start(self): """ Called when this controller becomes active. """ raise NotImplementedError('This is an abstract method!') @abstractmethod def finish(self): """ Called when this controller is replaced. """ raise NotImplementedError('This is an abstract method!')
lista = [1, 2, 3] lista2 = lista lista.append(8) #appende adiciona dados a sua lista (acrescentando) lista2[0] = - 5 lista_mista = ['abc', 3, 'fulano', True] lista_mista[0] lista_mista[4][2]
n = int(input()) # estrutura de seleção simples # executamos um trecho de código apenas se # a condição for verdadeira if n == 0: print('n é igual a zero') # estrutura de seleção composta # temos apenas 1 condição, mas 2 caminhos: # ou n é maior # ou n não é maior (o que inclui ser igual) if n > 10: # se print('n é maior que 10') print('bloco dentro do if') else: # senão print('n NÃO é maior que 10') print('bloco dentro do else') print('fim') #### seleção simples ##se <condição>: ## <bloco de código> ## ##<bloco fora do if> ## ## #### seleção composta ##se <condição>: ## <bloco de código> ##senão: ## <bloco de código> ## ##<bloco fora do if>
from time import sleep entrada = input('Digite os números separados por espaço:') numeros = entrada.split() for x in numeros: print(x, end='...') for x in range(5, -1, -1): print('resultado é {}, '.format(x), end='') sleep(1) input('enter para continuar...')
#[2, 3, 25, 4, 87, 27, 25] n = int(input('digite um número: ')) if n == 2 or n == 3 or n == 25 or n == 4 or n == 87 or n == 27: print(n, 'está na lista') else: print(n, 'não está na lista')
Complete the function that returns an array of length n, starting with the given number x and the squares of the previous number. If n is negative or zero, return an empty array/list. Examples 2, 5 --> [2, 4, 16, 256, 65536] 3, 3 --> [3, 9, 81] def squares(x, n): arr = [] sq = x while len(arr) < n: arr.append(sq) sq = sq**2 return arr
#For building the encrypted string: #Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String. #Do this n times! #Examples: #"This is a test!", 1 -> "hsi etTi sats!" #"This is a test!", 2 -> "hsi etTi sats!" -> "s eT ashi tist!" #Write two methods: #def encrypt(text, n) #def decrypt(encrypted_text, n) #For both methods: #If the input-string is null or empty return exactly this value! #If n is <= 0 then return the input text. def encrypt(text,n): if n <= 0: encrypted_text = text else: encrypted_text = text for i in range(n): encrypted_text = encrypted_text[1::2]+encrypted_text[0::2] return(encrypted_text) def decrypt(text,n): if n <= 0: decrypted_text = text else: import math decrypted_text = text for i in range(n): first_half = decrypted_text[:math.floor(len(text)/2)] second_half = decrypted_text[math.floor(len(text)/2):] new_list = [0 for i in range(len(text))] new_text = "" for j in range(len(first_half)): new_list[2*j+1] = first_half[j] for j in range(len(second_half)): new_list[2*j] = second_half[j] decrypted_text = new_text.join(new_list) return(decrypted_text)
#Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. # #Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw" spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test" def spin_words(sentence): sentence_list = sentence.split() sentence_list = [i if len(i) < 5 else i[::-1] for i in sentence_list] reversed_sentence = ' '.join(map(str, sentence_list)) return reversed_sentence
# If we were to set up a Tic-Tac-Toe game, we would want to know whether the board's current state is solved, wouldn't we? Our goal is to create a function that will check that for us! # Assume that the board comes in the form of a 3x3 array, where the value is 0 if a spot is empty, 1 if it is an "X", or 2 if it is an "O", like so: # [[0, 0, 1], # [0, 1, 2], # [2, 1, 0]] # We want our function to return: # -1 if the board is not yet finished (there are empty spots), # 1 if "X" won, # 2 if "O" won, # 0 if it's a cat's game (i.e. a draw). # You may assume that the board passed in is valid in the context of a game of Tic-Tac-Toe. def is_solved(board): # Check who won the rows. for i in range(3): if all([board[i][j] == 1 for j in range(3)]): return 1 break elif all([board[i][j] == 2 for j in range(3)]): return 2 break # Check who won the columns. for j in range(3): if all([board[i][j] == 1 for i in range(3)]): return 1 break elif all([board[i][j] == 2 for i in range(3)]): return 2 break # Check who won the diagonal. if all([board[i][i] == 1 for i in range(3)]): return 1 elif all([board[i][i] == 2 for i in range(3)]): return 2 # If the board is not yet finished, then return -1, otherwise it's a cat. if (0 in board[0]) or (0 in board[1]) or (0 in board[2]): return -1 else: return 0
# Array Exchange and Reversing # It's time for some array exchange! The objective is simple: exchange the elements of two arrays in-place in a way that their new content is also reversed. # before # my_list = ['a', 'b', 'c'] # other_list = [1, 2, 3] # exchange_with(my_list, other_list) # after # my_list == [3, 2, 1] # other_list == ['c', 'b', 'a'] def exchange_with(a, b): temp_1 = a[::-1] temp_2 = b[::-1] a.reverse() b.reverse() a.extend(b) b.extend(temp_1) del a[0:len(temp_1)] del b[0:len(temp_2)]
# Given a string made of digits [0-9], return a string where each digit is repeated a number of times equals to its value. # Examples # Digits.Explode("312") = "333122" # Digits.Explode("102269") = "12222666666999999999" def explode(s): s_lst = list(s) s_digits = [int(i) for i in s_lst if int(i) != 0] return ''.join([str(i)*i for i in s_digits])
#Given an vector of numbers, determine whether the sum of all of the numbers is odd or even. # #Example: #odd_or_even(vec![0]) returns "even" #odd_or_even(vec![0, 1, 4]) returns "odd" #odd_or_even(vec![0, -1, -5]) returns "even" def oddOrEven(arr): s = [ ] if sum(arr) % 2 == 0: s.append('even') else: s.append('odd') answer = ' '.join(map(str, s)) return(answer)
def calc(l, w, h): lw = l*w lh = l*h wh = w*h if lw <= lh and lw <= wh: least = lw elif lh <= lw and lh <= wh: least = lh elif wh <= lh and wh <= lw: least = wh surface = 2*l*w + 2*w*h + 2*h*l + least return surface def rLength(l, w, h): maxL = 0 if l >= h and l >= w: maxL = l elif h >= w and h >= l: maxL = h elif w >= l and w >= h: maxL = w length = l*w*h + 2*l + 2*w + 2*h - 2*maxL return length total = 0 rf = open('advent.txt', 'r') i = len(rf.readlines()) rf.seek(0) for i in range(0, i): line = rf.readline().strip('\n').split('x') total = total + rLength(int(line[0]),int(line[1]),int(line[2])) rf.close() print total #print Transect
""" 1. Проанализировать скорость и сложность одного любого алгоритма, разработанных в рамках домашнего задания первых трех уроков. Примечание: попробуйте написать несколько реализаций алгоритма и сравнить их. """ from timeit import timeit import cProfile def memorize(func): def g(n, memory={}): r = memory.get(n) if r is None: r = func(n) memory[n] = r return r return g def f(n): summary = 0 for i in range(1, n+1): summary += i return summary @memorize def test_digits(n): if n == 1: return 1 else: return n + test_digits(n - 1) n = 10 print(test_digits(n) == n*(n+1)//2) print(f(n) == n*(n+1)//2) print(timeit("test_digits(n)", setup="from __main__ import test_digits, n")) print(timeit("f(n)", setup="from __main__ import f, n")) # функция def f(n) имеет сложность O(n) и выполняется за 0.74-0.84 # рекурсия без мемоизации имеет сложность O(n) и выполняется за 1.55-1.6 # рекурсия с мемоизацией имеет сложность O(n) и выполняется за 0.19 # В итоге наиболее эффективным алгоритмом является рекурсия с мемоизация, которая выполняется за 0.19 из-за того, что # данные сохраняются в словарь и извлекаются из него, что не требует избыточного заполнения стека вызовов
""" 2. Написать два алгоритма нахождения i-го по счёту простого числа. Без использования «Решета Эратосфена»; Используя алгоритм «Решето Эратосфена» """ import timeit def simple_position(n): count = 1 simple = 2 while count <= n: temp = 1 is_simple = True while temp <= simple: if simple % temp == 0 and temp != simple and temp != 1: is_simple = False break temp += 1 if is_simple: if count == n: break count += 1 simple += 1 return simple def simple_era(n): simple = 2 limit = 10000 array = [i for i in range(limit)] array[1] = 0 while simple < limit: if array[simple] != 0: m = simple * 2 while m < limit: array[m] = 0 m += simple simple += 1 return [p for p in array if p != 0][n-1] n = int(input('Введите позицию простого числа: ')) print(simple_position(n)) print(simple_era(n)) print(timeit.timeit('simple_position(n)', setup='from __main__ import simple_position, n', number=100)) print(timeit.timeit('simple_era(n)', setup='from __main__ import simple_era, n', number=100))
#3. В массиве случайных целых чисел поменять местами минимальный # и максимальный элементы. from random import randint arr1 = [randint(i, 100) for i in range(10)] maximum = 0 minimum = float('inf') maximum_i = 0 minimum_i = 0 for i in range(len(arr1)): if arr1[i] > maximum: maximum = arr1[i] maximum_i = i elif arr1[i] < minimum: minimum = arr1[i] minimum_i = i print(arr1) arr1[minimum_i], arr1[maximum_i] = arr1[maximum_i], arr1[minimum_i] print(arr1)
# 8. Определить, является ли год, который ввел пользователем, # високосным или не високосным. #Год является високосным в двух случаях: либо он кратен 4, # но при этом не кратен 100, либо кратен 400. year = int(input("Введите год для проверки на високосность: ")) if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: print(f'{year} год висококсный') else: print(f'{year} год не висококсный')
# 3. По введенным пользователем координатам двух точек вывести # уравнение прямой вида y = kx + b, проходящей через эти точки. x1 = int(input('Введите x1: ')) y1 = int(input('Введите y1: ')) x2 = int(input('Введите x2: ')) y2 = int(input('Введите y2: ')) if x2 - x1 == 0 or y2 - y1 == 0: exit() else: x = y1 - y2 y = x2 - x1 b = x1 * y2 - x2 * y1 if y > 0 and b > 0: print(f'{x}x + {y}y + {b} = 0') elif y < 0 and b < 0: print(f'{x}x {y}y {b} = 0') elif y < 0 and b > 0: print(f'{x}x {y}y + {b} = 0') elif y > 0 and b < 0: print(f'{x}x + {y}y {b} = 0')
print("Array") strArray=["TOM","Jerry","Smith","Amit"]; i=0; for i in range(i,len(strArray)): print i+1," ",strArray[i]; if strArray[0]=="TOM": print("Tom Found!!");
from tkinter import * root = Tk() root.title("Simple Calculator") str1 = "" input1 = Entry(root,width=40) input1.grid(row=0,column=0,columnspan=4,padx=10,pady=10) def num(number): global str1 str1=str1+str(number) input1.delete(0,END) input1.insert(0,str1) def addopr(): global str1 str1=str1+"+" input1.delete(0,END) input1.insert(0,str1) def minusopr(): global str1 str1=str1+"-" input1.delete(0,END) input1.insert(0,str1) def equalopr(): global str1 i=eval(str1) str1=str(i) input1.delete(0,END) input1.insert(0,str1) def clearopr(): global str1 str1="" input1.insert(0,str1) def leftbracket(): global str1 str1=str1+"(" input1.delete(0,END) input1.insert(0,str1) def rightbracket(): global str1 str1 = str1 + ")" input1.delete(0, END) input1.insert(0, str1) def divide(): global str1 str1 = str1 + "/" input1.delete(0, END) input1.insert(0, str1) def multiply(): global str1 str1 = str1 + "*" input1.delete(0, END) input1.insert(0, str1) def decimal(): global str1 str1 = str1 + "." input1.delete(0, END) input1.insert(0, str1) Button(root,text="(",command=leftbracket,padx=25,pady=15).grid(row=1,column=0) Button(root,text="(",command=rightbracket,padx=25,pady=15).grid(row=1,column=1) Button(root,text="/",command=divide,padx=25,pady=15).grid(row=1,column=2) Button(root,text="*",command=multiply,padx=25,pady=15).grid(row=1,column=3) Button(root,text="1",command=lambda: num(1),padx=25,pady=15).grid(row=4,column=0) Button(root,text="2",command=lambda: num(2),padx=25,pady=15).grid(row=4,column=1) Button(root,text="3",command=lambda: num(3),padx=25,pady=15).grid(row=4,column=2) Button(root,text="4",command=lambda: num(4),padx=25,pady=15).grid(row=3,column=0) Button(root,text="6",command=lambda: num(5),padx=25,pady=15).grid(row=3,column=1) Button(root,text="6",command=lambda: num(6),padx=25,pady=15).grid(row=3,column=2) Button(root,text="7",command=lambda: num(7),padx=25,pady=15).grid(row=2,column=0) Button(root,text="8",command=lambda: num(8),padx=25,pady=15).grid(row=2,column=1) Button(root,text="9",command=lambda: num(9),padx=25,pady=15).grid(row=2,column=2) Button(root,text="0",command=lambda: num(0),padx=25,pady=15).grid(row=5,column=0) Button(root,text="+",padx=25,pady=15,command=addopr).grid(row=2,column=3) Button(root,text="-",padx=25,pady=15,command=minusopr).grid(row=3,column=3) Button(root,text="=",padx=25,pady=42,command=equalopr).grid(row=4,column=3,rowspan=2) Button(root,text="C",padx=25,pady=15,command=clearopr).grid(row=5,column=2,columnspan=1) Button(root,text=".",padx=25,pady=15,command=decimal).grid(row=5,column=1) root.mainloop()
""" db_backup.py Used to backup all of the data in the current database, make schema changes, and then reinput data """ import sqlite3 as lite def getName(): """ get current db version and then update it """ f = open('database_version.txt', 'r') version = f.read() f = open('database_version.txt', 'w') f.close() db_name = 'reviews' + str(version) + '.sqlite' # update version version = int(version) version += 1 f.write(str(version)) f.close() return db_name db_name = 'reviews.sqlite' def getTables(): conn = lite.connect(db_name) with conn: c = conn.cursor() sql = 'SELECT * FROM sqlite_master WHERE type="table"' c.execute(sql) x = c.fetchall() table_list = [] for i in xrange(len(x)): table_list.append(x[i][1]) return table_list def table_schema(): tables = getTables() table_number = len(tables) data = [] conn = lite.connect(db_name) with conn: c = conn.cursor() for i in xrange(table_number): # get schema of each table sql = 'SELECT * FROM ' + str(tables[i]) c.execute(sql) data.append(c.fetchall()) print data
# -*- coding: utf-8 -*- """ Created on Sat Oct 1 16:22:03 2016 @author: libbyaiello """ import sqlite3 conn = sqlite3.connect('schoolratings') c1 = conn.cursor() #don't call this unless you want to reset all the databases!! def set_up(): c1.execute('DROP TABLE t1_schools;') c1.execute('DROP TABLE t2_ratings;') c1.execute('CREATE TABLE t1_schools (school_id INTEGER PRIMARY KEY AUTOINCREMENT, school_name TEXT);') c1.execute('CREATE TABLE t2_ratings (rating_id INTEGER PRIMARY KEY AUTOINCREMENT, school_id, overall INTEGER, physical INTEGER, academic INTEGER, resources INTEGER, rating TEXT, FOREIGN KEY (school_id) REFERENCES t1_schools(school_id));') # For the schoolname inputted by the user, this function calculates the average ratings for each category for this school def get_ratings(schoolname): command = 'SELECT school_id FROM t1_schools WHERE school_name = \"'+schoolname+'\";' for schooldata in c1.execute(command): school_id = schooldata[0] count = 0.0 overall_total = 0 physical_total = 0 academic_total = 0 resources_total = 0 ratings = {} command = 'SELECT overall, physical, academic, resources, rating_id, rating FROM t2_ratings WHERE school_id = '+str(school_id)+';' for data in c1.execute(command): count += 1 overall_total += data[0] physical_total += data[1] academic_total += data[2] resources_total += data[3] rating_id = data[4] rating = data[5] ratings[rating_id] = rating if count == 0: return None overall_average = overall_total/count physical_average = physical_total/count academic_average = academic_total/count resources_average = resources_total/count return [overall_average, physical_average, academic_average, resources_average, ratings] categories = {'overall':0, 'physical':1, 'academic':2, 'resources':3} #this function takes in a category to sort by and returns a list of schools in descending order of their rankings in this category def get_rankings(category): rankings = [] #get all of the rankings for schooldata in c1.execute('SELECT school_name FROM t1_schools;'): schoolname = schooldata[0] rankings.append((schoolname, get_ratings(schoolname)[categories[category]])) #use lambda function to sort in descending order by x[1] return sorted(rankings, key = lambda x: x[1], reverse = True) # Interacts with the gui to allow users to input ratings for a school def add_rating(schoolname, overall, physical, academic, resources, rating): school_id = 0 #if the school already exists in t1_schools, pull up it's school_id for schooldata in c1.execute('SELECT school_id FROM t1_schools WHERE school_name = "'+schoolname+'";'): school_id = schooldata[0] c2 = conn.cursor() #if the school does not exist in the database, add it to t1_schools if school_id == 0: command = 'INSERT INTO t1_schools (school_name) VALUES (\"'+schoolname+'\")' c2.execute(command) for schooldata in c1.execute('SELECT school_id FROM t1_schools WHERE school_name = "'+schoolname+'";'): school_id = schooldata[0] #add this rating into t2_ratings c1.execute('INSERT INTO "t2_ratings" (school_id, overall, physical, academic, resources, rating) VALUES (?,?,?,?,?,?)', (school_id, overall, physical, academic, resources, rating)) # commits (updates the database) then closes the connection c1.close() conn.commit() conn.close()
import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:,3:13].values y = dataset.iloc[:,13].values #encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder label_encoder_X_1 = LabelEncoder() X[:, 1] = label_encoder_X_1.fit_transform(X[:,1]) label_encoder_X_2 = LabelEncoder() X[:, 2] =label_encoder_X_2.fit_transform(X[:,2]) onehotencoder = OneHotEncoder(categorical_features=[1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=0) from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_train) #Making the ANN import keras from keras.models import Sequential from keras.layers import Dense classifier = Sequential() #adding the input layer and the first hidden layer classifier.add(Dense(output_dim = 6, init='uniform',activation='relu', input_dim=11)) classifier.add(Dense(output_dim=6, init='uniform',activation='relu')) #Out put layer classifier.add(Dense(output_dim =1, init='uniform',activation='sigmoid')) classifier.compile(optimizer='adam', loss ='binary_crossentropy', metrics=['accuracy']) classifier.fit(X_train, y_train, batch_size=10, nb_epoch=100) # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred)
#!/usr/bin/env python2 #the above is the path to the python intepreter #I present to you: Rock, paper, scissors: THE VIDEO GAME #random module determines what move the computer will throw #time module is used to utilise dates and times import random import time #sets each move to a specific number so that once slected it is #equated to a specific variable rock = 1 paper = 2 scissors = 3 #specifying the rules of the game names = { rock: 'Rock', paper: "Paper", scissors: "Scissors" } rules = { rock: scissors, paper: rock, scissors: paper } #keeps track of scores player_score = 0 computer_score = 0 #greets the player #while loop is to allow the players to keep playing #as many times as the player wishes def start(): print 'Lets play a game of Rock, Paper, Scissors.' while game(): #pass statement allows the while loop to stop once finished pass scores() #called upon by the start function #determines the player move by calling upon the move() function #passes the moves and stores them as intergers into the result function def game(): player = move() computer = random.randint(1,3) result(player, computer) return play_again() #put into a while loop #used to obtain the an integer between one and three from the player #player variable to b created from the player's input #next are theinstructions given to the player \n adds a line break def move(): while True: print player = raw_input("Rock = 1\nPaper = 2\nScissors = 3\nMake a move") #try statement is used to clean up code and handle errors or exceptions try: player = int(player) #checks whether 1,2 or 3 are the moves if player in (1,2,3): return player except ValueError: pass print "oops! I didn't understand that. Please enter 1, 2 or 3." #only takes the player and computer variables #creates a countdown to the result #sleep pauses the execution of the code in no. of secs def result(player,computer): print "1..." time.sleep(1) print '2...' time.sleep(1) print "3!" time.sleep(0.5) #prints out what the computer played #looks up the numbers in the move() function then inserts it to where{0} is print "Computer threw {0}".format(computer_score) #calls the scores set earlier #the global function allows the variable to be changed #especially after having been appended by scores global player_score, computer_score #checks if the results are the same if player_score == computer_score: print "tie game" #checks whether its a win or a loss else: if rules[player] == computer: print "your victory has been assured!" else: print "the computer laughs as you realise you have been defeated!" computer_score += 1 #the play_again function #just like the moe function hich asks user for input def play_again(): answer = raw_input("would you like to play again? y/n: ") #checks to see what the response is if answer in ("y", "yes", "Yes", "Of course!"): return answer #we assume the player does not want to keep playing #prints a goodbye message and causes the game function not to restart else: print "Thank you very much for playing our game! See you next time!" #after the game is over we move to the score function #this code won't save the scores though def scores(): global player_score, computer_score print "High Scores" print "player ", player_score print "computer ", computer_score #enables it to be run differently, ie either in the command line or importing it to another script if __name__ == "__main__": start()
""" Imagine this. Your client's luxury hotel in Wakanda is not doing great. But you have a feeling that it might be connected to the recent geopolitical climate. There is a great table on Wikipedia that shows Global Peace Index for all countries, and you could use this to compare how does the performance of your hotel relate to this. However, it's a big table that you wouldn't want to copy by hand. That's where the pandas.read_html() function comes in. Provide it with a link to the wikipedia page, and it will return all the tables on this page as a DataFrame object. All you need to do is select the table you want, maybe improve it a bit and save it to excel. http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.read_html.html """ import pandas as pd # Get the page that contains some tables wiki_link = "https://en.wikipedia.org/wiki/Global_Peace_Index" # Use pandas to scrape all the tables off the page, this will return a list list_of_dataframes = pd.read_html(wiki_link) # Check out http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.read_html.html for more options print(type(list_of_dataframes)) # Go through all the tables that we scraped for df in list_of_dataframes: print(df.head()) # Use .head() to only print first 5 rows of the tables # The table that we are interested got printed second # Bearning in mind Python's 0-indexing, we get this table from the list table = list_of_dataframes[1] print(type(table)) # This is a pandas.DataFrame object that we can manipulate just like we saw in the previous snippet # Printing out just this table print(table.head()) # Notice that the table has no index, and no column names, just numbers. # We can set columns to be the same as first row of the table, and then delete that row table.columns = table.iloc[0] table.drop(0, inplace=True) # inplace=True makes this work on the object without retourning a new onw # Then we can set index using column name print(table.head()) table.set_index('Country') # Now that we have index and column names, we can dig in print(table.iloc[[6,56],0:5]) # Or just export the whole thing to excel # table.to_excel('D:/mypath/myfile.xlsx')
""" Essentially, an API is a web page that returns information in a nice machine-readable format. We use a number of APIs for benchmarking and other projects, but there are APIs for almost anything. For example - I'm sure you've all been wondering when is Jan's name day. There's an API for that. Every public API you will use will have a documentation that describes exactly what info you need to provide and what info it can provide back. The easiest way of making a request to an API is to use Python's requests library. Check the snippet and try it out! """ # Import the requests library that the script will use to communicate with the API # I recommend having a look at it's documentation at some point, as some APIs require some more advanced features of the library - http://docs.python-requests.org/en/master/ import requests # We'll use the abalin.net API to get our nameday information # Before going further, check the documentation to see what the API provides - https://api.abalin.net # We want to search nameday by name, so we set the appropriate endpoint api_endpoint = "https://api.abalin.net/get/getdate" # As you can see from the docs, there are two parameters that you need to provide - name that you are searching for, and a calendar (as each country has different name days) # You can do this by creating a dictionary with parameter names as keys, and the information as values. parameters = { 'name': 'Jan', 'calendar': 'cz' } # Now that we're all set, let's make the request using the requests library # This is Python's equivalent to you typing this url in your browser - https://api.abalin.net/get/getdate?name=Jan&calendar=cz response = requests.get(api_endpoint, params=parameters) # The library will return a special response object # Since the documentation says the API returns JSON strings, we can access these using the response objects' .json() method result = response.json() print(result)
import numpy as np class Energy: """ Object containing the information about any sort of energy production (+) or consumption (-)""" def __init__(self,name, energy=0): #could contain more information self.name = name self.energy = energy return
import json import requests # edit bearer to what you get from requests.get auth_token = {'Accept':'application/json', 'Authorization':'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTk3ODMxMjAzLCJleHAiOjE1OTc5MTc2MDN9.1xPbqhiYl6iXly4jE0_LSwMsQm5mJBv_xjJ-XC2VUgg'} host = input("What is Host IP: ") port = input("What is Host Port: ") url = "http://" + host + ":" + port # edit for your own creds r = requests.post(url + "/login", json={'username':'admin', 'password':'Zk6heYCyv6ZE9Xcg'}) print(json.dumps(r.json(), indent=4)) r = requests.get(url + "/users", headers=auth_token) my_json = r.json() dictionary = json.dumps(my_json, indent=4) print(dictionary) # edit to loop through for paremeter you want to lookup for i in my_json: name = i['name'] nameLogs = requests.get("http://10.10.10.137:3000/users/" + name, headers=auth_token) print(nameLogs.json())
from socket import * # if we use a hostname below instead of an IP address, then a DNS lookup will automatically be performed to get the IP address serverName = '' # sets the string serverName to hostname: provide a string containing either the IP address ("128.138.32.126") <-- (this is an example IP.. use your own ip address..) of the or hostname ("cis.poly.edu") of the server serverPort = 12000 # don't change this lol # the first parameter in socket() indicates the address family, where AF_INET indicates that the uderlying network is using IPv4 # the second parameter indicates that the socket is of type SOCK_DGRAM, which means it is a UDP socket clientSocket = socket(AF_INET,SOCK_DGRAM) # create socket # note that I'm not specifying the port number of the client socket when it's created, instead letting the operatin system do this for us # raw_python() is a built-in python function. Upon execution, the user at the client is prompted with the words "Input data:", # then using her keyboard to input the a line, which is put into the variable message message = raw_input('Input lowercase sentence:') # the sendto() method attaches the destination address # (comprising the serverName and serverPort) to the # message and sends the resulting packet into the # process' socket, clientSocket clientSocket.sendto(message,(serverName, serverPort)) # when the packet arrives from the internet at the client's socket, the packet's data is put into the variable # modifiedMessage and the packet's source address is put into the variable serverAddress # serverAddress carries both the server's IP address and port number # the method recvfrom also takes the buffer size 2048 as input (this buffer size works for most purposes) modifiedMessage, serverAddress = clientSocket.recvfrom(2048) # this should print out the modifiedMessage string, yielding the same input string but with all caps print(modifiedMessage) # closes the socket, then the process terminates clientSocket.close()
# This script rolls dice for the RPG Shadowrun, the roll technique is you roll # N number of 6 sided dice against a target number. For every die that equals or excedes # The target number you get a success. 0 successes means that you fail the task. # If you roll all ones it is a critical failure # 1 or 2 successes means you barely succeeded # 3 or 4 means that you did okay # 5 or more successes means you aced it. #Pyplot for Data Visualizations import matplotlib.pyplot as plt # Import numpy and set seed import numpy as np import time #set unique RNG seed for rubustness in die rolling np.random.seed(int(time.time())) #This list tracks indiviual dice for evaluation against a target number skill_check = [] success = 0 botch = 0 #To assign the number of dice to throw, always an interger >0 dice_pool = int(input("How many dice do you need to throw for the success test? ")) #To assign a target number to roll against tn = int(input("What is the target number of this success test? ")) #6's in SR are open-ended. If you roll a 6 you reroll that die and add the result #You repeat until the die is not a 6. This allows Target numbers to excede 6 for i in range(dice_pool): dice = np.random.randint(1,7) roll = dice if tn > 6: #open ended die rolling only needed if target number excededs 6 while dice == 6: dice = np.random.randint(1,7) roll = roll + dice skill_check.append(roll) #print(skill_check) #This counts for successes and botches, if botches = die pool its a critical failure for die in skill_check: if(die >= tn): success += 1 elif(die == 1): botch += 1 if(botch == dice_pool): print("You done messed up A-A-Ron!") print("You rolled " + str(success) + " successes.") #Gives a graphical display of your success test plt.hist(skill_check, bins =max(skill_check)) plt.show()
#Probabily of rolling a six given X number of dice #Answers the question of whehter or not more dice is better #More dice is actually worse import numpy as np #much faster to do this with a binomial def roll_dice2(dice_number, sixes_needed, trials): chance = float(1)/float(6) #dice number is trials, change is 1/6, then how many times #add up the times you get the sixes you need success = sum(np.random.binomial(dice_number, chance, trials) >= (sixes_needed)) print success return float(success)/float(trials) def roll_dice(dice_number, sixes_needed, trials): success = Series([0] * trials) # loops through trials number of times rolling dice and checking for i in range(0, trials): roll = Series(np.random.choice(range(1,7), dice_number, replace=True)) #print roll counts = roll.value_counts() #print counts if 6 in roll.value_counts(): #print ('Six found!') if roll.value_counts()[6] >= sixes_needed: success[i] = 1 #print ('Success! /n') return success dice_num = int(raw_input('Dice to roll: ')) six_needed = int(raw_input('How many sixes do you need?' )) trial_runs = 1000 #answer = roll_dice(dice_num, six_needed, trial_runs) #print answer.mean() answer2 = roll_dice2(dice_num, six_needed, trial_runs) print 'You will win %f percent of the time' % (round(answer2, 2) * 100)
# sortowanie szybkie (pesymistycznie n^2 ALE bardzo rzadkie; zazwyczaj nlgn) def quicksort(array, left, right): if left < right: mid = partition(array, left, right) quicksort(array, left, mid - 1) quicksort(array, mid + 1, right) def partition(array, left, right): elem = array[right] i = left for j in range(left, right): if array[j] <= elem: array[i], array[j] = array[j], array[i] i += 1 array[i], array[right] = array[right], array[i] return i if __name__ == '__main__': T1 = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] quicksort(T1, 0, len(T1) - 1) print(T1)
# Created by Marcin "Cozoob" Kozub 30.05.2021 # Zlozonosc: O(V + E) # reprezentacja list sasiedztwa def topological_sort(G): n = len(G) visited = [False for _ in range(n)] def visit(s): nonlocal visited, stack, n, G visited[s] = True for v in G[s]: if not visited[v]: visit(v) stack.append(s) stack = [] for v in range(n): if not visited[v]: visit(v) return stack[::-1] # zlozonosc czasowa O(V) if __name__ == '__main__': G = [ [], [], [3], [1], [1, 0], [2, 0] ] print(topological_sort(G))
from random import randint, seed class Node: def __init__(self): self.next = None self.value = None def qsort(L): start = Node() start.next = L def rek_qsort(prev_start, end_next): # funkcja otrzymuje wskaznik na element przed podzialem i zaraz po aby # fragment bylo mozna wpiac do listy while prev_start.next != end_next: left, right = partition(prev_start, end_next) rek_qsort(prev_start, left) # bez rekursji ogonowej prev_start = right left = end_next def partition(prev_start, end_next): pointer = prev_start.next # pointer wskazuje od ktorego momentu chcemy dzielic/sortowac # 3 nowe listy # wartosci wieksze od pivota greater_start = greater = Node() # wartosci mnijesze od pivota lesser_start = lesser = Node() # wartosci rowne pivotowi equal_start = equal = Node() pivot = pointer.value while pointer != end_next: if pointer.value < pivot: lesser.next = pointer lesser = lesser.next elif pointer.value > pivot: greater.next = pointer greater = greater.next else: equal.next = pointer equal = equal.next pointer = pointer.next # lacze 3 listy w jedna w odpowiedniej kolejnosci lesser.next = equal_start.next equal.next = greater_start.next # lacze nowa liste ze stara lista if equal.next == None: equal.next = end_next else: greater.next = end_next prev_start.next = lesser_start.next return equal_start.next, equal rek_qsort(start, None) return start.next def tab2list(A): H = Node() C = H for i in range(len(A)): X = Node() X.value = A[i] C.next = X C = X return H.next def printlist(L): while L != None: print(L.value, "->", end=" ") L = L.next print("|") # seed(42) n = 10 T = [randint(1, 10) for i in range(10)] L = tab2list(T) print("przed sortowaniem: L =", end=" ") printlist(L) L = qsort(L) print("po sortowaniu : L =", end=" ") printlist(L) if L == None: print("List jest pusta, a nie powinna!") exit(0) P = L while P.next != None: if P.value > P.next.value: print("Błąd sortowania") exit(0) P = P.next print("OK")
# Created by Marcin "Cozoob" Kozub at 20.04.2021 08:45 def can_construct(target, words): memo = [0 for _ in range(len(target) + 1)] memo[0] = True def rec_can_construct(target, words, memo): if target == "": return True if memo[len(target)] != 0: return memo[len(target)] for i in range(len(words)): word = words[i] flag = True if word[0] == target[0] and len(word) <= len(target): for j in range(1, len(word)): if word[j] != target[j]: flag = False if flag == True: curr_target = rec_can_construct(target[len(word):], words, memo) if curr_target == True: memo[len(target)] = True return True memo[len(target)] = False return False return rec_can_construct(target, words, memo) if __name__ == '__main__': # print(can_construct("abcdef", ["ab", "abc", "cd", "def", "abcd"])) # True # print(can_construct("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"])) # False # print(can_construct("enterapotentpot", ["a", "p", "ent", "enter", "ot", "o", "t"])) # True print(can_construct("eeeeeeeeeeeeeeeeeeeeeef", ["e", "ee", "eee", "eeee", "eeeee", "eeeeee"])) # False
# zlozonosc liniowa ! jeszcze lepsza niz nlgn !!! # O(n) def find_maximum_subarray(array): sum = 0 maxSum = array[0] for i in range(len(array)): if array[i] > array[i] + sum: sum = array[i] else: sum += array[i] # sum = max(array[i], array[i] + sum) if sum > maxSum: maxSum = sum return maxSum if __name__ == '__main__': # wynik dobry to indeksy miedzy [7,10] o sumie = 43 T = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7] # tablica B z tylko ujemnymi B = [-13, -3, -25, -20, -3, -16, -23, -18, -20, -7, -12, -5, -22, -15, -4, -7] print(T) print(find_maximum_subarray(T)) print(B) print(find_maximum_subarray(B))
# zlozonosc pesymistyczna n^2 def insertion_sort(A): for j in range(1, len(A)): key = A[j] # Wstaw A[j] w posortowany ciąg A[0,...,j-1] i = j - 1 while i >= 0 and A[i] > key: A[i + 1] = A[i] i -= 1 A[i + 1] = key def insertion_sortV2(A, left, right): for j in range(left + 1, right + 1): key = A[j] # Wstawiam A[j] w posortowany ciag A[0,...,j-1] i = j - 1 while i >= 0 and A[i] > key: A[i + 1] = A[i] i -= 1 A[i + 1] = key if __name__ == '__main__': A = [5,2,4,6,1,3] print(A) insertion_sortV2(A, 1, 4) # insertion_sort(A) print(A)
from queue import Queue # Created by Marcin "Cozoob" Kozub at 08.05.2021 16:32 # Implementacja BFS dla grafu w postaci list sąsiedztwa # repr. listowa O(V + E), repr. macierzowa O(V^2) def bfs(G, s): n = len(G) queue = Queue() visited = [False for _ in range(n)] queue.put(s) visited[s] = True while not queue.empty(): u = queue.get() for v in G[u]: if not visited[v]: visited[v] = True queue.put(v)
#!/usr/bin/python3 """takes in the name of a state as an arg lists all cities of that state using the database hbtn_0e_4_usa""" import MySQLdb import sys def filter_cities(): """takes 3 arguments argv to list from db argv[1]: mysql username argv[2]: mysql password argv[3]: database name argv[4]: state name """ db = MySQLdb.connect(host="localhost", port=3306, user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) """creates a cursor and executes query""" cur = db.cursor() cmd = """SELECT cities.name FROM cities, states WHERE BINARY states.name = %s AND cities.state_id = states.id ORDER BY cities.id ASC""" cur.execute(cmd, (sys.argv[4],)) states = cur.fetchall() print(", ".join(i[0] for i in states)) """closes cursor and db""" cur.close() db.close() if __name__ == "__main__": filter_cities()
#!/usr/bin/python3 def best_score(a_dictionary): best_n = 0 winner = None if type(a_dictionary) is dict: for (key, value) in a_dictionary.items(): if value > best_n: best_n = value winner = key return winner
#!/usr/bin/python3 """lists all cities from the db hbtn_0e_4_usa""" import MySQLdb import sys def cities_by_states(): """takes 3 arguments argv to list from db argv[1]: mysql username argv[2]: mysql password argv[3]: database name """ db = MySQLdb.connect(host="localhost", port=3306, user=sys.argv[1], passwd=sys.argv[2], db=sys.argv[3]) """creates a cursor and executes query""" cur = db.cursor() cur.execute("SELECT cities.id, cities.name, states.name FROM cities\ JOIN states ON cities.state_id = states.id\ ORDER BY cities.id ASC") for i in cur.fetchall(): print(i) """closes cursor and db""" cur.close() db.close() if __name__ == "__main__": cities_by_states()
#!/usr/bin/python3 """ base.py module """ import json class Base: """ Base class """ __nb_objects = 0 def __init__(self, id=None): """class constructor """ if id is not None: self.id = id else: Base.__nb_objects += 1 self.id = Base.__nb_objects @staticmethod def to_json_string(list_dictionaries): """Returns the JSON representation of str (list of dict) """ if list_dictionaries is None or len(list_dictionaries) == 0: return "[]" return json.dumps(list_dictionaries) @classmethod def save_to_file(cls, list_objs): """write an object to a text file using a JSON""" with open(cls.__name__ + ".json", "w", encoding="utf-8") as f: if list_objs is None: f.write("[]") else: f.write(cls.to_json_string([i.to_dictionary() for i in list_objs])) @staticmethod def from_json_string(json_string): """returns a str dict list represented by a JSON""" if json_string is None or json_string == "[]": return [] return json.loads(json_string) @classmethod def create(cls, **dictionary): """returns an instance with all attributes already set""" if cls.__name__ == "Rectangle": dum = cls(1, 1) if cls.__name__ == "Square": dum = cls(1) dum.update(**dictionary) return dum @classmethod def load_from_file(cls): """adding the class method that returns a list of instances""" try: with open(cls.__name__ + ".json", "r", encoding="UTF-8") as f: tmp = cls.from_json_string(f.read()) except FileNotFoundError: return [] return [cls.create(**d) for d in tmp]
import random for i in range(1): a=random.randint(1,10) turns= 3 if a%2==0: print("Hint - Number is even") else: print("Hint - Number is odd") for j in range(turns): guess=int(input('Guess a number between 1-10:')) if a==guess: print("Congrats!You won") break else: print("Sorry!Lose") j+=1
""" File containing the Population class, which contains a group of Chromosomes for training in the genetic algorithm. """ import random from lib.genetic_algorithm.chromosome import Chromosome class Population(): # pylint: disable=missing-class-docstring DEFAULT_MUTATION_CHANCE = 0.075 def __init__(self, population, mutation_chance=DEFAULT_MUTATION_CHANCE): """ Initializes a Population of chromosomes. """ assert len(population) % 4 == 0 for chromosome in population: assert isinstance(chromosome, Chromosome) self.population = population self.mutation_chance = mutation_chance self.generations = 0 def run(self, generations): """ This method will run the genetic algorithm on the population for the given number of generations. """ cut = len(self.population) // 2 for _ in range(generations): # Sort the population of chromosomes by their fitness population_by_fitness = sorted( self.population, key=lambda gene: gene.get_fitness()) print('Generation: {}'.format(self.generations)) for member in population_by_fitness: print(member) # Select the top half of the fittest members. fittest = population_by_fitness[cut:] # Shuffle and cross breed the fittest members. random.shuffle(fittest) for i in range(0, cut, 2): # Add two children so the population size remains the same. fittest += [fittest[i].cross( fittest[i + 1], self.mutation_chance)] fittest += [fittest[i].cross( fittest[i + 1], self.mutation_chance)] self.population = fittest for chromosome in self.population: chromosome.recalculate_fitness() self.generations += 1 def get_fittest_member(self): """ Returns the fittest member present in the population. """ return sorted(self.population, key=lambda gene: gene.get_fitness())[-1]
my_list = [] print(list(number for number in range(100))) print(list(number for number in range(100) if number % 2 == 0)) print(list(number for number in range(1, 100, 2))) set1 = {number ** 2 for number in range(100) if number % 2 == 0} print(sorted(set1)) my_dictionary = { '' } print({k: k ** 2 for k in [1, 2, 3]})
class Sum: @staticmethod def addition(num1, num2): return num1 * num2 @classmethod def addition(cls, num1, num2): cls.num1 = num1 cls.num2 = num2 return num1 + num2 print(Sum.addition(2, 3)) object1 = Sum() print(object1.addition(10, 10))
# import sys # import random # # while True: # try: # sys_random_number = # print("Guess a number between 1 to 10: ") # # # if 11 > user_number > 1: # if user_number == sys_random_number: # break # else: # print('please enter number between 1-10') # continue # except ValueError: # print('please enter number between 1-10') # # sys_random_number = random.randint(1, 10) # # while user_number != sys_random_number: # # print("Guess the number between 1 to 10: ") # user_number = sys.argv[1] # sys_random_number = random.randint(1, 10) # if user_number != sys_random_number: # continue # else: # print(f'Bingooo you number is {user_number} and system number is {sys_random_number}') # break
# '''Higher order function is a function which # either accepts the function as parameter or return the function for example MAP # or # def anyFunction(function1): # do some operation # ''' def any_function(function1): print(f"what were you expecting") return function1() # print(f"what will function return to you {return1} ") def some_other_function(): print( f"what were you expecting") # return 2 + 3 # any_function(some_other_function) @any_function def hello(): print("helooooooo")
import numpy as np # The Person class defines the base class that Employees and Passengers inherit attributes from class Person(object): def __init__(self, first, last, luggage): self.first_name = first self.last_name = last self.luggage_list = luggage def set_first(self, first): self.first_name = first def set_last(self, last): self.last_name = last def set_luggage(self, luggage): self.luggage_list = luggage def get_first(self): return self.first_name def get_last(self): return self.last_name def get_luggage(self): return self.luggage_list def get_name(self): return "%s, %s" % (self.last_name, self.first_name) # Concatenate the first and last name # Emplopyee class adds the position attribute to a Person class Employee(Person): def __init__(self, first, last, luggage, position): super().__init__(first, last, luggage) # Uses super() as a shortcut for referencing the Person class self.position = position def set_position(self, position): self.position = position def get_position(self): return self.position def __str__(self): return "%s is serving as %s for this flight." % (self.get_name(), self.position) # Passenger class adds the seat and seat type attributes to a Person class Passenger(Person): def __init__(self, first, last, luggage, seat_class, seat): super().__init__(first, last, luggage) # Uses super() as a shortcut for referencing the Person class self.seat_class = seat_class self.seat = seat def set_seat_class(self, seat_class): self.seat_class = seat_class def set_seat(self, seat): self.seat = seat def get_seat_class(self): return self.seat_class def get_seat(self): return self.seat def __str__(self): return "%s is flying %s in seat %s" % (self.get_name(), self.seat_class, self.seat) # The manifest class stores a collection of both the passengers and crew members. # It allows the creation of new Crew members and Passengers as well as their removal. # It also keeps a tally of the total number of people in the manifest. class Manifest(object): ON_BOARD = 0 def __init__(self): self.__crew: [Employee] = [] # Type the contents of the list self.__passengers: [Passenger] = [] # Type the contents of the list def add_crew(self, first, last, luggage, position): self.__crew.append(Employee(first, last, luggage, position)) Manifest.ON_BOARD = Manifest.ON_BOARD + 1 # Increment the manifest count def add_passenger(self, first, last, luggage, seat_class, seat): self.__passengers.append(Passenger(first, last, luggage, seat_class, seat)) Manifest.ON_BOARD = Manifest.ON_BOARD + 1 # Increment the manifest count def remove_crew(self, first, last): for i in self.__crew: if i.get_name() == "%s, %s" % (last, first): self.__crew.remove(i) Manifest.ON_BOARD = Manifest.ON_BOARD - 1 # Decrement the manifest count def remove_passenger(self, first, last): for i in self.__passengers: if i.get_name() == "%s, %s" % (last, first): self.__passengers.remove(i) Manifest.ON_BOARD = Manifest.ON_BOARD - 1 # Decrement the manifest count def __str__(self): crew_string = "" passenger_string = "" for x in self.__crew: crew_string = crew_string + "%s\n" % x.__str__() for y in self.__passengers: passenger_string = passenger_string + "%s\n" % y.__str__() return "There are %d souls on board.\n\nServing as crew:\n%s\n\nPassenger list:\n%s" % \ (Manifest.ON_BOARD, crew_string, passenger_string) # Route defines the parameters of the flight class Route(object): def __init__(self, start, destination, depart, arrive): self.__start = start self.__destination = destination self.__departure_stamp = depart self.__arrival_stamp = arrive def set_start(self, start): self.__start = start def set_destination(self, dest): self.__destination = dest def set_departure(self, depart): self.__departure_stamp = depart def set_arrival(self, arrival): self.__arrival_stamp = arrival def get_start(self): return self.__start def get_destination(self): return self.__destination def get_departure(self): return self.__departure_stamp def get_arrival(self): return self.__arrival_stamp def __str__(self): return "departs from %s at %s and is due to arrive in %s at %s." % \ (self.__start, self.__departure_stamp, self.__destination, self.__arrival_stamp) # Plane defines the attributes of the plane being used for a particular Flight class Plane(object): def __init__(self, model, capacity): self.__model = model self.__capacity = capacity def set_model(self, model): self.__model = model def set_capacity(self, capacity): self.__capacity = capacity def get_model(self): return self.__model def get_capacity(self): return self.__capacity def __str__(self): return "Plane model: %s carrying capacity: %d persons" % (self.__model, self.__capacity) # The Flight class inherits properties from Route, Plane, and Manifest # The manifest is empty by default and will be populated later. # The flight will have a predetermined schedule and plane model for the flight in order to build a manifest # Therefore, route and plane will be intialized at obejct instantiation. class Flight(Route, Plane, Manifest): def __init__(self, start, destination, depart, arrive, model, capacity): Manifest.__init__(self) Route.__init__(self, start, destination, depart, arrive) Plane.__init__(self, model, capacity) self.__id = np.random.randint(0, 4000 + 1, 1) def __str__(self): return "Flight No: %d\n%s\n%s\n%s" % (self.__id, Route.__str__(self), Plane.__str__(self), Manifest.__str__(self)) # Instantiate an object with Route and Plane parameters a = Flight("MCI", "LAX", "15:34 14Feb2019", "17:14 14Feb2019", "Airbus A319", 160) # Add People to the manifest; both crew and passengers a.add_crew("Jim", "Jones", 1423, "Pilot") a.add_crew("Larry", "Llewynn", 1687, "Pilot") a.add_crew("Cathy", "Catzman", 3416, "Flight Attendant") a.add_crew("Tom", "Thomas", 1463, "Flight Attendant") a.add_crew("Frank", "Franklin", 8142, "Flight Attendant") a.add_passenger("Lucy", "Liu", 2875, "First Class", "1A") a.add_passenger("Bernie", "Sanders", 1684, "Economy", "17C") # Print out information about the flight, including the manifest print(a.__str__())
'''utility generators and functions related to the fibonacci sequence''' from typing import Generator def fibonacci_iterator(a: int = 1, b: int = 1) -> Generator[int, None, None]: '''iterates through the fibonaccie sequence using starting values''' while True: yield a a, b = b, a + b
from tkinter import * from tkinter import messagebox from pyrogram import Client from pyrogram.api import functions import asyncio """Author: Ido Nidbach begin: 22.5.2019 finish: 10.6.2019 This program basically allows you to do number of things. it allows you to send messages, create group chats and adding users to it, send an image or a sticker and send your message in a time of your choice up to 24 hours. To start using the program you'll need three main things: 1. choosing a name for your session 2. API ID 3. API HASH The first one is easy, the other two requires you to enter the next url: "my.telegram.org" in this site you enter the phone number of your new user in telegram. you then go in "development tools" and fill the requested fields. you have now created your new app! congratulations! After creating your new app you receive both API ID and API HASH. you are now ready for using the program's client method. you enter the arguments for the client method in order to create a user. in this program, the client method is called: user. Once you enter the arguments for the user you can start using the program features. the arguments are: 1. name of the session you connect with your user(you choose the name of the session). 2. your API ID number which you get in "my.telegram.org". 3. your API HASH code as a string which you get in "my.telegram.org". After entering those arguments you'll need to enter your proxy's hostname and port number. you can now use the program's features! The first feature is creating a new group chat with up to 10 users. you enter a name for your new group and write what it's all about. next you fill in the fields that sits next the "invite users buttons". in each field you enter one username. minimum 2 users. lets say you've entered 2 usernames, in order to invite them you'll need to enter the group's link(make sure to know if your group is private or not and then you'll know it's link. so you enter the link, then you press on "invite 2 users" button. the users have been added to your group chat. The next feature is message sending in a couple of aspects: 1. sending a regular message 2. sending an image 3. sending a sticker 4. sending a timed message You enter the username of the person who receives the message. then you enter your message or image link or sticker code if your message is a text message you press "send message", if it's an image you press "send image" and if it's a sticker you press "send sticker" In order to send a timed message you enter the receiver's username and your message(or image link or sticker code) and press on time button you choose, for instance if you want to send the message one minute from now you press "send in 1 minute". Enjoy your Telepy experience and do not spam! """ # open the program window Telepy app = Tk() app.title("Telepy") app.configure(background="light blue") app.geometry("1100x750") # saves the session's name, API ID and API HASH in the text file "user info.txt" # and then deletes the input for inserting new input def save_info(): session_info = entry_session.get() api_id_info = entry_api_id.get() api_id_info = str(api_id_info) api_hash_info = entry_api_hash.get() file = open("user info.txt", "w") file.write(session_info) file.write("\n") file.write(api_id_info) file.write("\n") file.write(api_hash_info) file.close() print(messagebox.showinfo(title="message", message="user info saved in a text file: 'user info.txt'")) entry_session.delete(0, END) entry_api_id.delete(0, END) entry_api_hash.delete(0, END) # the programs's labels(headers) in the user and group sections Label(app, text="Welcome to Telepy!!", bg="green", fg="blue", font="Times 20").grid(row=0, column=0, sticky=W) Label(app, text="Send messages to Telegram via Telepy!", bg="grey", fg="black", font="Times 13").grid(row=1, column=0, sticky=W) Label(app, text="For creating a user", bg="light green", fg="black", font="Arial 15").grid(row=2, column=0, sticky=W) Label(app, text="Enter your session's name:", bg="blue", fg="black", font="Arial 10").grid(row=3, column=0, sticky=W) Label(app, text="Enter your Api ID:", bg="blue", fg="black", font="Arial 10").grid(row=4, column=0, sticky=W) Label(app, text="Enter your Api Hash:", bg="blue", fg="black", font="Arial 10").grid(row=5, column=0, sticky=W) Label(app, text="Enter your proxy hostname:", bg="blue", fg="black", font="Arial 10") \ .grid(row=7, column=0, sticky=W) Label(app, text="Enter your proxy port:", bg="blue", fg="black", font="Arial 10").grid(row=8, column=0, sticky=W) Label(app, text="-----------------------------------------", bg="light blue", fg="black") \ .grid(row=9, column=0, sticky=W) Label(app, text="For creating a group:", bg="light green", fg="black", font="Arial 15") \ .grid(row=10, column=0, sticky=W) Label(app, text="Enter a name for your group:", bg="blue", fg="black", font="Arial 10").grid(row=11, column=0, sticky=W) Label(app, text="What is your group all about:", bg="blue", fg="black", font="Arial 10") \ .grid(row=12, column=0, sticky=W) Label(app, text="Enter the group's link:", bg="blue", fg="black", font="Arial 10") \ .grid(row=14, column=0, sticky=W) Label(app, text="usernames:", bg="light green", fg="black", font="Arial 10").grid(row=16, column=1, sticky=W) # setting the API ID and port as integers api_id = IntVar() port = IntVar() # the program's entry inputs(user and group section) entry_session = Entry(app, width=30, bg="grey", fg="blue", font="Arial 10") entry_session.grid(row=3, column=1, sticky=W) entry_api_id = Entry(app, textvariable=api_id, width=30, bg="grey", fg="blue", font="Arial 10") entry_api_id.grid(row=4, column=1, sticky=W) entry_api_hash = Entry(app, width=35, bg="grey", fg="blue", font="Arial 10") entry_api_hash.grid(row=5, column=1, sticky=W) entry_hostname = Entry(app, width=30, bg="grey", fg="blue", font="Arial 10") entry_hostname.grid(row=7, column=1, sticky=W) entry_port = Entry(app, textvariable=port, width=30, bg="grey", fg="blue", font="Arial 10") entry_port.grid(row=8, column=1, sticky=W) entry_group_name = Entry(app, width=30, bg="grey", fg="blue", font="Arial 10") entry_group_name.grid(row=11, column=1, sticky=W) entry_group_description = Entry(app, width=30, bg="grey", fg="blue", font="Arial 10") entry_group_description.grid(row=12, column=1, sticky=W) entry_group_link = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") entry_group_link.grid(row=14, column=1, sticky=W) # username entry inputs(group section) username1 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username1.grid(row=17, column=1, sticky=W) username2 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username2.grid(row=18, column=1, sticky=W) username3 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username3.grid(row=19, column=1, sticky=W) username4 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username4.grid(row=20, column=1, sticky=W) username5 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username5.grid(row=21, column=1, sticky=W) username6 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username6.grid(row=22, column=1, sticky=W) username7 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username7.grid(row=23, column=1, sticky=W) username8 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username8.grid(row=24, column=1, sticky=W) username9 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username9.grid(row=25, column=1, sticky=W) username10 = Entry(app, width=20, bg="grey", fg="blue", font="Arial 10") username10.grid(row=26, column=1, sticky=W) # message section # labels(headers) and entry inputs message section Label(app, text="Enter the receiver's username here:", bg="blue", fg="black", font="Arial 10") \ .grid(row=0, column=2, sticky=W) Label(app, text="Enter your message here:", bg="blue", fg="black", font="Arial 10").grid(row=1, column=2, sticky=W) Label(app, text="Enter your image link here:", bg="blue", fg="black", font="Arial 10") \ .grid(row=2, column=2, sticky=W) Label(app, text="Enter you sticker code here:", bg="blue", fg="black", font="Arial 10") \ .grid(row=3, column=2, sticky=W) receiver_user_entry = Entry(app, width=30, bg="white", fg="black", font="Arial 10") receiver_user_entry.grid(row=0, column=3, sticky=W) message_entry = Entry(app, width=50, bg="white", fg="black", font="Arial 10") message_entry.grid(row=1, column=3, sticky=W) image_entry = Entry(app, width=30, bg="white", fg="black", font="Arial 10") image_entry.grid(row=2, column=3, sticky=W) sticker_entry = Entry(app, width=50, bg="white", fg="black", font="Arial 10") sticker_entry.grid(row=3, column=3, sticky=W) # send a regular message function def send_a_message_no_proxy(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get()) user.start() user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_a_message(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send_message(receiver_user_entry.get(), message_entry.get()) return # send an image function def send_an_image(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send_message(receiver_user_entry.get(), image_entry.get()) return # send a sticker function def send_a_sticker(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send_message(receiver_user_entry.get(), sticker_entry.get()) return # create a group function def create_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.CreateChannel(title=entry_group_name.get(), about=entry_group_description.get(), megagroup=True)) return # invite 2 users to a group def invite_2_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get())])) return # invite 3 users to a group def invite_3_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get()), user.resolve_peer(username3.get())])) return # invite 4 users to a group def invite_4_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get()), user.resolve_peer(username3.get()), user.resolve_peer(username4.get())])) return # invite 5 users to a group def invite_5_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get()), user.resolve_peer(username3.get()), user.resolve_peer(username4.get()), user.resolve_peer(username5.get())])) return # invite 6 users to a group def invite_6_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get()), user.resolve_peer(username3.get()), user.resolve_peer(username4.get()), user.resolve_peer(username5.get()), user.resolve_peer(username6.get())])) return # invite 7 users to a group def invite_7_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get()), user.resolve_peer(username3.get()), user.resolve_peer(username4.get()), user.resolve_peer(username5.get()), user.resolve_peer(username6.get()), user.resolve_peer(username7.get())])) return # invite 8 users to a group def invite_8_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get()), user.resolve_peer(username3.get()), user.resolve_peer(username4.get()), user.resolve_peer(username5.get()), user.resolve_peer(username6.get()), user.resolve_peer(username7.get()), user.resolve_peer(username8.get())])) return # invite 9 users to a group def invite_9_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get()), user.resolve_peer(username3.get()), user.resolve_peer(username4.get()), user.resolve_peer(username5.get()), user.resolve_peer(username6.get()), user.resolve_peer(username7.get()), user.resolve_peer(username8.get()), user.resolve_peer(username9.get())])) return # invite 10 users to a group def invite_10_users_to_group(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() user.send(functions.channels.InviteToChannel(channel=user.resolve_peer(entry_group_link.get()), users=[user.resolve_peer(username1.get()), user.resolve_peer(username2.get()), user.resolve_peer(username3.get()), user.resolve_peer(username4.get()), user.resolve_peer(username5.get()), user.resolve_peer(username6.get()), user.resolve_peer(username7.get()), user.resolve_peer(username8.get()), user.resolve_peer(username9.get()), user.resolve_peer(username10.get())])) return # Timing functions # each function with it's own time countdown by asyncio.sleep method which accepts the argument in seconds async def in_one_minute(): one_minute = await asyncio.sleep(60) return one_minute async def in_ten_minutes(): ten_minutes = await asyncio.sleep(600) return ten_minutes async def in_twenty_minutes(): twenty_minutes = await asyncio.sleep(1200) return twenty_minutes async def in_thirty_minutes(): thirty_minutes = await asyncio.sleep(1800) return thirty_minutes async def in_fourty_minutes(): forty_minutes = await asyncio.sleep(2400) return forty_minutes async def in_thifty_minutes(): fifty_minutes = await asyncio.sleep(3000) return fifty_minutes async def in_one_hour(): one_hour = await asyncio.sleep(3600) return one_hour async def in_two_hours(): two_hours = await asyncio.sleep(7200) return two_hours async def in_three_hours(): three_hours = await asyncio.sleep(10800) return three_hours async def in_four_hours(): four_hours = await asyncio.sleep(14400) return four_hours async def in_five_hours(): five_hours = await asyncio.sleep(18000) return five_hours async def in_six_hours(): six_hours = await asyncio.sleep(21600) return six_hours async def in_seven_hours(): seven_hours = await asyncio.sleep(25200) return seven_hours async def in_eight_hours(): eight_hours = await asyncio.sleep(28800) return eight_hours async def in_nine_hours(): nine_hours = await asyncio.sleep(32400) return nine_hours async def in_ten_hours(): ten_hours = await asyncio.sleep(36000) return ten_hours async def in_eleven_hours(): eleven_hours = await asyncio.sleep(39600) return eleven_hours async def in_twelve_hours(): twelve_hours = await asyncio.sleep(43200) return twelve_hours async def in_thirteen_hours(): thirteen_hours = await asyncio.sleep(46800) return thirteen_hours async def in_fourteen_hours(): fourteen_hours = await asyncio.sleep(50400) return fourteen_hours async def in_fifteen_hours(): fifteen_hours = await asyncio.sleep(54000) return fifteen_hours async def in_sixteen_hours(): sixteen_hours = await asyncio.sleep(57600) return sixteen_hours async def in_seventeen_hours(): seventeen_hours = await asyncio.sleep(61200) return seventeen_hours async def in_eighteen_hours(): eighteen_hours = await asyncio.sleep(64800) return eighteen_hours async def in_nineteen_hours(): nineteen_hours = await asyncio.sleep(68400) return nineteen_hours async def in_twenty_hours(): twenty_hours = await asyncio.sleep(72000) return twenty_hours async def in_twenty_one_hours(): twenty_one_hours = await asyncio.sleep(75600) return twenty_one_hours async def in_twenty_two_hours(): twenty_two_hours = await asyncio.sleep(79200) return twenty_two_hours async def in_twenty_three_hours(): twenty_three_hours = await asyncio.sleep(82800) return twenty_three_hours async def in_twenty_four_hours(): twenty_four_hours = await asyncio.sleep(86400) return twenty_four_hours # sending timed message functions # each function represents the time until the message will be sent def send_in_one_minute(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_one_minute()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_ten_minutes(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_ten_minutes()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_twenty_minutes(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_twenty_minutes()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_thirty_minutes(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_thirty_minutes()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_forty_minutes(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_fourty_minutes()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_fifty_minutes(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_thifty_minutes()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_one_hour(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_one_hour()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_two_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_two_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) def send_in_three_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_three_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_four_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_four_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_five_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_five_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_six_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_six_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_seven_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_seven_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_eight_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_eight_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_nine_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_nine_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_ten_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_ten_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_eleven_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_eleven_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_twelve_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_twelve_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_thirteen_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_thirteen_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_fourteen_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_fourteen_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_fifteen_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_fifteen_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_sixteen_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_sixteen_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_seventeen_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_seventeen_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_eighteen_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_eighteen_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_nineteen_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_nineteen_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_twenty_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_twenty_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_twenty_one_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_twenty_one_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_twenty_two_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_twenty_two_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_twenty_three_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_twenty_three_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return def send_in_twenty_four_hours(): user = Client(entry_session.get(), entry_api_id.get(), entry_api_hash.get(), proxy=dict(hostname=entry_hostname.get(), port=entry_port.get())) user.start() asyncio.run(in_twenty_four_hours()) user.send_message(receiver_user_entry.get(), message_entry.get()) return # The program's buttons register_button = Button(app, text="save info", command=save_info, width=12).grid(row=6, column=0, sticky=W) message_button = Button(app, text="send message", command=send_a_message, width=12)\ .grid(row=4, column=2, sticky=W) message_no_proxy_button = Button(app, text="send message without a proxy", command=send_a_message_no_proxy, width=25)\ .grid(row=4, column=3, sticky=W) image_button = Button(app, text="send image", command=send_an_image, width=12).grid(row=5, column=2, sticky=W) sticker_button = Button(app, text="send sticker", command=send_a_sticker, width=12) \ .grid(row=6, column=2, sticky=W) create_group_button = Button(app, text="create group", command=create_group, width=12) \ .grid(row=13, column=0, sticky=W) invitation_button1 = Button(app, text="invite 2 users to group", command=invite_2_users_to_group, width=20) \ .grid(row=17, column=0, sticky=W) invitation_button2 = Button(app, text="invite 3 users to group", command=invite_3_users_to_group, width=20) \ .grid(row=18, column=0, sticky=W) invitation_button3 = Button(app, text="invite 4 users to group", command=invite_4_users_to_group, width=20) \ .grid(row=19, column=0, sticky=W) invitation_button4 = Button(app, text="invite 5 users to group", command=invite_5_users_to_group, width=20) \ .grid(row=20, column=0, sticky=W) invitation_button5 = Button(app, text="invite 6 users to group", command=invite_6_users_to_group, width=20) \ .grid(row=21, column=0, sticky=W) invitation_button6 = Button(app, text="invite 7 users to group", command=invite_7_users_to_group, width=20) \ .grid(row=22, column=0, sticky=W) invitation_button7 = Button(app, text="invite 8 users to group", command=invite_8_users_to_group, width=20) \ .grid(row=23, column=0, sticky=W) invitation_button8 = Button(app, text="invite 9 users to group", command=invite_9_users_to_group, width=20) \ .grid(row=24, column=0, sticky=W) invitation_button9 = Button(app, text="invite 10 users to group", command=invite_10_users_to_group, width=20) \ .grid(row=25, column=0, sticky=W) send_message_1_minute = Button(app, text="send message in 1 minute", command=send_in_one_minute, width=30) \ .grid(row=8, column=2, sticky=W) send_message_10_minutes = Button(app, text="send message in 10 minutes", command=send_in_ten_minutes, width=30) \ .grid(row=9, column=2, sticky=W) send_message_20_minutes = Button(app, text="send message in 20 minutes", command=send_in_twenty_minutes, width=30).grid(row=10, column=2, sticky=W) send_message_30_minutes = Button(app, text="send message in 30 minutes", command=send_in_thirty_minutes, width=30).grid(row=11, column=2, sticky=W) send_message_40_minutes = Button(app, text="send message in 40 minutes", command=send_in_forty_minutes, width=30) \ .grid(row=12, column=2, sticky=W) send_message_50_minutes = Button(app, text="send message in 50 minutes", command=send_in_fifty_minutes, width=30) \ .grid(row=13, column=2, sticky=W) send_message_1_hour = Button(app, text="send message in 1 hour", command=send_in_one_hour, width=30) \ .grid(row=14, column=2, sticky=W) send_message_2_hours = Button(app, text="send message in 2 hours", command=send_in_two_hours, width=30) \ .grid(row=15, column=2, sticky=W) send_message_3_hours = Button(app, text="send message in 3 hours", command=send_in_three_hours, width=30) \ .grid(row=16, column=2, sticky=W) send_message_4_hours = Button(app, text="send message in 4 hours", command=send_in_four_hours, width=30) \ .grid(row=17, column=2, sticky=W) send_message_5_hours = Button(app, text="send message in 5 hours", command=send_in_five_hours, width=30) \ .grid(row=18, column=2, sticky=W) send_message_6_hours = Button(app, text="send message in 6 hours", command=send_in_six_hours, width=30) \ .grid(row=19, column=2, sticky=W) send_message_7_hours = Button(app, text="send message in 7 hours", command=send_in_seven_hours, width=30) \ .grid(row=20, column=2, sticky=W) send_message_8_hours = Button(app, text="send message in 8 hours", command=send_in_eight_hours, width=30) \ .grid(row=21, column=2, sticky=W) send_message_9_hours = Button(app, text="send message in 9 hours", command=send_in_nine_hours, width=30) \ .grid(row=22, column=2, sticky=W) send_message_10_hours = Button(app, text="send message in 10 hours", command=send_in_ten_hours, width=30) \ .grid(row=23, column=2, sticky=W) send_message_11_hours = Button(app, text="send message in 11 hours", command=send_in_eleven_hours, width=30) \ .grid(row=24, column=2, sticky=W) send_message_12_hours = Button(app, text="send message in 12 hours", command=send_in_twelve_hours, width=30) \ .grid(row=25, column=2, sticky=W) send_message_13_hours = Button(app, text="send message in 13 hours", command=send_in_thirteen_hours, width=30) \ .grid(row=8, column=3, sticky=W) send_message_14_hours = Button(app, text="send message in 14 hours", command=send_in_fourteen_hours, width=30) \ .grid(row=9, column=3, sticky=W) send_message_15_hours = Button(app, text="send message in 15 hours", command=send_in_fifteen_hours, width=30) \ .grid(row=10, column=3, sticky=W) send_message_16_hours = Button(app, text="send message in 16 hours", command=send_in_sixteen_hours, width=30) \ .grid(row=11, column=3, sticky=W) send_message_17_hours = Button(app, text="send message in 17 hours", command=send_in_seventeen_hours, width=30) \ .grid(row=12, column=3, sticky=W) send_message_18_hours = Button(app, text="send message in 18 hours", command=send_in_eighteen_hours, width=30) \ .grid(row=13, column=3, sticky=W) send_message_19_hours = Button(app, text="send message in 19 hours", command=send_in_nineteen_hours, width=30) \ .grid(row=14, column=3, sticky=W) send_message_20_hours = Button(app, text="send message in 20 hours", command=send_in_twenty_hours, width=30) \ .grid(row=15, column=3, sticky=W) send_message_21_hours = Button(app, text="send message in 21 hours", command=send_in_twenty_one_hours, width=30) \ .grid(row=16, column=3, sticky=W) send_message_22_hours = Button(app, text="send message in 22 hours", command=send_in_twenty_two_hours, width=30) \ .grid(row=17, column=3, sticky=W) send_message_23_hours = Button(app, text="send message in 23 hours", command=send_in_twenty_three_hours, width=30) \ .grid(row=18, column=3, sticky=W) send_message_24_hours = Button(app, text="send message in 24 hours", command=send_in_twenty_four_hours, width=30) \ .grid(row=19, column=3, sticky=W) app.mainloop()
number = input("Enter your number: ") test_number = number % 2 if test_number > 0 print("Your number is odd!") else if test_number = 0 print("Your number is even!") else print("Choose a number!")
def pay(hours, rate): pay = hours * rate print (pay) def overpay(hours, rate): overpay = hours * rate + ((hours - 40)*(rate *1.5)) print (overpay) try: hours = float(input('Enter hours: ')) rate = float(input('Enter rate: ')) except: print ("") print ('Please enter numeric value!') quit() if hours > 40: pay = hours * rate + (hours - 40) * rate * 0.5 else: pay = hours * rate print ("") print('Pay: $',pay)
# Uses python3 # Given a list of price per clicks (a) and a list of clicks per day (b), find the total revenue after values from a and b are paired to maximize revenue # Safe move: find the highest click per pay price, and associate that with the highest available click per day import sys def max_dot_product(a, b): revenue = 0 while len(a) > 0 and len(b) > 0: greatest_price = max(a) greatest_frequency = max(b) a.remove(greatest_price) b.remove(greatest_frequency) revenue += (greatest_price * greatest_frequency) return revenue if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] a = data[1:(n + 1)] b = data[(n + 1):] print(max_dot_product(a, b))
#Uses python3 #runtime is quadratic #swap based on index values def swap(a, x, y): temp = a[x] a[x] = a[y] a[y] = temp def swap_sort(a): for i in range(0, len(a)): min_index = i for j in range(i+1, len(a)): if a[j] < a[min_index]: min_index = j swap(a, min_index, i) return a print(swap_sort([5,3,8,7,1,9]))
# Uses python3 import sys from math import floor def mergeit(left, right): result = [] leftIdx = 0 rightIdx = 0 while leftIdx < len(left) and rightIdx < len(right): if left[leftIdx] <= right[rightIdx]: result.append(left[leftIdx]) leftIdx += 1 else: result.append(right[rightIdx]) rightIdx += 1 if leftIdx < len(left): result.extend(left[leftIdx:]) if rightIdx < len(right): result.extend(right[rightIdx:]) return result def mergeSort(a): if len(a) <= 1: return a mid = floor(len(a)/2) b = mergeSort(a[:mid]) c = mergeSort(a[mid:]) return mergeit(b,c) # print(mergeSort([65,1,3,6,8,7])) if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) for i in (mergeSort(a)): print(i)
import matplotlib.pyplot as plt from unsupervised_learning.clustering.gaussian_mixture import GaussianMixture from sklearn.datasets import make_blobs def main(): X, y = make_blobs(n_samples=100, cluster_std=2, random_state=42) model = GaussianMixture(); model.fit(X) plt.scatter(X[:, 0], X[:, 1], c=model.labels_) plt.title("Mixture of gaussians") plt.xlabel("x") plt.ylabel("y") plt.show() if __name__ == "__main__": main();
from unsupervised_learning.clustering.kmeans import Kmeans from sklearn.datasets import make_blobs import matplotlib.pyplot as plt def main(): #Test the kmeans algorithm using 100 samples taken from 3 blobs. X, y = make_blobs(n_samples=100, random_state=42) model = Kmeans(init='kmeans++') model.fit(X) plt.title("Kmeans on 100 points and 3 centroids") plt.scatter(X[:, 0], X[:, 1], c = model.labels_) plt.xlabel("x") plt.ylabel("y") plt.show() if __name__ == "__main__": main();
#!/usr/bin/python #Title: Assignment2---Question32 #Author:Merin #Version:1 #DateTime:24/11/2018 4:30pm #Summary:Write a program to perform following operations on List. Create three lists as List1,List2 and List3 having 5 city names each list. # a. Find the length city of each list element and print city and length # b. Find the maximum and minimum string length element of each list # c. Compare each list and determine which city is biggest & smallest with length. # d. Delete first and last element of each list and print list contents. #Function Body for 'findLength' def findLength(listL): for x in range(5): print listL[x],"\t\t\t",len(listL[x]) #Function Body for 'findMinMax' def findMinMax(listL,y): length = [] for x in range(5): length.append(len(listL[x])) for x in range(5): if length[x]==min(length): print listL[x],"has minimum length in List",y elif length[x]==max(length): print listL[x],"has maximum length in List",y #Function Body for 'findMinMaxinAll' def findMinMaxinAll(list1,list2,list3): minLen=100;maxLen=0 for y in range(3): if y==0: listL=list1 elif y==1: listL=list2 else: listL=list3 length = [] for x in range(5): length.append(len(listL[x])) for x in range(5): if length[x]==min(length)and length[x]<minLen: minLen=length[x];minElement=listL[x] elif length[x]==max(length)and length[x]>maxLen: maxLen=length[x];maxElement=listL[x] print "\nCity with smallest length among 3 lists:",minElement print "City with biggest length among 3 lists:",maxElement # List Creation list1 =['Zurich','Lucern','Interlaken','Lauterbrunnen','Lugano'] list2=['Bangalore','Delhi','Kochi','Mumbai','Pune'] list3=['London','Leeds','Manchester','Southampton','Watford'] #a.Find the length city of each list element and print city and length print "City Name\t\tLength" findLength(list1) findLength(list2) findLength(list3) #b.Find the maximum and minimum string length element of each list print "\nthe maximum and minimum string length element of each list:" findMinMax(list1,1) findMinMax(list2,2) findMinMax(list3,3) #c.Compare each list and determine which city is biggest & smallest with length. findMinMaxinAll(list1,list2,list3) #d.Delete first and last element of each list and print list contents list1.pop(0);list1.pop() list2.pop(0);list2.pop() list3.pop(0);list3.pop() print "\nLists after deleting first & last element:" print "List1-->",list1 print "List2-->",list2 print "List3-->",list3
#!/usr/bin/python #Title: Assignment2---Question35 #Author:Merin #Version:1 #DateTime:26/11/2018 2:45pm #Summary:Create Tuple as specified below; # a) Create a Tuple tup1 with days in a week & print the tuple elements # b) Create a Tuple tup2 with months in a year and concatenate it with tup1 # c) Create 3 tuples( tup1,tup2,tup3) with numbers and determine which is greater. # d) Try to delete an individual element in tup1 and try deleting complete Tuple -tup1 notice the error type you get. # e) Insert new element in to tuple by typecasting it to List #a)Create a Tuple tup1 with days in a week tup1 =('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday') print "Tuple 1:",tup1 #b)Create a Tuple tup2 with months in a year and concatenate it with tup1 tup2=('January','February','March','April','May','June','July','August','September','October','November','December') print "Tuple 2:",tup2 print "Concatenation of Tuple 1 & 2:",tup1+tup2 #c)Create 3 tuples( tup1,tup2,tup3) with numbers and determine which is greater. tup1=(1,2,3,4,5,6,7,8,9,10) tup2=(10,2,30,4,50,6,70,8,90,10) tup3=(1,20,3,40,5,60,7,80,9,100) print "tup1:",tup1 print "tup2:",tup2 print "tup3:",tup3 if cmp(tup1,tup2)>0 and cmp(tup1,tup3)>0: print tup1," is the greatest" elif cmp(tup2,tup1)>0 and cmp(tup2,tup3)>0: print tup2," is the greatest" elif cmp(tup3,tup1)>0 and cmp(tup3,tup1)>0: print tup3," is the greatest" else: print "All are equal" #d)Try to delete an individual element in tup1 and try deleting complete Tuple -tup1 notice the error type you get. #tup1.pop(2) #print tup1 # Error Message: # Traceback (most recent call last): # File "C:/Users/deepu/Desktop/MERIN/PYTHON/ass2Q35.py", line 41, in <module> # tup1.pop(2) # AttributeError: 'tuple' object has no attribute 'pop' del tup1 #print "tup1:",tup1 # Error Messgae: # Traceback (most recent call last): # File "C:/Users/deepu/Desktop/MERIN/PYTHON/ass2Q35.py", line 49, in <module> # print "tup1:",tup1 # NameError: name 'tup1' is not defined #e) Insert new element in to tuple by typecasting it to List tempList=list(tup2) tempList.insert(2,'Inserted Element') tup2=tuple(tempList) print "tup2 with an inserted element( by typecasting it to List):",tup2
#!/usr/bin/python #Title: Assignment2---Question25 #Author:Merin #Version:1 #DateTime:28/11/2018 3:20pm #Summary: Write a program to print the different data types (Numbers, strings characters) using the Format symbols #string name="Python" print "%s is a programming language"%name #integer number=1234 print "%d is a integer number"%number #floating point number number=1.234 print "%f is a floating point number"%number #long number number=0xC0DE print "%x is a hexadecimal number"%number #exponential number=1.234 print "%e is a floating point number"%number
#!/usr/bin/env python """ This code was written by Chris Suarez as a contribution to fivethirtyeight.com. This is a simultation to solve a problem posed in the weekly segement called the riddler! The link for this problem is here: https://fivethirtyeight.com/features/santa-needs-some-help-with-math/ """ import numpy import time import sys import math # Function to simulate the songs the elves would hear in a single shift def shift_simulator(playlist_size): songs_played = list() # Playing 100 songs randomly from the playlist given the playlist_size for song_no in range(1, 100): # Picking random song to play next song = numpy.random.randint(1, playlist_size) # If the song has been played then break and return failure to break snowballs! # Else add the specific song to the list of songs that have been played so far this shift if song in songs_played: return False else: songs_played.append(song) # If we make it through the list then return success of shift without snowballs! return True # Main simulation function if __name__=='__main__': # Recording simulation input from user start_time = time.time() playlist_size_l = int(raw_input("Size of playlist (low)? ")) playlist_size_h = int(raw_input("Size of playlist (high)? ")) trials = int(raw_input("How many shift simulations do you want to run for each playlist size? ")) # Running trials of varying playlist sizes for playlist_size in range(playlist_size_l, playlist_size_h): # Failure count snowballed = 0 print("...") sys.stdout.write("\n\n\n\n") # Run the set of trials for the given playlist size for t in range(0,trials): # Call shift simulator safe_shift = shift_simulator(playlist_size) # Record number of failures if not safe_shift: snowballed += 1 run_time = time.time() - start_time # Live output of stats and estimated simulation time sys.stdout.write("\033[F\033[F\033[F\033[F") sys.stdout.write("Shifts worked: " + str(t + 1)) sys.stdout.write("\nSnowballed Shifts: " + str(snowballed)) sys.stdout.write("\nRun time: " + str(math.floor(run_time * 10) / 10) + " seconds ") sys.stdout.write("\nEstimated time remaining: " + str(math.floor((trials*run_time / (t+1) - run_time)*10) / 10) + " seconds ") sys.stdout.write("\n...") sys.stdout.flush() # Print final empirical probability of failure to prevent snowballs with given playlist size print("\nSampled probability of snowballed Shifts: " + str(snowballed/float(trials)) + " Playlist size: " + str(playlist_size))
#!/usr/bin/python import sys def help_screen(): print """ ---------------------------------------------------------------- FASTA TO CSV: Turn a FASTA into a CSV file! by D. Gonzales This program takes a multi-fasta file and converts it to a csv file. Input: >seq1 ATGC >seq2 ATTC Output: seq1,ATGC seq2,ATTC Usage: fasta_csv.py [-h] [-i in] [-o out] [-h] = This helpful help screen. [-i] = FASTA input file. [-o] = CSV output file. *Labels should not contain white spaces. *Requirements: python 2.7, sys, getopt, biopython. ----------------------------------------------------------------""" sys.exit() def fasta_csv(infile,outfile): from Bio import SeqIO infile=SeqIO.index(infile,'fasta') keys=infile.keys() outfile=open(outfile,'w') outfile.write('key,seq\n') for key in keys: outfile.write(key+','+str(infile[key].seq)+'\n') outfile.close() def main(): import getopt try: opts,args=getopt.getopt(sys.argv[1:],'i:o:h') except getopt.GetoptError as err: print str(err) print 'Usage: fasta_csv.py [-h] [-i in] [-o out]' sys.exit() for o,a in opts: if o=='-h': help_screen() if o=='-i': infile=str(a) if o=='-o': outfile=str(a) options=[opt[0] for opt in opts] for option in ['-i','-o']: if option not in options: print 'missing arguement' print 'Usage: fasta_csv.py [-h] [-i in] [-o out]' sys.exit() fasta_csv(infile,outfile) if __name__=='__main__': main() sys.exit()
#!/usr/bin/python import sys def help_screen(): print """ ---------------------------------------------------------------- FASTA DEREPLICATOR: Remove sequence replicates in a fasta file! by D. Gonzales This program takes a fasta file and removes identical sequences that appear more than once, even as a substring. Usage: fasta_dereplicator.py [-h] [-i in] [-o out] [-h] = This helpful help screen. [-i] = Input FASTA file. [-o] = Output FASTA file. *Requirements: python 2.7, sys, getopt. ----------------------------------------------------------------""" def fasta_dereplicator(infile,outfile): infile=open(infile,'r') contigs=[] for line in infile: if line[0]!='>': contigs.append(line.strip().upper()) derep1=list(set(contigs)) joined='#'.join(derep1) derep2=[] for item in derep1: if joined.count(item)==1: derep2.append(item) outfile=open(outfile,'w') index=0 for item in derep2: if index==0: outfile.write('>contig_'+str(index)+'\n'+item) else: outfile.write('\n'+'>contig_'+str(index)+'\n'+item) index=index+1 outfile.close() def main(): import getopt try: opts,args=getopt.getopt(sys.argv[1:],'i:o:h') except getopt.GetoptError as err: print str(err) print 'Usage: fasta_dereplicator.py [-h] [-i in] [-o out]' sys.exit() for o,a in opts: if o in ('-h'): help_screen() if o=='-i': infile=str(a) if o=='-o': outfile=str(a) for option in ['-i','-o']: if option not in [opt[0] for opt in opts]: print 'missing arguement' print 'Usage: fasta_dereplicator.py [-h] [-i in] [-o out]' sys.exit() fasta_dereplicator(infile,outfile) if __name__=='__main__': main() sys.exit()
import pandas as pd import numpy as np class CoulombMatrix(object): """ (CoulombMatrix) The implementation of coulomb matrix by Matthias Rupp et al 2012, PRL (3 different representations). Parameters ---------- CMtype: string, optional (default='SC') The coulomb matrix type, one of the following types: * 'Unsorted_Matrix' or 'UM' * 'Unsorted_Triangular' or 'UT' * 'Eigenspectrum' or 'E' * 'Sorted_Coulomb' or 'SC' * 'Random_Coulomb' or 'RC' max_n_atoms: integer or 'auto', optional (default = 'auto') maximum number of atoms in a molecule. if 'auto' we find it based on the input molecules. nPerm: integer, optional (default = 3) Number of permutation of coulomb matrix per molecule for Random_Coulomb (RC) type of representation. const: float, optional (default = 1) The constant value for coordinates unit conversion to atomic unit example: atomic unit -> const=1, Angstrom -> const=0.529 const/|Ri-Rj|, which denominator is the euclidean distance between atoms i and j """ def __init__(self, CMtype='SC', max_n_atoms = 'auto', nPerm=3, const=1): self.CMtype = CMtype self.max_n_atoms = max_n_atoms self.nPerm = nPerm self.const = const def __cal_coul_mat(self, mol): cm = [] for i in xrange(len(mol)): vect = [] for k in range(0,i): vect.append(cm[k][i]) for j in range(i,len(mol)): if i==j: vect.append(0.5*mol[i,0]**2.4) else: vect.append((mol[i,0]*mol[j,0]*self.const)/np.linalg.norm(mol[i,1:]-mol[j,1:])) for m in range(len(mol),self.max_n_atoms): vect.append(0.0) cm.append(vect) for m in range(len(mol),self.max_n_atoms): cm.append([0]*self.max_n_atoms) return np.array(cm) #shape nAtoms*nAtoms def represent(self, molecules): """ provides coulomb matrix representation for input molecules. Parameters ---------- molecules: dictionary, numpy array or pandas data frame if dictionary: output of cheml.initialization.XYZreader if numpy array: an array or list of molecules, which each molecule has a shape of (number of atoms, 4) if pandas dataframe : only one molecule with shape (number of atoms, 4). The four columns are nuclear charge, x-corrdinate, y-coordinate, z-coordinate for each atom, respectively. Returns ------- pandas DataFrame shape of Unsorted_Matrix (UM): (n_molecules, max_n_atoms**2) shape of Unsorted_Triangular (UT): (n_molecules, max_n_atoms*(max_n_atoms+1)/2) shape of eigenspectrums (E): (n_molecules, max_n_atoms) shape of Sorted_Coulomb (SC): (n_molecules, max_n_atoms*(max_n_atoms+1)/2) shape of Random_Coulomb (RC): (n_molecules, nPerm * max_n_atoms * (max_n_atoms+1)/2) """ if isinstance(molecules, dict): molecules = np.array([molecules[i]['mol'] for i in xrange(1, len(molecules)+1)]) elif isinstance(molecules, pd.DataFrame): # only one molecule molecules = np.array([molecules.values]) self.n_molecules = len(molecules) if self.max_n_atoms == 'auto': self.max_n_atoms = max([len(m) for m in molecules]) if self.CMtype == "Unsorted_Matrix" or self.CMtype == 'UM': cms = np.array([]) for mol in molecules: cm = self.__cal_coul_mat(mol) cms = np.append(cms, cm.ravel()) cms = cms.reshape(self.n_molecules, self.max_n_atoms**2) cms = pd.DataFrame(cms) return cms elif self.CMtype == "Unsorted_Triangular" or self.CMtype == 'UT': cms = np.array([]) for mol in molecules: cm = self.__cal_coul_mat(mol) cms = np.append(cms, cm[np.tril_indices(self.max_n_atoms)]) cms = cms.reshape(self.n_molecules, self.max_n_atoms*(self.max_n_atoms+1)/2) cms = pd.DataFrame(cms) return cms elif self.CMtype == 'Eigenspectrum' or self.CMtype == 'E': eigenspectrums = np.array([]) for mol in molecules: cm = self.__cal_coul_mat(mol) # Check the constant value for unit conversion; atomic unit -> 1 , Angstrom -> 0.529 eig = np.linalg.eigvals(cm) eig[::-1].sort() eigenspectrums = np.append(eigenspectrums,eig) eigenspectrums = eigenspectrums.reshape(self.n_molecules, self.max_n_atoms) eigenspectrums = pd.DataFrame(eigenspectrums) return eigenspectrums elif self.CMtype == 'Sorted_Coulomb' or self.CMtype == 'SC': sorted_cm = np.array([]) for mol in molecules: cm = self.__cal_coul_mat(mol) lambdas = np.linalg.norm(cm,2,1) sort_indices = np.argsort(lambdas)[::-1] cm = cm[:,sort_indices][sort_indices,:] # sorted_cm.append(cm) sorted_cm = np.append(sorted_cm, cm[np.tril_indices(self.max_n_atoms)]) # lower-triangular sorted_cm = sorted_cm.reshape(self.n_molecules, self.max_n_atoms*(self.max_n_atoms+1)/2) sorted_cm = pd.DataFrame(sorted_cm) return sorted_cm elif self.CMtype == 'Random_Coulomb' or self.CMtype == 'RC': random_cm = np.array([]) for nmol,mol in enumerate(molecules): cm = self.__cal_coul_mat(mol) lambdas = np.linalg.norm(cm,2,1) sort_indices = np.argsort(lambdas)[::-1] cm = cm[:,sort_indices][sort_indices,:] cm_perms = [] for l in range(self.nPerm): mask = np.random.permutation(self.max_n_atoms) cm_mask = cm[:,mask][mask,:] # cm_perms.append(cm_mask) cm_perms += list(cm_mask[np.tril_indices(self.max_n_atoms)]) # lower-triangular random_cm = np.append(random_cm, cm_perms) random_cm = random_cm.reshape(self.n_molecules, self.nPerm*self.max_n_atoms*(self.max_n_atoms+1)/2) return pd.DataFrame(random_cm) class BagofBonds(object): """ (BagofBonds) The implementation of bag of bonds version of coulomb matrix by katja Hansen et al 2015, JPCL. Parameters ---------- const: float, optional (default = 1.0) The constant value for coordinates unit conversion to atomic unit if const=1.0, returns atomic unit if const=0.529, returns Angstrom const/|Ri-Rj|, which denominator is the euclidean distance between two atoms Attributes ---------- header: list of header for the bag of bonds data frame contains one nuclear charge (represents single atom) or a tuple of two nuclear charges (represents a bond) Examples -------- >>> from cheml.datasets import load_xyz_polarizability >>> from cheml.chem import BagofBonds >>> coordinates, y = load_xyz_polarizability() >>> bob = BagofBonds(const= 1.0) >>> X = bob.represent(coordinates) """ def __init__(self, const=1.0): self.const = const def represent(self, molecules): """ provides bag of bonds representation for input molecules. Parameters ---------- molecules: dictionary,numpy array or pandas data frame if dictionary: output of cheml.initialization.XYZreader if numpy array: array or list of molecules, which each molecule is an array with shape (number of atoms, 4). if pandas dataframe : only one molecule with shape (number of atoms, 4). The four columns are nuclear charge, x-corrdinate, y-coordinate, z-coordinate for each atom, respectively. Returns ------- pandas data frame, shape: (n_molecules, max_length_of_combinations) """ if isinstance(molecules, dict): molecules = np.array([molecules[i]['mol'] for i in xrange(1,len(molecules)+1)]) elif isinstance(molecules, pd.DataFrame): molecules = molecules.values BBs_matrix = [] # list of dictionaries for each molecule all_keys = {} # dictionary of unique keys and their maximum length for nmol,mol in enumerate(molecules): bags = {} for i in xrange(len(mol)): for j in xrange(i,len(mol)): if i==j: key = (mol[i,0], mol[i,0]) Fc = 0.5 * mol[i, 0] ** 2.4 if key in bags: bags[key].append(Fc) else: bags[key] = [Fc] else: key = (max(mol[i,0],mol[j,0]),min(mol[i,0],mol[j,0])) Fc = (mol[i,0]*mol[j,0]*self.const) / np.linalg.norm(mol[i,1:]-mol[j,1:]) if key in bags: bags[key].append(Fc) else: bags[key] = [Fc] for key in bags: if key in all_keys: all_keys[key] = max(all_keys[key], len(bags[key])) else: all_keys[key] = len(bags[key]) BBs_matrix.append(bags) # extend bags with zero for i, bags in enumerate(BBs_matrix): for key in all_keys: if key in bags: diff = all_keys[key] - len(bags[key]) BBs_matrix[i][key] = sorted(BBs_matrix[i][key], reverse=True) + diff*[0] else: BBs_matrix[i][key] = all_keys[key]*[0] df = pd.DataFrame(BBs_matrix) del BBs_matrix order_headers = list(df.columns) output = pd.DataFrame(list(df.sum(1))) del df self.headers = [] for key in order_headers: if key[0]==key[1]: k = key[0] else: k = key self.headers += all_keys[key] * [k] return output
from random import randint ''' PICKS RANDOM MOVES BASED ON THE LENGTH OF CURRENTLY AVAILABLE MOVES TO MAKE THIS WAS THE STARTING POINT OF OUR ALGORITHMIC DESIGN AND BOARD MECHANISM VALIDATION/TESTING ''' class Random(object): @staticmethod def choose_move(actions): return randint(0,len(actions)-1)
class Vector: __privateCount = 0 publicCount = 0 def __init__(self, a, b): self.a = a self.b = b def __str__(self): return "Vector(%d,%d)" % (self.a, self.b) def __add__(self, other): return Vector(self.a + other.a, self.b + other.b) def increaseCount(self): self.__privateCount += 1 self.publicCount += 1 print self.__privateCount v1 = Vector(10, 20) v2 = Vector(100, 200) print v1 + v2 v1.increaseCount() print v1.publicCount #object._className__attrName print v1._Vector__privateCount
# -*- coding: utf-8 -*- import bisect class Node: def __init__(self, x, y, parent=None, g=0, h=0): self.x, self.y = x, y self.parent = parent self.g, self.h = g, h self.f = g + h def get_path(self): path = [] t = self while t: path.append((t.x, t.y)) t = t.parent path.reverse() return path def __cmp__(self, other): return other.f - self.f def __str__(self): return "{(%d, %d), g: %d, h: %d, f: %d}" % (self.x, self.y, self.g, self.h, self.f) class _OpenList(list): def __init__(self): self._nodes = {} def push(self, node): # 按f值逆排序 key = "%d,%d" % (node.x, node.y) assert key not in self._nodes idx = bisect.bisect_right(self, node) #f值相同,后插入优先 self.insert(idx, node) self._nodes[key] = node #print "push:", node #print "insert idx:", idx def remove(self, node): assert node in self key = "%d,%d" % (node.x, node.y) assert key in self._nodes #print "remove", node del self._nodes[key] b = bisect.bisect_left(self, node) e = bisect.bisect_right(self, node) assert b < e for i in range(b, e): if self[i] is node: del self[i] #print "del idx:", i break def get(self, x, y): key = "%d,%d" % (x, y) return self._nodes.get(key) def __contains__(self, item): key = "%d,%d" % (item.x, item.y) return key in self._nodes DIRS = ((1, 0, 1000), (1, -1, 1414), (0, -1, 1000), (-1, -1, 1414), (-1, 0, 1000), (-1, 1, 1414), (0, 1, 1000), (1, 1, 1414), ) def search_path(map, sx, sy, ex, ey): if sx == ex and sy == ey: return [(sx, sy), (ex, ey)] calc_h = lambda x, y: abs(x-ex) + abs(y-ey) rows = len(map) cols = len(map[0]) open_list = _OpenList() close_set = set() begin = Node(sx, sy) open_list.push(begin) while open_list: current = open_list.pop() close_set.add((current.x, current.y)) for dx, dy, g in DIRS: x = current.x + dx y = current.y + dy if x < 0 or y < 0 or x >= cols or y >= rows: continue if not map[y][x] or (x, y) in close_set: continue node = Node(x, y, current, current.g + g, calc_h(x, y)) if x == ex and y == ey: return node.get_path() if node in open_list: node2 = open_list.get(x, y) if node2.g > node.g: open_list.remove(node2) open_list.push(node) else: open_list.push(node) else: return [] def print_path(map, path): rows = len(map) cols = len(map[0]) print ' ', for col in range(0, cols): print col, print for row in range(0, rows): print row, for col in range(0, cols): if map[row][col] == 0: print '^', else: if (col, row) in path: print '-', else: print '.', print if __name__ == '__main__': map = [] for row in range(0, 7): map.append([]) for col in range(0, 9): map[-1].append(1) map[1][4] = 0 map[2][4] = 0 map[3][4] = 0 map[4][4] = 0 map[5][4] = 0 path = search_path(map, 2, 3, 6, 3) print_path(map, path)
numbers = [11, 7, 9, 23, 100, 88, 3, 21, 99, 100, 101, 32, 1, 17] def sort(list): length = len(list) if length < 2: return list for i in numbers: numbers.remove(i) break_out = False for j in range(0, length-1): if numbers[j] >= i: numbers.insert(j, i) break_out = True break if not break_out: numbers.append(i) print numbers sort(numbers) print numbers
def increase(n): return lambda x : x+n f = increase(40) print f(1) print f(11) pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair : pair[1]) print pairs
#Programmer: Qin Xusen #Time: 2021/4/14-10:52 def getText(): txt=open("C:\\Users\\Surface\\Desktop\\hamlet.txt","r").read() txt=txt.lower() for i in '|"$%&()+,-./:;<=>?@{\\}^_‘{|}~': txt=txt.replace(i," ") return txt hamletTxt=getText() words=hamletTxt.split() counts={} for word in words: counts[word]=counts.get(word,0)+1 items=list(counts.items()) print(items) items.sort(key=lambda x:x[1], reverse=True) for i in range(10): (word,counts)=items[i] print("{0:<10}{1:<50}".format(word,counts))
#Programmer: Qin Xusen #Time: 2021/4/28-22:58 def getNum(): # 获取用户不定长度的输入 numbers=[] l=input().split(sep=',') for i in l: numbers.append(float(i)) return numbers mean(numbers) dev(numbers,mean(numbers)) median(numbers) def mean(numbers): # 计算平均值 Total=0 for i in numbers: Total+=i mean=Total/int(len(numbers)) return mean def dev(numbers, mean): # 计算标准差 sdev = 0.0 for num in numbers: sdev = sdev + (num - mean) ** 2 return pow(sdev / (len(numbers) - 1), 0.5) def median(numbers): # 计算中位数 numbers.sort(reverse=True) l=int(len(numbers)) if l%2!=0: return int(numbers[int(l/2)]) else: return (numbers[int(l/2)]+numbers[int(l/2-1)])/2 n = getNum() # 主体函数 m = mean(n) print("平均值:{:.2f},标准差:{:.2f},中位数:{}".format(mean(n),dev(n,m),median(n)))
import numpy as np import random from feature_scaling import Scaler from loss_functions import * class MultivarLinReg(): # create initializer method def __init__(self, features: str, method: str, loss: str, weights: str, alpha: float, max_iter: int): """ The features property determines whether weights should be computed for one single feature or all features. This argument can only be set to 'single' or 'all'. The method property determines whether gradient descent or an analytic solution should be used for weights optimization. This argument can only be set to 'analytic' or 'gradient_descent'. The loss property determines whether the mean squared error or the root mean squared error should be used as the loss function. This argument can only be set to 'mse' or 'rmse'. The weights property determines whether weights should either be initialized randomly or with zeros. This argument can only be set to 'random' or 'zeros'. The alpha property denotes the learning rate of gradient descent. It controls the step sizes taken and thus is responsible for the convergence. Reasonable alpha values are 0.1, 0.01 or 0.001. Try different values. The max_iter property denotes the number of iterations gradient descent should maximally take until convergence. """ self.features = features self.method = method self.loss = loss self.weights = weights self.alpha = alpha self.max_iter = max_iter def preprocessing(self, X): """ Usually a constant is included as one of the regressors due to the offset parameter w_0. As w_0 is just an off-set parameter and denotes the intercept, we have to add a column with ones (x_0 = 1) to the features matrix X. Gradient descent will take longer to reach the global minimum when the features are not on a similar scale. Thus, feature scaling is an important step prior to gradient descent computation. The data matrix is required to be (centered and) normalized before (!) we add a column with ones (x_0 = 1) to X. """ N = X.shape[0] scaler = Scaler(method='normalization') # we only use the train set X = scaler.normalization(X) if self.features == 'single': X = np.c_[np.ones(N, dtype = int), X[:,0]] return X elif self.features == 'all': X = np.c_[np.ones(N, dtype = int), X] return X else: raise Exception('The features argument can only be set to "single" or "all"') def analytic(self, X, y): """ This function computes the optimal weights with an analytic solution instead of using gradient descent. """ if self.method == 'analytic': X = self.preprocessing(X) try: inverse_mat = np.linalg.inv(X.T.dot(X)) except np.linalg.LinAlgError: print('The inverse cannot be computed. Look at your data!') weights = np.dot(inverse_mat.dot(X.T), y) return weights else: raise Exception('The argument "method" is not set to analytic') def init_weights(self, X): """ Weights are either initialized randomly or with zeros (dependent on the set-up). """ M = X.shape[1] if self.weights == 'random': random.seed(42) weights = np.array([random.random() for _ in range(M)]) return weights elif self.weights == 'zeros': weights = np.zeros(M, dtype = int) return weights else: raise Exception('The weights argument can only be set to "random" or "zeros"') def loss_computation(self, X, y, w): """ Compute either mean squared error or root mean squared error as in-sample loss per iteration. """ if self.loss == 'mse': J = MSE(X, y, w) return J elif self.loss == 'rmse': J = RMSE(X, y, w) return J else: raise Exception('The loss argument can only be set to "mse" or "rmse"') @staticmethod def gradients(X, y, w): """ This function computes the gradients (i.e., derivative with respect to each parameter w_j) to update the weights after each iteration. It computes the derivative with respect to each w_j simulteanously. This function is a static method as it does not access any parameters of the object. You just have to pass the features matrix X, the vector y and the weights w. No instance is required. """ n = X.shape[0] f = X @ w # compute the derivative with respect to theta_j for all theta_j in the weights vector (simultaneously) derivatives = [(2 / n) * np.sum((f - y) * X[:,i]) for i, _ in enumerate(w)] return derivatives # default tolerance is set to 0.001 (can easily be changed) def gradient_descent(self, X, y, tolerance = 0.001): """ Compute gradient descent to find the optimal weights / coefficients. Be aware that w_0 is just an off-set parameter which denotes the intercept and is not a coefficient for a feature. Gradient descent will take longer to reach the global minimum when the features are not on a similar scale. Thus, feature scaling is an important step prior to gradient descent computation. """ if self.method == 'gradient_descent': X = self.preprocessing(X) weights = self.init_weights(X) # setting parameters to determine convergence alpha = self.alpha max_iter = self.max_iter num_iter = 1 convergence = 0 # initialize loss with 0 loss = 0 losses = [] while convergence < 1: current_loss = self.loss_computation(X, y, weights) losses.append(current_loss) derivatives = MultivarLinReg.gradients(X, y, weights) weights = np.array([w - alpha * d for w, d in zip(weights, derivatives)]) num_iter += 1 diff = abs(loss - current_loss) loss = current_loss if diff < tolerance: convergence = 1 elif num_iter > max_iter: convergence = 1 return weights, losses else: raise Exception('The method argument is not set to "gradient_descent"')
class Employee: raise_factor = 1.06 num_of_emps = 0 list_of_emps = [] def __init__(self, fname, lname, pay=10000): self.fname = fname self.lname = lname self.pay = pay self.email = "{}.{}@gle.com".format(fname, lname) Employee.num_of_emps += 1 Employee.list_of_emps.append(self) def fullname(self): return "{} {}".format(self.fname, self.lname) def raise_pay(self): self.pay = int(self.pay * Employee.raise_factor) @classmethod def set_raise_factor(cls, new_factor): cls.raise_factor = new_factor @classmethod def init_by_fullname(cls, name): firstname = name.split()[0] lastname = name.split()[1] return cls(firstname, lastname) @staticmethod def congratulate(): print("Eydetun Mobarak") emp1 = Employee("alireza", "afroozi") emp2 = Employee.init_by_fullname("Mohsen Rahimbakhsh") print(emp2.fname) print(emp2.lname) print(emp2.pay) # print(emp1.pay)
my_list = [1, 2, 3, 5, 8, 10, 3, 5] my_list2 = ['Mohsen', 'Mahdi', 'Radmehr', "Alireza"] my_list.sort() my_list2.sort() print(my_list) print(my_list2)
n = input() m = input() sn = n[::-1] sm = m[::-1] if (sn > sm): print(n, ">", m) elif (sn < sm): print(n, "<", m) else: print(n, "=", m)
import prettytable n = int ( input("Number of employees: ") ) employees = [] for i in range(n): emp = input("Emplyee number {}: ".format(i + 1)) employees.append(emp) hours = [] for i in range(n): h = float ( input("Work hours of Employee {}: ".format(i + 1))) hours.append(h) factors = [] for i in range(n): f = int ( input("How much employee {} gets per hour: ".format(i + 1))) factors.append(f) my_list = list ( zip (hours, factors) ) print(my_list) my_dict = dict (zip (employees, hours, factors) ) # pt = prettytable.PrettyTable( ["Name", "Hours", "Salary"] ) # for c in my_list: # pt.add_row([c[0] , c[1], c[1] * c[2]] ) # print(pt)
def mul(arg1, *args): # args is a list of arguments p = arg1 for i in args: p *= i return p if __name__ == '__main__': print(mul(2, 4, 6))
import math def fibonacci(n): li = [0, 1] for i in range(2, n + 1): li.append(li[i - 1] + li[i - 2]) return li[n]
my_dict = { 'name': 'alireza', 'last name': 'afroozi', 'face': { 'hair color': 'Brown', 'eye color': 'Blue' } , 'friends': ['sina', 'vahid', 'amir', 'erfan'] , } for key, val in my_dict.items(): print(f'key {key} is {val}') for key in my_dict.keys(): print(f'key {key} is {my_dict[key]}')
num = int (input("Enter your number: ")) print("Your num is even" if num % 2 == 0 else "Your num is odd") # if num % 2 == 0: # msg = "Your num is even" # else: # msg = "Your num is odd"
from math import sqrt def is_prime(m): if m == 1: return False for x in range(2, int(sqrt(m)) + 1): if m % x == 0: return False return True def prime_numbers(n): li = [] for m in range(1, n): if is_prime(m): li.append(m) return li print(prime_numbers(1000))
class Calendar: special_months = [1, 4, 7, 9, 11] def __init__(self, year, month, day): self.year = year self.month = month if day > 31 and month not in Calendar.special_months: raise RuntimeError("Invalid Date") if day == 32 and (month != 1 or year % 4 != 0): raise RuntimeError("Invalid Date") self.day = day months = [ "Hammer", "Alturiak", "Ches", "Tarsakh", "Mirtul", "Kythorn", "Flamerule", "Eleasis", "Eleint", "Marpenoth", "Uktar", "Nightal" ] special_days = { 31: "Midwinter", 122: "Greengrass", 213: "Midsummer", 274: "Highharvestide", 335: "Feat of the Moon" } shieldmeet = 214 lookup = { 1: "st", 2: "nd", 3: "rd" } def build_day_map(calendar): day_map = dict() day_count = 0 modifier = 0 for month in months: if month == "Nightal" or month == "Hammer" or month == "Alturiak": seasonal = " and it's winter!" elif month == "Ches" or month == "Tarsakh" or month == "Mirtul": seasonal = " and it's spring!" elif month == "Kythorn" or month == "Flamerule" or month == "Eleasis": seasonal = " and it's summer!" else: seasonal = " ant it's autumn!" for i in range(1, 31): day_count += 1 old_day_count = -1 while True: # No change if old_day_count == day_count: break old_day_count = day_count if day_count == shieldmeet and calendar.year % 4 == 0: day_map[day_count] = "Shieldmeet" + seasonal day_count += 1 modifier += 1 elif day_count - modifier in special_days: day_map[day_count] = special_days[day_count - modifier] + seasonal day_count += 1 day_map[day_count] = str(i) + (lookup[i] if i in lookup else "th") + " of " + month + seasonal if len(day_map) != calc_days_in_year(calendar): raise RuntimeError("You fucked up somewhere") return day_map def calc_start_index(calendar): index = ((calendar.month - 1) * 30) + calendar.day if index > 32 and calendar.year % 4 == 0: index += 1 for day, item in special_days.items(): if index - calendar.day + 1 >= day: # Shieldmeet would break this conditional if there was a celebration in the next month index += 1 return index def calc_days_in_year(calendar): return 366 if calendar.year % 4 == 0 else 365 def convert(calendar, days_passed): while True: start_index = calc_start_index(calendar) days_in_current_year = calc_days_in_year(calendar) if start_index + days_passed > days_in_current_year: calendar.year += 1 calendar.month = 1 calendar.day = 1 days_passed -= (days_in_current_year - start_index) else: day_map = build_day_map(calendar) day_text = day_map[start_index + days_passed] return day_map[start_index + days_passed]