text
stringlengths
37
1.41M
import string choice = input("Encrypt(0) or Decrypt(1): ") if choice == "0": orgText = input('Enter text to encrypt: ') orgKey = input('Enter key: ') elif choice == "1": cipherText = input("Input ciphertext: ") key = input("Enter key: ") def encrypt(text, key): textAlt = [] keyAlt = [] combinedAlt = [] counter = 0 counter2 = 0 cipherText = [] # get alternates for i in text: textAlt.append(alternate(i, counter, len(text))) counter += 1 for i in key: keyAlt.append(alternate(i, counter2, len(key))) counter2 += 1 # combine alternates if len(textAlt) > len(keyAlt): for i in range(len(keyAlt)): combinedAlt.append(specialAdd(textAlt[i], keyAlt[i])) for i in range(len(keyAlt), len(textAlt)): combinedAlt.append(textAlt[i]) elif len(textAlt) < len(keyAlt): for i in range(len(textAlt)): combinedAlt.append(specialAdd(textAlt[i], keyAlt[i])) for i in range(len(textAlt), len(keyAlt)): combinedAlt.append(keyAlt[i]) elif len(textAlt) == len(keyAlt): for i in range(len(textAlt)): combinedAlt.append(specialAdd(textAlt[i], keyAlt[i])) # get ciphertext for i in combinedAlt: cipherText.append(makeChar(i)) return ''.join(cipherText) def decrypt(text, key): keyAlt = [] textAlt = [] combinedAlt = [] split = [] characters = [] out = '' a = len(text) for i in range(a - 1): if i % 6 == 0 and i != 0: split.append(text[i-6:i]) split.append(text[len(text) - 6: len(text)]) for i in split: if i == '000000': characters.append('/') elif i == '000001': characters.append(' ') elif i == '000010': characters.append('9') elif i == '000011': characters.append('8') elif i == '000100': characters.append('7') elif i == '000101': characters.append('6') elif i == '000110': characters.append('5') elif i == '000111': characters.append('4') elif i == '001000': characters.append('3') elif i == '001001': characters.append('2') elif i == '001010': characters.append('1') elif i == '001011': characters.append('0') elif i == '001100': characters.append('Z') elif i == '001101': characters.append('Y') elif i == '001110': characters.append('X') elif i == '001111': characters.append('W') elif i == '010000': characters.append('V') elif i == '010001': characters.append('U') elif i == '010010': characters.append('T') elif i == '010011': characters.append('S') elif i == '010100': characters.append('R') elif i == '010101': characters.append('Q') elif i == '010110': characters.append('P') elif i == '010111': characters.append('O') elif i == '011000': characters.append('N') elif i == '011001': characters.append('M') elif i == '011010': characters.append('L') elif i == '011011': characters.append('K') elif i == '011100': characters.append('J') elif i == '011101': characters.append('I') elif i == '011110': characters.append('H') elif i == '011111': characters.append('G') elif i == '100000': characters.append('F') elif i == '100001': characters.append('E') elif i == '100010': characters.append('D') elif i == '100011': characters.append('C') elif i == '100100': characters.append('B') elif i == '100101': characters.append('A') elif i == '100110': characters.append('z') elif i == '100111': characters.append('y') elif i == '101000': characters.append('x') elif i == '101001': characters.append('w') elif i == '101010': characters.append('v') elif i == '101011': characters.append('u') elif i == '101100': characters.append('t') elif i == '101101': characters.append('s') elif i == '101110': characters.append('r') elif i == '101111': characters.append('q') elif i == '110000': characters.append('p') elif i == '110001': characters.append('o') elif i == '110010': characters.append('n') elif i == '110011': characters.append('m') elif i == '110100': characters.append('l') elif i == '110101': characters.append('k') elif i == '110110': characters.append('j') elif i == '110111': characters.append('i') elif i == '111000': characters.append('h') elif i == '111001': characters.append('g') elif i == '111010': characters.append('f') elif i == '111011': characters.append('e') elif i == '111100': characters.append('d') elif i == '111101': characters.append('c') elif i == '111110': characters.append('b') elif i == '111111': characters.append('a') characters.append(" ") current = "" counter = 0 for i in characters: if counter < 2: current += i elif counter == 2: combinedAlt.append(current) current = "" counter = 0 try: current += i except TypeError: pass counter += 1 counter = 0 for i in key: keyAlt.append(alternate(i, counter, len(key))) counter += 1 if len(combinedAlt) >= len(keyAlt): for i in range(len(combinedAlt)): try: textAlt.append(specialSub(combinedAlt[i], keyAlt[i])) except IndexError: textAlt.append(combinedAlt[i][0]) elif len(combinedAlt) < len(keyAlt): for i in range(len(combinedAlt)): textAlt.append(specialSub(combinedAlt[i], keyAlt[i])) for i in textAlt: out += unAlternate(i) return out def unAlternate(alt): conversion = string.ascii_letters + '0123456789 ' out = '' if alt in conversion: out += conversion[len(conversion) - 1 - conversion.index(alt)] return out def alternate(char, index, length): conversion = string.ascii_letters + '0123456789 ' out = '' if char in conversion: out += conversion[len(conversion) - 1 - conversion.index(char)] out += str(length - index) return out def specialAdd(text, key): conversion = string.ascii_letters + '0123456789 ' + string.ascii_letters + '0123456789 ' textIndex = conversion.index(text[0]) keyIndex = conversion.index(key[0]) numNum = int(text[1:]) + int(key[1:]) extra = '' if numNum >= len(conversion): extra += '/' else: extra += conversion[numNum] out = conversion[textIndex + keyIndex] + extra return out def specialSub(alt, keyAlt): keyIndex2 = None altIndex2 = None out = '' conversion = string.ascii_letters + '0123456789 ' + string.ascii_letters + '0123456789 ' keyIndex = conversion.index(keyAlt[0]) altIndex = conversion.index(alt[0]) if keyIndex > altIndex: altIndex = conversion.rindex(alt[0]) out += conversion[altIndex - keyIndex] return out def makeChar(alt): # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 <-- characters (remember space at end) decision = '' counter = 0 for i in alt: if counter < 2: if i is '/': decision += '000000' elif i is ' ': decision += '000001' elif i is '9': decision += '000010' elif i is '8': decision += '000011' elif i is '7': decision += '000100' elif i is '6': decision += '000101' elif i is '5': decision += '000110' elif i is '4': decision += '000111' elif i is '3': decision += '001000' elif i is '2': decision += '001001' elif i is '1': decision += '001010' elif i is '0': decision += '001011' elif i is 'Z': decision += '001100' elif i is 'Y': decision += '001101' elif i is 'X': decision += '001110' elif i is 'W': decision += '001111' elif i is 'V': decision += '010000' elif i is 'U': decision += '010001' elif i is 'T': decision += '010010' elif i is 'S': decision += '010011' elif i is 'R': decision += '010100' elif i is 'Q': decision += '010101' elif i is 'P': decision += '010110' elif i is 'O': decision += '010111' elif i is 'N': decision += '011000' elif i is 'M': decision += '011001' elif i is 'L': decision += '011010' elif i is 'K': decision += '011011' elif i is 'J': decision += '011100' elif i is 'I': decision += '011101' elif i is 'H': decision += '011110' elif i is 'G': decision += '011111' elif i is 'F': decision += '100000' elif i is 'E': decision += '100001' elif i is 'D': decision += '100010' elif i is 'C': decision += '100011' elif i is 'B': decision += '100100' elif i is 'A': decision += '100101' elif i is 'z': decision += '100110' elif i is 'y': decision += '100111' elif i is 'x': decision += '101000' elif i is 'w': decision += '101001' elif i is 'v': decision += '101010' elif i is 'u': decision += '101011' elif i is 't': decision += '101100' elif i is 's': decision += '101101' elif i is 'r': decision += '101110' elif i is 'q': decision += '101111' elif i is 'p': decision += '110000' elif i is 'o': decision += '110001' elif i is 'n': decision += '110010' elif i is 'm': decision += '110011' elif i is 'l': decision += '110100' elif i is 'k': decision += '110101' elif i is 'j': decision += '110110' elif i is 'i': decision += '110111' elif i is 'h': decision += '111000' elif i is 'g': decision += '111001' elif i is 'f': decision += '111010' elif i is 'e': decision += '111011' elif i is 'd': decision += '111100' elif i is 'c': decision += '111101' elif i is 'b': decision += '111110' elif i is 'a': decision += '111111' counter += 1 return decision if choice == "0": print(encrypt(orgText, orgKey)) elif choice == "1": print(decrypt(cipherText, key))
# -*- coding: utf-8 -*- """ Created on Thu Mar 26 01:08:43 2020 @author: carlos """ from random import randint import math import copy NUM_CARGAS=4 NOMBRE_PROCESOS=['A','B','C','D','E','F','G','H'] NUM_COLAS_PRIORIDAD=7 def printLista(l): for i in l: print(i) def cargaClase(l): l.append([0,3,'A']) l.append([1,5,'B']) l.append([3,2,'C']) l.append([9,5,'D']) l.append([12,5,'E']) def carga(letra): return [randint(0,6),randint(4,8),letra] def fcfs(l): c=copy.deepcopy(l) T=0.0 E=0.0 P=1 c[0].append(c[0][0]) T=c[0][1] for i in range (1,NUM_CARGAS): te=(c[i-1][3]+c[i-1][1])-c[i][0] c[i].append(te+c[i][0]) E=te+E T=T+te+c[i][1] P=P+(te+c[i][1])/c[i][1] E=E/NUM_CARGAS T=T/NUM_CARGAS P=P/NUM_CARGAS print("FCFS: ") for i in range (0,NUM_CARGAS): for x in range(0,c[i][1]): print(c[i][2],end='') print() print("T=%f E=%f P=%f"%(T,E,P)) print("----------------------") def rr(l,q): c=[] c=copy.deepcopy(l) print("RR%d: "%q) queue=[] t=c[0][0] n=0 for i in c: if i[0]==t: c[n].append(0) queue.append(i) n=n+1 r=[] todosIniciados=False while True: for i in range (0,NUM_CARGAS): if todosIniciados==True: break if(c[i][0]<=t+q and c[i].__len__()<4): c[i].append(0) queue.append(c[i]) if (i==NUM_CARGAS-1): todosIniciados=True corteQ=0 n=0 for i in queue: if n==0: i[1]=i[1]-q if i[1]>0: for x in range(0,q): print(i[2],end='') corteQ=corteQ+1 elif i[1]<=0: for x in range(0,q+i[1]): print(i[2],end='') corteQ=corteQ+1 i[1]=0 r.append(i) n=1 else: queue.remove(i) i[3]=i[3]+t+corteQ-i[0] i[0]=i[0]+t+corteQ-i[0] queue.insert(n,i) n=n+1 aux=queue[0] queue.remove(aux) aux[0]=aux[0]+corteQ queue.append(aux) for i in queue: if i[1]==0: queue.remove(i) if todosIniciados==True and queue.__len__()==0: print() break t=t+corteQ P=0.0 E=0.0 T=0.0 for i in range (0,NUM_CARGAS): for j in range(0,NUM_CARGAS): if c[i][2]==r[j][2]: T=T+l[i][1]+r[j][3] E=E+r[j][3] P=P+(l[i][1]+r[j][3])/l[i][1] E=E/NUM_CARGAS T=T/NUM_CARGAS P=P/NUM_CARGAS print("T=%f E=%f P=%f"%(T,E,P)) print("----------------------") def spn(l): print("SPN: ") c=copy.deepcopy(l) for x in c: x.append(0) x.append(False) queue=[] t=c[0][0] todosIniciados=False while True: for i in range(0,NUM_CARGAS): if c[i][0]<=t and c[i][4]==False: c[i][4]=True c[i][3]=t-c[i][0] queue.append(c[i]) if i==NUM_CARGAS-1: todosIniciados=True if queue.__len__()==0: continue else: pivote=queue[0] for i in range(0,queue.__len__()): if queue[i][1]<pivote[1]: pivote=queue[i] for i in range(0,pivote[1]): print(pivote[2],end='') queue.remove(pivote) t=t+pivote[1] for i in range(0,queue.__len__()): queue[i][3]=queue[i][3]+pivote[1] if todosIniciados==True and queue.__len__()==0: print() break P=0.0 E=0.0 T=0.0 for x in c: T=T+x[1]+x[3] E=E+x[3] P=P+(x[1]+x[3])/x[1] E=E/NUM_CARGAS T=T/NUM_CARGAS P=P/NUM_CARGAS print("T=%f E=%f P=%f"%(T,E,P)) print("----------------------") def fb(l,qb,n): print("FB: ") c=copy.deepcopy(l) for x in c: x.append(0) x.append(False) x.append(x[1]) queue=[] for i in range(0,NUM_COLAS_PRIORIDAD): queue.append([]) t=c[0][0] todosIniciados=False while True: for i in range(0,NUM_CARGAS): if c[i][0]<=t and c[i][4]==False: c[i][4]=True c[i][3]=t-c[i][0] queue[0].append(c[i]) if i==NUM_CARGAS-1: todosIniciados=True tmp=[] aux=0 moveToQ=0 for i in range(0,NUM_COLAS_PRIORIDAD): if queue[i].__len__()==0: continue Q=fbQ(i,qb) queue[i][0][1]=queue[i][0][1]-(Q*n) if queue[i][0][1]<=0: aux=(Q*n)+queue[i][0][1] queue[i][0][1]=0 else: aux=Q*n for k in range(0,int(aux)): print(queue[i][0][2],end='') tmp=queue[i][0] queue[i].remove(tmp) moveToQ=i+1 break for i in range(0,NUM_COLAS_PRIORIDAD): for j in range(0,queue[i].__len__()): queue[i][j][3]=queue[i][j][3]+aux if tmp[1]>0: queue[moveToQ].append(tmp) t=t+aux stop=True if todosIniciados==True: for i in range(0,NUM_COLAS_PRIORIDAD): if queue[i].__len__()>0: stop=False if stop==True: print() break P=0.0 E=0.0 T=0.0 for x in c: T=T+x[3]+x[5] E=E+x[3] P=P+(x[3]+x[5])/x[5] E=E/NUM_CARGAS T=T/NUM_CARGAS P=P/NUM_CARGAS print("T=%f E=%f P=%f"%(T,E,P)) print("----------------------") def fbQ(n,q): return math.pow(2,n*q) print("Inicio del programa") cargas=[] print("**************Carga aleatoria 1:****************") for i in range (0,NUM_CARGAS): cargas.append(carga(NOMBRE_PROCESOS[i])) print(cargas[i][2]+': '+str(cargas[i][0])+', t='+str(cargas[i][1])+';',end=' ') print() cargas.sort() fcfs(cargas) rr(cargas,1) rr(cargas,4) spn(cargas) fb(cargas,1,1) cargas.clear() print("**************Carga aleatoria 2:****************") for i in range (0,NUM_CARGAS): cargas.append(carga(NOMBRE_PROCESOS[i])) print(cargas[i][2]+': '+str(cargas[i][0])+', t='+str(cargas[i][1])+';',end=' ') print() cargas.sort() fcfs(cargas) rr(cargas,1) rr(cargas,4) spn(cargas) fb(cargas,1,1) cargas.clear() print("**************Carga aleatoria 3:****************") for i in range (0,NUM_CARGAS): cargas.append(carga(NOMBRE_PROCESOS[i])) print(cargas[i][2]+': '+str(cargas[i][0])+', t='+str(cargas[i][1])+';',end=' ') print() cargas.sort() fcfs(cargas) rr(cargas,1) rr(cargas,4) spn(cargas) fb(cargas,1,1) cargas.clear() print("**************Carga aleatoria 4:****************") for i in range (0,NUM_CARGAS): cargas.append(carga(NOMBRE_PROCESOS[i])) print(cargas[i][2]+': '+str(cargas[i][0])+', t='+str(cargas[i][1])+';',end=' ') print() cargas.sort() fcfs(cargas) rr(cargas,1) rr(cargas,4) spn(cargas) fb(cargas,1,1) cargas.clear() print("**************Carga aleatoria 5:****************") for i in range (0,NUM_CARGAS): cargas.append(carga(NOMBRE_PROCESOS[i])) print(cargas[i][2]+': '+str(cargas[i][0])+', t='+str(cargas[i][1])+';',end=' ') print() cargas.sort() fcfs(cargas) rr(cargas,1) rr(cargas,4) spn(cargas) fb(cargas,1,1) cargas.clear()
# Tarea 1: Ejercicios de sincronizacion # Los alumnos y el asesor # por Roel Perez from threading import Semaphore, Thread from time import sleep from random import randint x = 5 #Num max de alumnos en el cubículo y = 5 #Num max de preguntas por alumno Q = [] #Lista que almacena la pregunta (id y numero de pregunta) cubiculo = Semaphore(x) #Multiplex de capacidad del cubículo atencion = Semaphore(1) #Mutex de Q preguntas = Semaphore(0) #Señalizador de que se ha hecho una pregunta capacidad = Semaphore(1) #Mutex del proceso pregunta-respuesta # hilo de alumno def alumno(id): preguntas_totales = randint(1,y) #numero de preguntas que tiene el alumno num_pregunta = 1 #contador del numero de pregunta cubiculo.acquire() #entra al cubiculo print('El alumno %d ha entrado al cubiculo. Tiene %d pregunta(s)' % (id, preguntas_totales)) while(num_pregunta <= preguntas_totales): #mientras tenga preguntas no resueltas capacidad.acquire() # Adquiere el proceso de pregunta/respuesta atencion.acquire() # Escribe sobre la variable Q print('El alumno %d hace la pregunta %d' % (id, num_pregunta)); Q.append(id) Q.append(num_pregunta) atencion.release() preguntas.release() #Señaliza al asesor que se hizo una pregunta num_pregunta += 1 sleep(0.1) print('El alumno %d sale del cubiculo' % (id)) cubiculo.release() #sale del cubiculo def asesor(): while(True): print('El asesor espera...') preguntas.acquire() # Espera a que hayan hecho una pregunta atencion.acquire() # Lee y limpia la variable Q alumno_id = Q.pop(0) num_pregunta = Q.pop(0) print('El asesor responde la pregunta %d del alumno %d' % (num_pregunta,alumno_id)) atencion.release() capacidad.release() #Libera el proceso de pregunta/respuesta #Se inicia un hilo de asesor t_asesor = Thread(target = asesor) t_asesor.start() #Se inician 20 hilos de alumnos for i in range(1,21): t_alumnos= Thread(target = alumno, args = [i]) t_alumnos.start()
""" 选择排序 1.将列表中第一个元素与其后所有元素进行比较,碰到较小的便与之交换。 2.排除第1步中选出的元素,对剩下的元素进行第1步操作。 3.重复上述操作。 """ def selectSort(lis): if len(lis) <= 1: return lis max_value = max(lis) max_index = lis.index(max_value) del lis[max_index] return selectSort(lis) + [max_value] a = [5, 7, 3, 4, 1, 9, 8, 2] print(selectSort(a))
from collections import Iterable def gen(): a, b = 0, 1 while True: yield b a, b = b, a + b myGen = gen() for i in range(1, 10): print(next(myGen))
# 将不同的请求整合成一种请求 import requests from tools.my_logging import LOG class Http_request: def __init__(self, url, method, data=None, header=None): self.url = url self.method = method self.data = data self.header = header def do_request(self): try: LOG.info("正在请求HTTP") if self.method.lower() == 'get': res = requests.get(self.url, params=self.data, headers=self.header) LOG.info("正在进行get请求:请求地址:{},请求参数:{},请求头为:{}".format(self.url, self.data, self.header)) elif self.method.lower() == 'post': res = requests.post(self.url, json=self.data, headers=self.header) LOG.info("正在进行post请求:请求地址:{},请求参数:{},请求头为:{}".format(self.url, self.data, self.header)) else: LOG.error("暂时请求方式只有get,post,如需添加请联系胡晓明,现请求方式为{}".format(self.method)) except Exception as e: LOG.error("请求出现异常信息为:{}".format(e)) raise e return res.json() if __name__ == '__main__': url = "https://apity.bndxxf.com/company/sys/pc/login" dat = {"telephone": "18806644815", "password": "kwicOYe1ZHRPwapWtHRw8LlSuP2++T7Tc826GdZV6t6tTAdg2YxNm6e17MYtfQBKOb268xGth1YEy2L4FbOrfRZjnsZyxRskTRj6rFDYjiy8cEnC+eC1G2s5inhXbQJLLtGmE0uB2IgNTGOoAKG0UP/zdus1D6MXayuQgVjyo1c=", "rememberMe": 0} res = Http_request(url, 'post', dat).do_request() print(res)
x = int(input("Da un x = ")) rev = 0 sum = 0 i = 0 number = [] y = x while(y > 0): dig=y%10 rev=rev*10+dig y=y//10 number.append(dig) print(number) while i < len(number): sum = sum + pow(number[i], len(number)) i = i+1 if sum == x: print("Nr este un nr Armstrong") else: print("Nr nu este un nr Armstrong")
# Basic Data Types Challenge 1 : Letter Counter App print("Welcome") # Get user input name = input("What is your name : ").title().strip() print("Hello, {}.".format(name)) print("\nL E T T E R C O U N T E R\n") # Get input + standardize it message = input("Enter a message : ").lower() letter = input("Letter to be counted : ").lower() # Count the number of occurances and display it letter_count = message.count(letter) print("{} -> {}".format(letter, letter_count))
# ./Classes/Coordinates class Coordinates: def __init__(self, x=0, y=0): self._x = x self._y = y @property def x(self): return self._x; @property def y(self): return self._y; @x.setter def x(self, val): self._x = val @y.setter def y(self, val): self._y = val @property def location(self): return self._x, self._y
import sys playerOne = int(input("Player one please choose '1 = rock', '2 = paper', or '3 = scissors': ")) playerTwo = int(input("Player two please choose '1 = rock', '2 = paper', or '3 = scissors': ")) if playerTwo == 3 and playerOne == 1: print("Player Two wins!") sys.exit("Game Over") if playerTwo == 1 and playerOne ==3: print("Player One wins!") sys.exit("Game Over") if playerOne == playerTwo: print("The game is a draw.") if playerOne > playerTwo: print("Player One has won the game.") if playerTwo > playerOne: print("Player Two has won the game.")
#This python script is designed to display a live feed of Gamestop's price #Dominic Wojewodka #03/09/2021 from tkinter import * import time #for animation #(arch) sudo pacman -S tkinter from Stock_Alert import Stock #List of functions in Stock #__init__(self,ticker) #getPrice() #getOpenPrice() #init_treshold() #stdTresh() #alertPercent() #Setting up the animation WIDTH = 1920 HEIGHT = 1080 xVelocity = 3 yVelocity = 2 window = Tk() canvas = Canvas(window,width=WIDTH,height=HEIGHT) canvas.pack() #selecting pictures and placing them on the canvas andromeda = PhotoImage(file='Images/andromeda1080.png') wsb = PhotoImage(file='Images/wsb.png') IMG_W = wsb.width() IMG_H = wsb.height() background = canvas.create_image(0,0,image=andromeda,anchor=NW) myImage = canvas.create_image(0,0,image=wsb,anchor=NW) GME = Stock("GME") prev=GME.getPrice() #prev=GME.getAfterMarketPrice() #timer prevents lag timer = 0 while True: coordinates = canvas.coords(myImage) if (coordinates[0] >= (WIDTH-IMG_W) or coordinates[0]<0): xVelocity *= -1 if (coordinates[1] >= (HEIGHT-IMG_H) or coordinates[1]<0): yVelocity *= -1 canvas.move(myImage,xVelocity,yVelocity) #Code for discplaying price if (timer == 180): #new = GME.getAfterMarketPrice() new = GME.getPrice() if((float(new) - float(prev))<= 0): color = "red" else: color = "green" price = Label(text=new,bg="black",fg=color,font=("Helvetica",36)) price.place(height=150,width=150,x=((WIDTH/2)-50),y=((HEIGHT/2)-50)) prev = new timer = 0 ### window.update() time.sleep(0.01) timer += 1 window.mainloop()
import requests # request = requests.get('http://api.open-notify.org') # print(request.text) # print the json data as text people = requests.get('http://api.open-notify.org/astros.json') print(people.text) # Converts data to python dictionary format people_json = people.json() print(people_json) # To print the number of people in space print("Number of people in space:",people_json['number']) # To print the names of people in space using a for loop for p in people_json['people']: print(p['name'])
from sort import InsertionSort def start(): selection_sort = InsertionSort() try: size = int(input('Enter the number of elements: ')) arr = [] print('Start entering elements:') for i in range(size): arr.append(int(input())) print('Sorted Array is:') print(selection_sort.sort(arr)) except Exception as error: print(error) if __name__ == '__main__': start()
class BinarySearch: def search(self, arr, key): if len(arr) == 0: return False, None left, right = 0, len(arr)-1 while left <= right: middle = (right + left) // 2 if arr[middle] == key: return True, middle elif arr[middle] > key: right = middle-1 elif arr[middle] < key: left = middle+1 return False, None
from sort import RadixSort def start(): radix_sort = RadixSort() try: size = int(input('Enter the number of elements: ')) arr = [] print('Start entering elements:') for i in range(size): temp = int(input()) if temp < 0: print('\n-- Current implementation only works with positive integers. --') return arr.append(temp) print('Sorted Array is:') print(radix_sort.sort(arr)) except Exception as error: print(error) if __name__ == '__main__': start()
#Write a python program to test if an array contains a specific value. inp=input('enter alphabetical elements separated by space: ') split=inp.split() print('the list of array is: ',split) char=input('enter the letter you want to find: ') a=0 for i in range(len(split)): if split[i]==char: a = a + 1 if a>=1: print('element is present in array') else: print('element not present in list of array')
#Write a pyhton program to find the duplicate values of an array of integer values. inp=int(input('enter how many numbers you want to enter ')) list=[] for i in range(0,inp): enter=int(input('enter the number: ')) list.append(enter) res = [] for i in list: if i not in res: res.append(i) print("The list after removing duplicates : " + str(res))
#Write a python program to calculate the average value of array elements. num=int(input('how many numbers you want: ')) list=[] for i in range(num): enter=int(input('enter the number: ')) list.append(enter) avg_list=sum(list)/len(list) print('the array is: ',list) print('the average of elements are: ',float(avg_list))
# Write a python program to add two matrices of the 3x3 size. def read(r,c,mat): for i in range(r): a=[] for j in range(c): a.append(int(input())) mat.append(a) def dis(r,c,mat): for i in range(r): for j in range(c): print(mat[i][j],end=' ') print() def add(r,c,mat1,mat2): res=[] for i in range(r): a=[] for j in range(c): a.append(mat1[i][j]+mat2[i][j]) res.append(a) print('addition of matrix is : ') dis(r,c,res) def main(): mat1=[] mat2=[] print('enter the elements of 1st matrix ') read(3,3,mat1) print('enter the elements of 2nd matrix ') read(3,3,mat2) print('1st matrix is : ') dis(3,3,mat1) print('2nd matrix is : ') dis(3,3,mat2) add(3,3,mat1,mat2) if __name__=='__main__': main()
# To check the priority for the mathematical operators used in Python # Debug the program for better understanding a=4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) - (1.0/11)) print(a) a=((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5)) print(a) # To find the perimeter of the circle r=input('enter the radius in cm : ') radius=float(r) π=3.14159265359 perimeter=2*π*radius print('the perimeter of circle is : ',perimeter)
class rectangle(): def __init__(self,length,breadth): self.length = length self.breadth = breadth def area(self): area = self.length *self.breadth print('Area of rectangle is : ',area) if __name__ == '__main__': length = int(input('Enter length of rectangle: ')) breadth = int(input('Enter breadth of rectangle : ')) a=rectangle(length,breadth) a.area()
class student: name = 'John' roll_number=2 a=student() print('the student name is '+a.name+' and roll number is',a.roll_number)
class complex(): def __init__(self,a,b,p,q): self.a = a self.b=b self.p=p self.q=q def sum1(self): x= self.a+self.p y= self.b+self.q print('Sumation of two given complex no : ',x,' + ',y,'i') def dif(self): x= self.a-self.p y= self.b-self.q print('Difference of two given complex no : ',x,' + ',y,'i') def mul(self): x=(self.a*self.p)-(self.b*self.q) y=(self.a*self.q)+(self.p*self.b) print('Multiplication of two complex no : ',x,' + ',y,'i') def main(): print('a+bi') a = int(input('enter a: ')) b = int(input('enter b: ')) print('First no is :',a,' + ',b,'i') print('px+q') p = int(input('enter p: ')) q = int(input('enter p: ')) print('Second no is :',p,' + ',q,'i') s= complex(a,b,p,q) s.sum1() s.dif() s.mul() if __name__ == '__main__': main()
#Write a program to shift every element of an array to circularly right. number_array = list() number = input("Enter the number of elements you want: ") print ('Enter numbers in array: ') for i in range(int(number)): n = input(f"number {i+1} : ") number_array.append(int(n)) print('original array is: ',number_array) print ('circulatory right array is: ',number_array[::-1])
# class House(): # #静态变量,可在类中调用也可在对象中调用 # door="red" # floor="red" # # #构造函数,在类实例化的时候直接执行 # #此处的self是指方法中必须至少有一个参数,self是约定俗成的一种方式,是每个实例化对象的主人 # def __init__(self): # #调用静态变量需要加self # print(self.door) # #实例变量,在类中,方法中,以”self.变量名“定义,在该类的其他方法中以self.变量名直接引用, # # 因为构造函数在实例化的时候已经执行了 # self.kitchen="cook" # #定义方法 # def sleep(self): # #类当中,方法当中调用,普通变量 # bed="席梦思" # #在方法中以self.变量名定义的变量是全局变量,在整个类中有效, # # 但是如果在别的方法中调用,则必须先执行定义该变量的方法 # #所以为了方便可以将全局变量直接定义在构造函数中,实例化时自动执行 # self.table="桌子是黄色的" # print(f"可以在房子里躺在{bed}上睡觉") # # def cook(self): # print(f"可以在房子里做饭吃{self.bed}") # #把类实例化 # north_house=House() # china_house=House() # #调用实例化当中的方法 # north_house.sleep()
# -*- coding: utf-8 -*- “”“ Created on Sat Dec 26 14:26:14 2015 @author: Bernard ”“” #import statements import pandas import numpy #load the gapminder_ghana_updated dataset csv into the program data = pandas.read_csv(‘gapminder_ghana_updated.csv’, low_memory = False) #print number of observations(rows) which is the number of years this data #has been looked at; print length print(“number of observations(rows) which is the number of years this data has been looked at: ”) print(len(data)) #print number of variables (columns) print(“number of variables (columns) available in the dataset: ”) print(len(data.columns)) print(“data index: ”) print(len(data.index)) #Converting datat to numeric data[“incomeperperson”] = data[“incomeperperson”].convert_objects(convert_numeric=True) data[“lifeexpectancy”] = data[“lifeexpectancy”].convert_objects(convert_numeric=True) data[“literacyrate”] = data[“literacyrate”].convert_objects(convert_numeric= True) #displaying rows or observation in Dataframe. #inc_pp_count is the name that will hold the result from incomeperperson count # sort = false ; i use value false so that the data will be sorted according #to the original format and sequence of the loaded data print(“counts for incomeperperson - 2010 Gross Domestic Product per capita in constant 2000 US$ of Ghana. ”) inc_pp_count = data[“incomeperperson”].value_counts(sort = False) #print the count of inc_pp_count ; incomeperperson print(inc_pp_count) print(“percentages for incomeperperson - 2010 Gross Domestic Product per capita in constant 2000 US$ of Ghana. ”) inc_pp_percent = data[“incomeperperson”].value_counts(sort=False, normalize =True) #print the percentage of incomeperperson print(inc_pp_percent) print(“counts for lifeexpectancy- 2011 life expectancy at birth (years) of Ghana”) life_exp_count = data[“lifeexpectancy”].value_counts(sort = False) #print the count of life_exp_count ; lifeexpectancy print(life_exp_count) print(“percentages for lifeexpectancy- 2011 life expectancy at birth (years) of Ghana ”) life_exp_percent = data[“lifeexpectancy”].value_counts(sort =False, normalize = True) #print the percentage of life_exp_count ; lifeexpectancy print(life_exp_percent) print(“counts for literacyrate - 2010, Literacy rate, adult total (% of people ages 15 and above) of Ghana”) lit_rate_count = data[“literacyrate”].value_counts(sort = False ,dropna=False) #dropna displays missen values #print the count of lit_rate_count ; literacyrate print(lit_rate_count) print(“percentages literacyrate - 2010, Literacy rate, adult total (% of people ages 15 and above) of Ghana ”) lit_rate_percent = data[“literacyrate”].value_counts(sort =False, normalize = True) #print the percentage of lit_rate_count ; literacyrate print(lit_rate_percent)
a=input() a=a.lower() if(a=='a' or a=='e' or a=='i' or a=='o' or a=='u'): print("Vowel") elif(97<=ord(a)<=122): print("Consonant") else: print("Invalid Input")
print("Program to check age Booleans ") myAge = 21 userAge = int( input("Enter your age: ")) if(myAge < userAge): print("He's older than you") elif(myAge > userAge): print("He's younger than you") else: print("You two have the same age")
import math print("Program to calculate the area and circumference of a circle") radius = float( input("Enter the value of radius: ")) area = math.pi * (radius ** 2) circumference = 2 * math.pi * radius print("Area = ", round(area, 2)) print("Circumference = ", round(circumference, 2))
#import moduels import os import csv #set path for file dirname = os.path.dirname(__file__) budgetcsvpath = os.path.join("Resources", "budget_data.csv") #declare variables total_months = 0 net_total = 0 months = [] change = [] profit_loss = [] #Print info print(f"Financial Analysis") print(f"--------------------------") #Sum total months and net total, add to months and proft loss list with open(budgetcsvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") next(csvreader, None) for row in csvreader: total_months += 1 net_total += int(row[1]) profit_loss.append(int(row[1])) months.append(row[0]) print(f"Total Months: {total_months}") print(f"Total: $ {net_total}") #create list of change in profit/loss for i in range(1,len(profit_loss)): change.append((int(profit_loss[i]) - int(profit_loss[i-1]))) #Calculate average change average_change = sum(change)/ len(change) #Print info print(f"Average Change: {round(average_change,2)}") #Calculate greatest increase and decrease greatest_increase = max(change) greatest_decrease = min(change) #Print info print(f"Greatest Increase: {months[change.index(max(change)) + 1]} (${(str(greatest_increase))})") print(f"Greatest Decrease: {months[change.index(min(change)) + 1]} (${(str(greatest_decrease))})") #location of open output files output_file = os.path.join("Analysis", "Financial_Analysis_Summary.txt") with open(output_file,"w") as file: #Write output file file.write("Financial Analysis") file.write("\n") file.write("----------------------------") file.write("\n") file.write(f"Total Months: {total_months}") file.write("\n") file.write(f"Total: ${net_total}") file.write("\n") file.write(f"Average Change: {round(average_change,2)}") file.write("\n") file.write(f"Greatest Increase in Profits: {months[change.index(max(change)) + 1]} (${(str(greatest_increase))})") file.write("\n") file.write(f"Greatest Decrease in Profits: {months[change.index(min(change)) + 1]} (${(str(greatest_decrease))})")
#[08/13/13] Challenge #137 [Easy] String Transposition #http://www.reddit.com/r/dailyprogrammer/comments/1m1jam/081313_challenge_137_easy_string_transposition/ f = [s.strip() for s in open("challenge137.txt").readlines()] max_len = max([len(s) for s in f]) padded = [s+" "*((max_len)-len(s)) for s in f] for c in range(max_len): seg = "" for s in padded: seg +=(s[c]) print (seg)
#[08/06/13] Challenge #134 [Easy] N-Divisible Digits #http://www.reddit.com/r/dailyprogrammer/comments/1jtryq/080613_challenge_134_easy_ndivisible_digits/ import time def n_digits(N,M): for x in range(int("9"*N),0,-1): if x%M == 0 and len(str(x)) == N: return x return None start = time.clock() def n_digits(N,M): return int("9"*N) - (int("9"*N) %M) print (n_digits(9,641351511)) stop = time.clock() print(stop-start)
## [11/11/13] Challenge #141 [Easy] Monty Hall Simulation #http://www.reddit.com/r/dailyprogrammer/comments/1qdw40/111113_challenge_141_easy_monty_hall_simulation/ import random def monty_hall(n): Tactic1 = 0 Tactic2 = 0 prizes = ["car","goat","goat"] for x in range(n): random.shuffle(prizes) guess = 0 if prizes[guess] is "car": Tactic1+= 1 else: options = prizes[1:] options.remove("goat") #reveal and remove a goat prize from the remaining options if options[0] == "car": #if the remaining door contains a car... Tactic2+= 1 #then switching to it yields a win print ("Tactic 1", Tactic1/n) print ("Tactic 2", Tactic2/n) monty_hall(10000)
import data df = data.data # print(df.head()) # print(pd.isnull(df).sum()) # Remove missing value df_re = df.dropna(axis=0) # Change missing value with 0 df["total_bill"] = df["total_bill"].fillna(0) df["size"] = df["size"].fillna(0) # print(df)
#You are in a room with a circle of 100 chairs. The chairs are numbered sequentially from 1 to 100. #At some point in time, the person in chair #1 will be asked to leave. The person in chair #2 will be skipped, and the person in chair #3 will be asked to leave. This pattern of skipping one person and asking the next to leave will keep going around the circle until there is one person left the survivor. #Write a program to determine which chair the survivor is sitting in. class Node: def __init__(self, initData): self.data = initData self.next = None def getData(self): return self.data def getNext(self): return self.next class LinkedList: def __init__(self): self.head = None self.tail = None def append(self, item): tempNode = Node(item) if self.head: #makes the linked list circular tempNode.next = self.head if self.tail: self.tail.next = tempNode self.tail = tempNode else: self.tail = tempNode self.head.next = self.tail else: self.head = tempNode def printList(self): currentNode = self.head for i in range(self.count()): print 'Current Node Data:',currentNode.data currentNode = currentNode.next return "end of list" def count(self): counter = 1 currentNode = self.head while currentNode.next != self.head: counter +=1 currentNode = currentNode.next return counter #Note: returns the node object def find(self, data): currentNode = self.head for i in range(self.count()): if currentNode.data != data: currentNode = currentNode.next else: return currentNode def delete(self, data): #find the node removeNode = self.find(data) #find the previous node refNode = self.head for i in range(self.count()): if removeNode != refNode.next: refNode = refNode.next #swap pointers if removeNode == self.head: self.head = removeNode.next refNode.next = self.head elif removeNode == self.tail: self.tail = removeNode.next refNode.next = self.tail else: refNode.next = removeNode.next def rude_chairs(num_of_chairs): chairs = LinkedList() for num in range(1, num_of_chairs+1): chairs.append(num) currentNode = chairs.head deleteNode = None while chairs.count() > 1: deleteNode = currentNode currentNode = currentNode.next.next #print "Delete Chair: ", deleteNode.data chairs.delete(deleteNode.data) return 'Survivor is', chairs.head.data print rude_chairs(10)
#HARSH KUMAR AGARWAL #a = ("{0:0%db}" % alen).format(a) #converts to binary value(as a string of length alen) #int("stirng of zeros and one", 2) #converts from string binary to int decimal import math def pow2c(a): #this function finds if the given parameter is a power of 2 or not c=math.log2(a) #finding the log base 2 value of a return(c.is_integer()) #checking if the log base 2 value is an integer or not def size_of_word(n): return (len('{:b}'.format(n))<32) #checks and return if the given value is less than 32 bit or not def search_dm(addr,tag_f,c1): #function to search the address using direct mapping technique nb_tf = len(tag_f[0]) #find the size of the tag field linno=int(addr[nb_tf:nb_tf+nb_cl],2) #extract the relevant part from the given address stf=tag_f[linno] if(stf==addr[:nb_tf]): #checking if the given location has the same tag field or not(if yes than cache hit) print("CACHE HIT") r=int(math.log2(len(c1[0]))) # r stores the number of bit in which cache is stored bi=int(addr[-r:] ,2) # slicing the address from the given address and then converting it to decimal form print("the value found at the given location is : ",c1[linno][bi]) #printing the value at the given location else: print("cache miss,address not found") def load_cache_dm(rd,tag_f,c1,sd): #function to load data into the cache using direct mapping technique nb_tf = len(tag_f[0]) #finding the length of the bit required to store the tag field linno = int(rd[nb_tf:nb_tf + nb_cl], 2) #slicing the part needed from the given address print("befor changing ,cache = ",c1) print("befor changing ,tag fields=",tag_f) tag_f[linno]=rd[:nb_tf] #changing the data in tag field c1[linno]=sd #changing the data in the cache print("After changing the cache, the new cache : ",c1) print("After changing the tag fields",tag_f) def search_am(addr,tag_f,c1): #function to search the address using associative mapping technique nb_tf = len(tag_f[0]) #finding the length of the bit required to store the tag field se=addr[:nb_tf] #slicing the part needed from the given address flag=0 for i in range(len(c1)): #start searching on each line of the cache if(se==tag_f[i]): #checking if the given location has the same tag field or not(if yes than cache hit) flag=1 print("CACHE HIT") r = int(math.log2(len(c1[0]))) # r stores the number of bit in which cache is stored bi = int(addr[-r:], 2) # slicing the address from the given address and then converting it to decimal form print("the value found at the given location is : ", c1[i][bi]) #printing the value at the given location break if(flag==0): print("cache miss,address not found") def load_cache_am(rd,tag_f,c1,sd,wheretocopy): #function to load data into the cache using associative mapping technique print("befor changing ,cache = ", c1) #rd is the value of the tagfield print("befor changing ,tag fields=", tag_f) tag_f[wheretocopy]=rd #changing the data in tag field c1[wheretocopy]=sd #changing the data in the cache print("After changing the cache, the new cache : ", c1) print("After changing the tag fields", tag_f) def search_nam(n,addr,tag_f,c1): #function to search the address using n was associative mapping technique no_sets=int(cl/n) noofbit_for_sets=int(math.log2(no_sets)) #finding the length of the bit required to sets nb_tf = len(tag_f[0]) #finding the length of the bit required to store the tag field setno = int(addr[nb_tf:nb_tf + noofbit_for_sets], 2) #slicing the part needed from the given address and converting it to decimal form se = addr[:nb_tf] #slicing the tag field part needed from the given address flag = 0 for i in range(n*setno,n*setno+n): if(se==tag_f[i]): #checking if the given location has the same tag field or not(if yes than cache hit) flag = 1 print("CACHE HIT") r = int(math.log2(len(c1[0]))) # r stores the number of bit in which cache is stored bi = int(addr[-r:], 2) # slicing the address from the given address and then converting it to decimal form print("the value found at the given location is : ", c1[i][bi]) #printing the value at the given location break if (flag == 0): print("cache miss,address not found") def load_cache_nam(n,rd,tag_f,c1,sd,wheretocopy): #function to load data into the cache using n way associative mapping technique no_sets = int(cl / n) #calculating the number of sets from the given data noofbit_for_sets = int(math.log2(no_sets)) #finding the length of the bit required to sets nb_tf = len(tag_f[0]) setno = int(rd[nb_tf:nb_tf + noofbit_for_sets], 2) #slicing the part needed from the given address and converting it to decimal form print("befor changing ,cache = ", c1) print("befor changing ,tag fields=", tag_f) tag_f[(setno*n+wheretocopy)]=rd[:nb_tf] #changing the data in tag field c1[(setno*n+wheretocopy)]=sd #changing the data in the cache print("After changing the cache, the new cache : ", c1) print("After changing the tag fields", tag_f) N=64 #predifining total size of main memory cl=4 #predifing cache line size b=4 #predifing size of block majchoice=int(input("\nEnter 1 if you want to use predefined values or 2 if you want to enter your own value :\t")) if(majchoice==2): cl = int(input("enter numbers of cache lines size :\t")) b=int(input("enter block size :\t")) N=int(input("enter the total number of blocks in the main memory as a power of 2\t")) s=cl*b #s is the total cache size nb=int(N/b) #number of blocks nb_cl=int(math.log2(cl)) #store number of bits for cache line nb_b=int(math.log2(b)) #store number of bits for block size nb_nb=int(math.log2(nb)) #store number of bits for number of blocks mm = [] #initializing main memory(instead not used in the program) cac=[] #initializing cache memory tf=[] #initializing tag field(part with cache to see the address part) if(not pow2c(s*N)): #checking if the given values are of power 2 or not print("THE GIVEN VALUES ARE NOT OF POWERS OF 2 PLEASE RERUN THE PROGRAM AND TRY AGAIN!!") else: print("\t ENTER THE OPTIONS") print("1. Direct mapping ") print("2. Associative memory") print("3. n-way set associative memory where n is a power of 2.") for i in range(nb): row = [] for j in range(b): row.append(i+j) #putting some values in the main memory before our code start though not used in the program mm.append(row) for i in range(cl): row = [] for j in range(b): row.append(i+j) #putting some values in the cache before our code start cac.append(row) o=int(input("Your choice: ")) #asking for the choice wanttocont = 1 if(o==1): nb_tf=nb_nb-nb_cl #finding the number of bits required for tag field with the given data for i in range(cl): row=("{0:0%db}" % nb_tf).format(i) #initialsing tag values with some data each in binary format of length find earlier tf.append(row) while(wanttocont==1): choi=int(input("Enter 1 if you want to search ,2 if you want to load : ")) if(choi==1): print("Enter the address first ",nb_tf,"for tag field. Next ",nb_cl,"for line no. and next", nb_b,"for block offset") s=input("Enter the address to be fetched in binary format :\t") search_dm(s, tf, cac) #calling the function for searching the given address wanttocont = int(input("Enter 1 if you want to continue :\t")) elif(choi==2): print ("Enter first",nb_tf,"bit for tag field and next ",nb_cl,"bits for the cache line") r_add = input("Enter here: ") print("Enter",b,"values you want to store in cache") sentdata=[] for i in range(b): t=int(input()) #taking values to be stored in the cache if(not size_of_word(t)): #checking each word is less than 32 bit or not print("The entered value is of greater size") break sentdata.append(t) load_cache_dm(r_add, tf, cac, sentdata) #calling the fuction for loading of the given data wanttocont = int(input("Enter 1 if you want to continue : ")) else: print("Invalid choice ") wanttocont = int(input("Enter 1 if you want to continue : ")) elif(o==2): counter = 0 nb_tf = nb_nb #finding the number of bits required for tag field with the given data for i in range(cl): row=("{0:0%db}" % nb_tf).format(i) #initialsing tag values with some data each in binary format of length find earlier tf.append(row) while (wanttocont == 1): choi = int(input("Enter 1 if you want to search ,2 if you want to load : ")) if (choi == 1): print("Enter the address first ", nb_tf, "for tag field and next", nb_b,"for block offset") s = input("Enter the address to be fetched in binary format : ") search_am(s, tf, cac) #calling the function for searching the given address wanttocont = int(input("Enter 1 if you want to continue : ")) elif (choi == 2): print("Enter", b, "values you want to store in cache") sentdata = [] for i in range(b): t = int(input()) #taking values to be stored in the cache if (not size_of_word(t)): #checking each word is less than 32 bit or not print("The entered value is of greater size") break sentdata.append(t) print ("Enter first", nb_tf, "bit for tag field") r_add = input("Enter here: ") load_cache_am(r_add, tf, cac, sentdata, counter) #calling the fuction for loading of the given data counter=counter+1 counter = counter % cl #mainting the counter so that we know where to store next data wanttocont = int(input("Enter 1 if you want to continue : ")) else: print("Invalid choice ") wanttocont = int(input("Enter 1 if you want to continue : ")) elif(o==3): n=int(input("Enter the value of n: ")) if(not pow2c(n)): print("THE GIVEN VALUES ARE NOT OF POWERS OF 2 PLEASE RERUN THE PROGRAM AND TRY AGAIN!!") else: counter = 0 no_sets = int(cl / n) noofbit_for_sets = int(math.log2(no_sets)) nb_tf=nb_nb-noofbit_for_sets #finding the number of bits required for tag field with the given data for i in range(cl): row = ("{0:0%db}" % nb_tf).format(i) #initialsing tag values with some data each in binary format of length found earlier tf.append(row) while (wanttocont == 1): choi = int(input("Enter 1 if you want to search ,2 if you want to load : ")) if (choi == 1): print("Enter the address first ", nb_tf, "for tag field. Next ", noofbit_for_sets , "for set line", nb_b,"for block offset") s = input("Enter the address to be fetched in binary format : ") search_nam(n, s, tf, cac) #calling the function for searching the given address wanttocont = int(input("Enter 1 if you want to continue : ")) elif (choi == 2): print ("Enter first", nb_tf, "bit for tag field and next ", noofbit_for_sets, "bits for set line") r_add = input("Enter here: ") print("Enter", b, "values you want to store in cache") sentdata = [] for i in range(b): t = int(input()) #taking values to be stored in the cache if (not size_of_word(t)): #checking each word is less than 32 bit or not print("The entered value is of greater size") break sentdata.append(t) load_cache_nam(n, r_add, tf, cac, sentdata, counter) #calling the fuction for loading of the given data counter = (counter + 1) % n #mainting the counter so that we know where to store next data wanttocont = int(input("Enter 1 if you want to continue : ")) else: print("Invalid choice ") wanttocont = int(input("Enter 1 if you want to continue : ")) else: print("INVALID OPTION SELECTED") print("PLEASE RERUN THE PROGRAM")
# Hello World program in Python import re greeting = 'Hello World!' EOL = '\n' regex = re.compile(r'Hell') print 'Searching in: ', greeting + EOL mo = regex.search(greeting) if mo: print '"Mo" is there!' else: print '"Mo" is not at home today.'
""" A simple program to generate a simple randomized encryption / decryption functions """ import random # Ecrypt | Decrypt instuction # /r -> Replace by a random number between 0 and 255 encryptionTable = [ ["string = [e ^ /r for e in string]", "string = [e ^ /r for e in string]"], ["string = [e + /r for e in string]", "string = [e - /r for e in string]"], ["string = [e * /r for e in string]", "string = [e // /r for e in string]"], ["string = [e << 2 for e in string]", "string = [e >> 2 for e in string]"], ["string = [e << 1 for e in string]", "string = [e >> 1 for e in string]"] ] # Create a new encryption/ associated decryption algorithm def createEncryption(): # Store the generated code generatedCode = "" # Choose how much step are required to create the encryption algorithm steps = random.randint(2, 16) # Get size of the encryption table encryptionTableSize = len(encryptionTable) # New encryption/decryption algorithm table ecryptionAlgo = [] decryptionAlgo = [] # Create algorithms for _ in range(steps): # Create a new random number shared by step rng = random.randint(0, 255) # Create algorithms instructionChoosen = random.randint(0, encryptionTableSize - 1) ecryptionAlgo.append(encryptionTable[instructionChoosen][0].replace("/r", str(rng))) decryptionAlgo.insert(0, encryptionTable[instructionChoosen][1].replace("/r", str(rng))) # Generate function string - These was splited for readability generatedCode = "" # Encryption generatedCode += "def encrypt(string):\n" for i in range(steps): generatedCode += " " * 2 + ecryptionAlgo[i] + "\n" generatedCode += " " * 2 + "return string\n" # Dencryption generatedCode += "def decrypt(string):\n" for i in range(steps): generatedCode += " " * 2 + decryptionAlgo[i] + "\n" generatedCode += " " * 2 + "return string\n" return generatedCode def generateArray(string): """ Create a array containing char id """ output = [] for char in string: output.append(ord(char)) return output def arrayToString(array): return "[" + ", ".join([str(e) for e in array]) + "]" arrayHelloWord = generateArray("Hello World!") algorithms = createEncryption() testCode = "array =" + arrayToString(arrayHelloWord) + "\n" testCode += algorithms testCode+= """ def arrayToOutput(array): output = "" for e in array: output += chr(e) return output print("Input array: ", array) print(arrayToOutput(array)) print("Encrypting...") array = encrypt(array) print(array) print("Decrypting...") array = decrypt(array) print(array) print(arrayToOutput(array)) """ print("GENERATED CODE:\n", testCode) print("===========================") exec(testCode)
"""Реализация класса модифицированного многомерного линейного генератора и вспомогательных функций""" import math from typing import Callable, List def bits_number(num): """Возвращает количество бит, необходимое для представления числа в двоичном виде""" return math.floor(math.log2(num)) + 1 def nums_xor(nums: list): """xor массива чисел""" ret = nums[0] for n in nums[1:]: ret ^= n return ret def form_nums_list(state: int, r: int, pickup_list: List[int]) -> List[int]: """Формирует список значений из ячеек state указанных в pickup_list""" # возвращаемый список ret = [] # маска для получения значения ячейки, состоит из r единиц. Для получения значения i-ой ячейки # сдвигается на i*r влево. Далее производится операция AND со значением текущего состояния # and_mask = int('1' * r, base=2) and_mask = (1 << r) - 1 # для каждой точки съема for point in pickup_list: # опреление необходимого сдвига для маски shift = r * point # вычисление значения ячейки под номером point point_val = ((and_mask << shift) & state) >> shift # добавление в массив ret.append(point_val) return ret class MMLR: """ Modified Multidimensional Linear Register Класс для формирования модифицированного многомерного линейного генератора с одной обратной связью и имитации его работы Атрибуты экземпляров: r: int n: int pp: List[int] mf: function state: int """ def __init__( self, r: int, n: int, pickup_points: List[int], modifying_func: Callable, init_state: int = 0): """ Конструктор модифицированного многомерного линейного генератора Параметры: r (int): размерность ячейки n (int): количество ячеек pickup_points (list): список номеров точек съема modifying_func (function): модифицирующее преобразование def modifying_func(x: int): int: ... init_state (int): начальное заполнение регистра """ # if r <= 0: raise Exception self.r = r # if n <= 0: raise Exception self.n = n # if len(pickup_points) <= 0 or len(pickup_points) > n: raise Exception if 0 not in pickup_points: raise Exception if set(pickup_points).difference(set(i for i in range(n))): # содержит элементы не из промежутка [0,n-1] raise Exception self.pp = pickup_points # добавить проверку аргументов функции self.mf = modifying_func # if init_state < 0: raise Exception if init_state != 0 and bits_number(init_state) > n * r: raise Exception self.state = init_state def form_pp_nums(self): """Формирует список чисел из ячеек, соответсвующих точкам съема""" return form_nums_list(self.state, self.r, self.pp) def do_shift(self, new_val: int): """Производит сдвиг регистра и записывает новое значение new_val в последнюю ячейку""" # сдвиг в сторону младшей ячейки self.state = self.state >> self.r # запись нового значения в старшую ячейку self.state = self.state | (new_val << (self.r * (self.n - 1))) def do_cycle(self): """Произвести один цикл работы генератора""" # формирование списка зачений из ячеек, соответсвующих точкам съема pp_nums = self.form_pp_nums() # xor значений точек съема xored_nums = nums_xor(pp_nums) # применение модифицирующего преобразования modified_val = self.mf(xored_nums) # сдвиг регистра и запись нового значения self.do_shift(modified_val) def get_current_state_val(self) -> int: """Возвращает значение, соответсвующее текущему состояния генератора""" return self.state def get_current_output_val(self) -> int: """Возвращает значение ячейки с наименьшим порядковым номером""" return form_nums_list(self.state, self.r, [0])[0] def get_current_state(self) -> List[int]: """Возвращает список значений ячеек, соответсвующий текущему состоянию генератора""" return form_nums_list(self.state, self.r, [i for i in range(self.n)]) def __iter__(self): return self def __next__(self): self.do_cycle() return self.get_current_output_val(), self.get_current_state_val() def do_idling(self, idling_rounds=0): ''' Проделать idling_rounds холостых ходов генератора ''' if idling_rounds < 0: raise Exception('Error: wrong idling_rounds value') if idling_rounds == 0: n = self.n else: n = idling_rounds for _ in range(n): next(self) # pass
print("Hi") integer = 5 number = 5.5 word = "string" print(integer) print(number) print(word) print("===list===") list_of_things = [ integer, 5, number, word, ] print(list_of_things) print(list_of_things[0]) list_of_things[0] = list_of_things[0] + 1 print(list_of_things[0]) print("===dictionary===") dictionary_of_things = { 'integer_key': integer, word: integer, 'list_of_things_key': list_of_things, } print(dictionary_of_things) print("===set===") # sets have distinct items set_of_things = { integer, 5, # ignored number, word, } print(set_of_things) print("===tuples===") # tuples can have duplicates tuple_of_things = ( integer, 5, # duplicates are allowed number, word, list_of_things, ) print(tuple_of_things) print(tuple_of_things[0]) #tuple_of_things[0] = tuple_of_things[0] + 1 # not allowed print("bye")
import random class Minesweeper: # Constructor def __init__(self, height, length, numbombs): # Creates a player board, a bomb board, and places the bombs self._height = height self._length = length self._numbombs = numbombs self._turnCount = 0 self._bombboard = [[0] * self._height for x in range(self._length)] self._playerboard = [["-"] * self._height for x in range(self._length)] self._placedbombs = 0 self._win = False # Creates boards and places bombs randomly for x in range(numbombs): while self._placedbombs != numbombs: self._placedbombs = 0 self._bombboard[random.randint(0,self._length-1)][random.randint(0,self._height-1)] = -1 for y in range(self._height): for x in range(self._length): if self._bombboard[x][y] == -1: self._placedbombs += 1 # Denotes each space on the bomb board with the number of bombs next to the space for y in range(self._height): for x in range(self._length): if self._bombboard[x][y] != -1: self._bombboard[x][y] = self.bombChecker(x, y) # Prints out empty board self.print() # Prints out the player board with appropriate spacing and with correctly revealed spaces def print(self): print(" ", end="") for i in range(1, len(str(self._height))): print(" ", end="") for x in range(self._length): print(str(x + 1) + " ", end="") for i in range(len(str(x + 1)), len(str(self._length))): print(" ", end="") print() for y in range(self._height): print(str(y + 1) + " ", end="") for i in range(len(str(y+1)), len(str(self._height))): print(" ", end="") for x in range(self._length): if x != self._length - 1: print(str(self._playerboard[x][y]) + " ", end="") for i in range(1, len(str(self._length))): print(" ", end="") else: print(str(self._playerboard[x][y])) # Checks to see if a space has been revealed and is on the board # Handles errors with "Invalid Input" def checkValid(self, x, y): try: if self._playerboard[x][y] == "-": return True else: print("Invalid Input") return False except Exception: print("Invalid Input") return False # Reveals a space on the player board def select(self, x, y, z=1): if self.checkValid(x, y): if self._bombboard[x][y] == -1: self._playerboard[x][y] = "B" self.print() print("Bomb! You lose.") for y in range(self._height): for x in range(self._length): if self._bombboard[x][y] == -1: self._playerboard[x][y] = "B" else: self._playerboard[x][y] = self._bombboard[x][y] self._turnCount += 1 if self._playerboard[x][y] == 0: self.revealAdj(x,y) # Checks if bomb is in the given space and if it is it moves it and then calls select on that space def selectFirst(self, x, y): if self.checkValid(x,y): # Moves bomb if in the selected space if self._bombboard[x][y] == -1: unplaced = True while unplaced: i = random.randint(0,self._length-1) j = random.randint(0,self._height-1) if self._bombboard[i][j] != -1: self._bombboard[i][j] = -1 self._bombboard[x][y] = self.bombChecker(x,y) unplaced = False # Recreates the bomb board with the newly placed bomb for m in range(self._height): for n in range(self._length): if self._bombboard[n][m] != -1: self._bombboard[n][m] = self.bombChecker(n, m) self.select(x,y) else: self.select(x,y) # Flags a space on the player board with an "F" def flag(self, x, y): if self.checkValid(x,y): if self._playerboard[x][y] == "-": self._playerboard[x][y] = "F" else: print("Invalid Input") # Unflags a space on the player board if it has an "F" # Handles errors with try, except def unflag(self, x, y): try: if self._playerboard[x][y] == "F": self._playerboard[x][y] = "-" else: print("Invalid Input") except Exception: print("Invalid Input") # Checks if the game has been won or lost yet def checkStatus(self): progress = 0 # Counts the number of spaces revealed so far # Checks if any bombs have been revealed for y in range(self._height): for x in range(self._length): if self._playerboard[x][y] == "B": return False if str(self._playerboard[x][y]).isdigit(): progress += 1 # Checks if the spaces revealed is the total number of non-bomb spaces if progress == self._length * self._height - self._numbombs: print("You win!") self._win = True return False # If not then the game goes on else: return True # Reveals all the adjacent spaces on the player board and calls itself again if any of those are a zero def revealAdj(self, x, y): xstart = 0 xend = 3 ystart = 0 yend = 3 if x == 0: xstart = 1 if x == self._length-1: xend = 2 if y == 0: ystart = 1 if y == self._height-1: yend = 2 for j in range(ystart,yend): for i in range(xstart,xend): if self._playerboard[x+i-1][y+j-1] == "-": self.select(x+i-1,y+j-1) # Checks to see how many bombs are next to a space and returns it def bombChecker(self, x, y): bombs = 0 xstart = 0 xend = 3 ystart = 0 yend = 3 if x == 0: xstart = 1 if x == self._length - 1: xend = 2 if y == 0: ystart = 1 if y == self._height - 1: yend = 2 for j in range(ystart,yend): for i in range(xstart,xend): if self._bombboard[x+i-1][y+j-1] == -1: bombs += 1 return bombs # Asks the player for input and executes the appropriate commands def turn(self): while self.checkStatus(): type = "" if self._turnCount != 0: type = input("“select” or “flag” or “unflag”? ") x = input("Select an x coordinate: ") # Checks to make sure 'x' is valid while not x.isdigit() or int(x) <= 0 or int(x) > self._length: print("Invalid Input") x = input("Select an x coordinate: ") y = input("Select a y coordinate: ") # Checks to make sure 'y' is valid while not y.isdigit() or int(y) <= 0 or int(y) > self._height: print("Invalid Input") y = input("Select a y coordinate: ") # Converts x and y into integers x = int(x) y = int(y) # Calls the appropriate method # If the user input for what action to take doesn't match "flag" or "unflag", select is called if type == "unflag": self.unflag(x - 1, y - 1) elif self.checkValid(x-1,y-1): if self._turnCount == 0: self.selectFirst(x-1,y-1) elif type == "select": self.select(x-1,y-1) elif type == "flag": self.flag(x-1,y-1) else: print("Invalid Input") self.print() # Returns true if the player won the game and false if they lost def getWin(self): return self._win # Returns the board with all of the spaces revealed # Bombs marked as 'B' def _getSolution(self): for y in range(self._height): for x in range(self._length): if self._bombboard[x][y] == -1: self._bombboard[x][y] = "B" return self._bombboard
#11. Write a Python program to find the greatest common divisor (gcd) of two integers. def gdc(x, y): if y == 0: return x else: print "y is: ", y print "Modulo is:", x%y return gdc(y, x % y) print gdc(24, 18)
#29. Write a Python program to separate and print the numbers and their position of a given string. import re my_string = "The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly." p = re.search(r'\d+', my_string) print p.span() print "---------------------" #30. Write a Python program to abbreviate 'Road' as 'Rd.' in a given string. str_1 = "Road, sixty six." p = re.sub('Road', 'Rd.', str_1) print p print "--------------------" #31. Write a Python program to replace all occurrences of space, comma, or dot with a colon. str_2 = "Road, sixty six." pattern = r"\,|\ |\." replace = re.sub(pattern, ":", str_2) print replace print '--------------------' #32. Write a Python program to replace maximum 2 occurrences of space, comma, or dot with a colon. text = 'Python Exercises, PHP exercises.' pattern = r"[ ,.]" rep = re.sub(pattern, ":", text, 2) print rep
#1. Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included). new_list = [] for i in range(1500, 1700): if i % 7 == 0 and i % 5 == 0: new_list.append(str(i)) print ",".join(new_list) #2. Write a Python program to convert temperatures to and from celsius, fahrenheit. x = raw_input("would you like to convert fahrenheit(f) or celsius(c)?") if x == "c": d = raw_input("how much would you like to convert?") z = (int(d) * 1.8) + 32 print "{0} celsius is {1} farenheit".format(d, z) else: k = raw_input("how much would you like to convert?") y = (int(k) - 32) / 1.8 print "{0} celsius is {1} farenheit".format(k, y)
#2. Write a Python program that matches a string that has an a followed by zero or more b's. from re import * p = compile(r'[ab*]') m = p.search("ac") if m: print 'Match found' else: print 'No match'
#ex24 Write a Python program to check whether a string starts with specified characters str1 = 'Karolina' if str1.startswith('Kar', 0, 3): print True #ex25 Write a Python program to create a Caesar encryption
x = {"a","b","c","d","e"} y = {"b","c"} x.difference_update(y) print x #9. Write a Python program to create a symmetric difference. s = set("ABC") t = frozenset('bookBC') print s ^ t #10. Write a Python program to issubset and issuperset. num_set = set([0, 1, 2, 3, 4, 5]) v = set([0, 1, 2, 8, 9, 10]) print "-----------------" print num_set.issubset(v) print num_set.issuperset(v) #11. Write a Python program to create a shallow copy of sets. my_set = set([0, 1, 2, 3, 4, 5]) my_set.add(7) set_copy = my_set.copy() set_copy.add(6) print my_set print set_copy
#34. Write a Python program using Sieve of Eratosthenes method for computing primes upto a specified number. def computing_primes(number): non_prime_nums = [] prime_nums = [] lenght = range(2, number+1) for i in lenght: if i not in non_prime_nums: prime_nums.append(i) for j in range(i*i, number+1, i): non_prime_nums.append(j) return prime_nums # func call print computing_primes(40) #35. Write a Python program to create a list by concatenating a given list which range goes from 1 to n. def concatenating_list(sample_list, n): lenght = range(1, n+1) for j in lenght: for i in sample_list: add = i + str(j) print add print concatenating_list(["p", "q"], 5) #36. Write a Python program to get variable unique identification number or string. x = 10 print id print format(id(x), 'x') s = 'w3resource' print(format(id(s), 'x'))
#ex38 Write a Python program to count occurrences of a substring in a string. #ex39 Write a Python program to reverse a string. #ex40 Write a Python program to reverse words in a string. #ex41 Write a Python program to strip a set of characters from a string. def occurances_count(word): dict = {} for letter in word: keys = dict.keys() if letter in keys: dict[letter] += 1 else: dict[letter] = 1 return dict print occurances_count("kot is nice and warm") str1 = 'The quick brown fox jumps over the lazy dog.' print(str1.count("jumps")) def reversed_words(sentence): return ''.join(reversed(sentence)) print reversed_words('The quick brown fox jumps over the lazy dog.') def reversed_words(sentence): return ' '.join(word[::-1] for word in sentence.split()) print('\n') print reversed_words('The quick brown fox jumps over the lazy dog.') seq = '888The quick brown fox jumps over the lazy dog.88888888' new_seq = seq.strip('8') print new_seq def characters_strip(seq, chars): return ''.join(c for c in seq if c not in chars) print characters_strip('The quick brown fox jumps over the lazy dog.', 'a') #ex42 Write a python program to count repeated characters in a string import collections the_string = 'thequickbrownfoxjumpsoverthelazydog' results = collections.Counter(the_string) print(results) import collections str1 = 'thequickbrownfoxjumpsoverthelazydog' d = collections.defaultdict(int) for c in str1: d[c] += 1 for c in sorted(d, key=d.get, reverse=True): if d[c] > 1: print('%s %d' % (c, d[c]))
#7. Write a Python program to find sequences of lowercase letters joined with a underscore. import re def match_text(string): p = re.search(r'\_\w', string) #QUESTION if p: print True else: print False match_text("t_b")
#5. Write a Python program to sort a list of elements using the selection sort algorithm. sample_Data = [14,46,43,27,57,41,45,21,70] for k in range(0,len(sample_Data) -1): minIndex = k for i in range(k+1,len(sample_Data)): if sample_Data[i] < sample_Data[minIndex]: minIndex = i if minIndex != k: sample_Data[k], sample_Data[minIndex] = sample_Data[minIndex], sample_Data[k] print sample_Data print "------------------" #6. Write a Python program to sort a list of elements using the insertion sort algorithm. lst = [14,46,43,27,57,41,45,21,70] for i in range(1, len(lst)): for j in range(i - 1, -1, -1): if lst[j] > lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] else: break print lst
#3. Write a Python program that matches a string that has an a followed by one or more b's import re def text_match(string): pattern = 'b+a' p = re.match(pattern, string) if p: print True else: print False text_match("ddd") print '---------------------' #4. Write a Python program that matches a string that has an a followed by zero or one 'b'. def search_text(str1): p = re.match(r'b?a', str1) if p: print "Match found" else: print "No results" search_text("c")
#38. Write a Python program to display astrological sign for given date of birth. day_of_birth = int(raw_input("Please eneter day of your birth: ")) month_of_birth = raw_input("Please eneter month of your birth: ") if day_of_birth > 21 and month_of_birth == "March" or day_of_birth > 20 and month_of_birth == "April": sign = "Aries" elif day_of_birth < 21 and month_of_birth == "April" or day_of_birth < 21 and month_of_birth == "May": sign = "Taurus" elif day_of_birth > 22 and month_of_birth == "May" or day_of_birth > 21 and month_of_birth == "June": sign = "Gemini" elif day_of_birth < 22 and month_of_birth == "June" or day_of_birth < 22 and month_of_birth == "July": sign = "Cancer" elif day_of_birth > 23 and month_of_birth == "July" or day_of_birth > 22 and month_of_birth == "August": sign = "Leo" elif day_of_birth < 23 and month_of_birth == "August" or day_of_birth < 23 and month_of_birth == "September": sign = "Virgo" elif day_of_birth > 24 and month_of_birth == "September" or day_of_birth > 23 and month_of_birth == "October": sign = "Libra" elif day_of_birth < 24 and month_of_birth == "October" or day_of_birth < 22 and month_of_birth == "November": sign = "Scorpio" elif day_of_birth > 23 and month_of_birth == "November" or day_of_birth > 21 and month_of_birth == "December": sign = "Sagittarius" elif day_of_birth < 22 and month_of_birth == "December" or day_of_birth < 20 and month_of_birth == "January": sign = "Aquarius" else: sign = "Pisces" print "Your sign is:", sign
def new_string(str1): str2 = str1[-1] + str1[1:-1] + str1[0] return str2 print new_string('kocikot')
#34. Write a Python program to check a triangle is valid or not. side1 = int(raw_input("Please enter the length of side1: ")) side2 = int(raw_input("Please enter the length of side2: ")) side3 = int(raw_input("Please enter the length of side3: ")) if side1 + side2 > side3 and side3 + side2 > side1 and side1 + side3 > side2: print "Triange is valid" else: print "Triange is not valid" #35. Write a Python program to check a string represent an integer or not. import re user_input = raw_input("Please enter a string: ") if not user_input.isdigit(): print "The string is not an integer." if re.search("[0-9]", user_input): print "The string is an integer." else: print "The string is not an integer."
def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" print "We can just give the function numbers directly:" cheese_and_crackers(10, 20) print "OR, we can use variables from our script:" amount_of_cheese = 10 amount_of_crackers = 20 cheese_and_crackers(amount_of_cheese, amount_of_crackers) print "We can even do math inside too:" cheese_and_crackers(10 + 20, 5 + 6) print "And we can combine the two, variables and math:" cheese_and_crackers (amount_of_cheese + 100, amount_of_crackers + 1000) # Mistakes -> INDENTATION! def math_and_calculation(num1, num2): print "Number one equals %r" % num1 print "Number two equals %r" % num2 print "All looks nice!" print "Thank you!\n" print "I am calling the function" math_and_calculation(2, 5) print "The result of addition is:" math_and_calculation(10 + 5, 1 + 3) print "I am declaring 2 new variables" number1 = 6 number2 = 20 math_and_calculation(number1, number2) print "Adding varibles and integers" math_and_calculation(number1 + 10, number2 + 5) print "Why don't you put your numbers:" number1 = int(raw_input("Enter the first number: ")) number2 = int(raw_input("Enter the first number: ")) math_and_calculation(number1, number2)
#15. Write a Python program to get the length of an array. from array import array my_array = array("c", "kot") num_array = array("i", [1, 2, 3, 4, 5]) print "Lenght of the array is:" print len(my_array) print len(num_array) #16. Write a Python program to convert an array to an ordinary list with the same items. number_array = array("i", [1, 2, 3, 4, 5]).tolist() print "Array to list:" print number_array #17. Write a Python program to convert an array to an array of machine values and return the bytes representation. import binascii an_array = array("i", [11, 12, 13, 14, 15]) print binascii.hexlify(an_array)
name = len("kocikot") print name def string_length(str1): count = 0 for char in str1: count += 1 return count print(string_length('kot')) name = 'kot' print name[1]
#7. Write a Python program to sort a list of elements using shell sort algorithm. def shellSort(sample): lenght = len(sample) gap = lenght/2 while gap >=1: i=gap while(i < lenght): value = sample[i] j=i while(j -gap >=0 and value < sample[j-gap]): sample[j] = sample[j - gap] j-=gap sample[j] = value i +=1 gap /=2 print shellSort([3, 5, 9, 2, 4, 7])
#11. Write a Python program that matches a word at end of string, with optional punctuation. import re theStr = "Owl eats everything and even more." p = re.match(r'[a-zA-Z0-9]+$|[a-zA-Z0-9]+\.$', theStr) if p: print "Word matches!" else: print "No match found!"
#6. Write a Python program to count the number of even and odd numbers from a series of numbers. numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) even_nums = 0 odd_nums = 0 for num in numbers: if num % 2 == 0: even_nums += 1 else: odd_nums +=1 print "Number of enven number is: {0}".format(even_nums) print "Number of odd number is: {0}".format(odd_nums) #7. Write a Python program that prints each item and its corresponding type from the following list. datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A'}] for i in datalist: print "Type of {0} is {1}".format(i, type(i)) print "=================" #8. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. for i in range(0,6): if i == 3 or i==6: continue print i
#13. Write a Python program to map two lists into a dictionary. keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') l = dict(zip(keys,values)) print l print "----------------" new_dic = {k:v for k,v in zip(keys, values)} print new_dic #14. Write a Python program to sort a dictionary by key. d1 = {'food': 'spam', 'age': 42, 'name': 'Monty'} for k,v in sorted(d1.items(),key = lambda x: x[0]): print k,v print "----------------" color_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'} for key in sorted(color_dict): print "{0} = {1}".format(key, color_dict[key]) #15. Write a Python program to get the maximum and minimum value in a dictionary. d2 = {'food': 1, 'age': 42, 'name': 30} print "----------------" print max(d2, key= lambda x: d2[x]) print min(d2, key= lambda x: d2[x]) import operator result = max(d2.iteritems(), key=operator.itemgetter(1)) result1 = min(d2.iteritems(), key=operator.itemgetter(1)) print "----------------" print result print result1
def odd_index_remove(str1): str2 =str1[0::2] return str2 print odd_index_remove('dupa') def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print (word_count("kot is kot firend")) def word_count_occurances(str1): words = str1.split() for word in words: if word in words > 1: return word + ' = ' + str(1) else: return word + str(1) return words print (word_count_occurances("this is cat"))
#33. Write a Python program to find all five characters long word in a string. import re my_string = 'Pytho Exercises, PHPis exercises.' pattern = re.findall(r'\b\w{5}\b', my_string) print pattern #34. Write a Python program to find all three, four, five characters long words in a string. text = 'Pytho Exercises and PHPI exercises.' pattern = re.findall(r'\b\w{3,5}\b', text) print pattern #35. Write a Python program to find all words which are at least 4 characters long in a string. text1 = 'Pytho Exercises and PHPI exercises.' pattern1 = re.findall(r'\b\w{4,}\b', text) print pattern1
print "I will now count my chickens:" #How many chicekns do I have? print "Hens", 25+30/6 #Amount of hens print "Roosters", 100-25*3 % 4 #Amount of Roosters print "Now I will count the eggs:" #Amount of eggs print 3+2+1 -5 + 4 % 2 -1 / 4+6 print "Is it true that 3 + 2 < 5 - 7?" #Boolean check print 3+2 < 5 - 7 print "What is 3+2?", 3+2 print "What is 5 - 7?", 5-7 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5>=-2 print "Is it less or equal", 5 <= -2 print 7.0/4.0 print 7/4
#3. Write a Python program to append text to a file and display the text. foo = open("C:\case_test.txt", "r+") data = foo.write("Hello Python. I love you.\n") print foo.read() foo.close()
#write a program to take 2 numbers from the user #then take option to add/subtract/multiple/divide #and perform that operation a=int(input("enter value of a")) b=int(input("enter value of b")) c=a+b print(c)
#wite a program to print a function of addition and subtraction a=10 b=20 def add(): return a+b def sub(): print(a-b) return result=add() result=sub() print(result)
## Dictionary ( key and value) # ---------------------------- # - O notation # - Key is unique # - Order doesn't matter d = {'nok' : 1, "ok": 2} print(d['ok']) d['nok'] = 3 print(d['nok']) for key in d: print(key, d[key]) for k, v in d.items(): print(k, v) # Nested dict d = {"ok": 2, "nok": 3} c = 0 while c < 3: d = {"ok" : [d]} c += 1 print(d) d['ok'][0]['ok'][0]['ok'][0]['nok'] = 30 print(d)
D1 = {'ok' : 1, 'nok': 2} D2 = {'ok': 2, 'new': 3} # Create Below # 1. Union of keys, # values does not matter # D_Union = {'ok': 1, 'nok': 2, 'new': 3} # solution: D3 = D1.copy() for d in D2: D3[d] = D2[d] print(D3) # 2. Intersection of keys; # values doesnot matter # D_Intersection = {'ok': 1} #solution: D3 = {} for d in D1: if d in D2: D3[d] = D1[d] print(D3) # 3. Difference # D1 - D2 = {'nok': 2} # solution: D3 = {} for d in D1: if d not in D2: D3[d] = D1[d] print(D3) # 4. Sum # # values are aded for same keys # D_merge = {'ok': 3, 'nok': 2, 'new': 3} # solution: D3 = D1.copy() for d in D2: if d in D3: D3[d] += D2[d] else: D3[d] = D2[d] print(D3)
import math cat1 = input ("ingrese el cateto 1:") cat2 = input ("ingrese el cateto 2:") def hip(): return math.sqrt(cat1*2 + cat2*2) print "hipotesa es:",hip
import addmath def isPalindrome(n): n=str(n) if(len(n)<1): return True if(n[0]!=n[-1]): return False return isPalindrome(n[1:-1]) numbers=set() def lychrel(n): for i in range(50): n+=int(str(n)[::-1]) if(isPalindrome(n)): return False return True tot=0 for i in range(1, 10000): if(lychrel(i)): tot+=1 print(tot)
import itertools def digitCommonButNotZero(num1, num2): num1=str(num1) num2=str(num2) if '0' in num1 or '0' in num2: return False for char in num1: if char in num2 and char!='0': return char return False def testProperty(num, denom): char = digitCommonButNotZero(num, denom) if not char: return False if num>=denom: return False num2=int(str(num).replace(char, '', 1)) denom2=int(str(denom).replace(char, '', 1)) if num/denom == num2/denom2: return True return False fractions=[] for num in range(10, 100): for denom in range(10, 100): if testProperty(num, denom): fractions.append((num, denom)) print(fractions)
def reverse(n): assert type(n) == int return int(str(n)[::-1]) def reversible(n): k = n + reverse(n) for char in str(k): if int(char) % 2 == 0: return False return k r_set = set() for n in range(10**9): if n in r_set: continue if reversible(n): print(n) r_set.add(n) r_set.add(reverse(n))
import math def isPrime(n): if n<=1: return False if n==2: return True elif n%2==0: return False for i in range(2, math.ceil(math.sqrt(n))+1): if(n%i==0): return False return True primes=[] for i in range(2, 2000000): if(isPrime(i)): primes.append(i) print(sum(primes))
def factorial(n): product=1 for i in range(n,1,-1): product*=i return product product=str(factorial(100)) sum=0 for digit in product: sum+=int(digit) print(sum)
import addmath import itertools primes=[2, 3, 5, 7, 11, 13, 17] def has_property(number): d1=1 while(d1+2<10): d2=d1+1 d3=d1+2 if(int(str(number)[d1]+str(number)[d2]+str(number)[d3])%primes[d1-1]!=0): return False d1+=1 return True sumall=0 for perm in itertools.permutations([0,1,2,3,4,5,6,7,8,9],10): perm=addmath.number_from_digits(perm) if(has_property(perm)): print(perm) sumall+=int(perm) print(sumall)
import addmath numer=2 denom=3 count=0 for i in range(1000): numer+=2*denom denom=numer-denom print(numer, denom) if(len(str(numer))>len(str(denom))): count+=1 print(count)
def isPrime(n): if n == 2: return True elif n == 3: return True if n % 2 == 0: return False elif n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True n = 2 sum = 0 while n < 2000000: if isPrime(n): sum += n n += 1 print(n) print(sum)
#Problem 9 #Ask user for three item prices, and quantitys and calculates cost, with tax #User inputs informaiton for price and Quantity Item= input("enter price of item 1 $:") Quantity= input("enter the quantity of item 1:") Item2= input("enter the price of item 2 $:") Quantity2= input("enter the quantity of item 2:") Item3= input("enter the price of item 3 $:") Quantity3= input("enter the quantity of item 3:") #Converts user inputs into floats for $value i1=float(Item) q1=float(Quantity) i2=float(Item2) q2=float(Quantity2) i3=float(Item3) q3=float(Quantity3) #Calculate the subtotal, tax, and total for the floaats Subtotal = ((i1*q1)+(i2*q2)+(i3*q3)) tax= Subtotal*.055 total= Subtotal + tax #Prints output for user Subtotal, tax and total print("Subtotal", "$",Subtotal) print("tax", "$",tax) print("total", "$",total)
# WARNING: ЭТОТ ФАЙЛ ОТДЕЛЬНО ЗАПУСКАТЬ НЕ НУЖНО # НУЖНО ЗАПУСКАТЬ ТОЛЬКО main.py import re def read_data(filename): with open(filename, 'r') as file: data = file.read() text_info = re.findall('[a-zA-Z.]+', data) data = re.sub(',', '.', data) text_info = list(text_info) columns = text_info[:2] units = text_info[2:4] data = re.split('[\s]', data)[4:] data = [float(i) for i in data] data_x = data[::2] data_y = data[1::2] return [data_x, data_y] def write_data(filename, list1, list2): with open(filename, 'w+') as file: for i, j in zip(list1, list2): file.write('{}\t{:f}\n'.format(i, j))
import logging logging.basicConfig(filename="mylog.txt",level=logging.INFO) logging.info("A New request came:") try: x=int(input("Enter the first number: ")) y=int(input("Enter the second number: ")) print(x/y) except ZeroDivisionError as msg: print("Cannot divided with Zero") logging.exception(msg) except ValueError as msg: print("Enter only int values") logging.exception(msg) logging.info("request processing completed")
class Solution: def isPalindrome(self, s: str) -> bool: import re s1 = re.sub('[^a-zA-Z0-9]',' ',s) s1 = s1.lower() s1 = s1.split() s1 = ''.join(s1) s2 = s1[::-1] #print(s1,s2) if(s1==s2): return True else: return False
# # @lc app=leetcode id=2 lang=python3 # # [2] Add Two Numbers # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode(None) ans = head value = 0 while l1 or l2 or value: if l1: value += l1.val l1 = l1.next if l2: value += l2.val l2 = l2.next head.next = ListNode(value%10) value = value // 10 head = head.next return ans.next
# # @lc app=leetcode id=48 lang=python3 # # [48] Rotate Image # """ If we want to rotate the matrix by 90 degrees(clockwise), we can transpose the matrix first. Transposing a metrix exchanges the row and column of the same index: 1st row becomes 1st column, 2nd row becomes 2nd column etc. Rotating the matrix by 90 degree(clockwise) puts the 1st row to the last column, 2nd row to the 2nd-to-last column. so we reverse each row after transposing the matrix. For example: [1,2,3] will become [1,4,7] after transpose. Then we reverse every rows so we get:[7,4,1] [4,5,6] [2,5,8] [8,5,2] [7,8,9] [3,6,9] [9,6,3] If we want to rotate the matrix counterclockwise, we can exchange the corresponding rows after we transpose the matrix. (1st row becomes the last row, 2nd row becomes the 2nd-to-last row etc.) """ class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in range(n): for j in range(n): if i < j: matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for l in matrix: l.reverse()
# -*- coding: utf-8 -*- class Solution(object): """ We can think a line of zigzag pattern is an item of a list. And the result of zigzag string is the join of list. So we sequentially generated the zigzag list and join it. The time complexity is O(n). """ def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ step = (numRows == 1) - 1 l = [''] * numRows i = 0 for c in s: if i == 0 or i == numRows - 1: step = - step l[i] += c i += step return ''.join(l) if __name__ == '__main__': test_str1 = 'PAYPALISHIRING' s = Solution() assert s.convert(test_str1, 3) == 'PAHNAPLSIIGYIR'
# # @lc app=leetcode id=61 lang=python3 # # [61] Rotate List # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if k == 0: return head h = head n = 0 while h: n += 1 h = h.next if n <= 1 or n == k or k % n == 0: return head if k > n: k = k % n t = k fast = head while t > 0: t -= 1 fast = fast.next slow = head while fast.next: slow = slow.next fast = fast.next tmp = slow.next slow.next = None fast.next = head return tmp
#1 Position arguments #2 Default argument #3 keyword argument #4 variable length positional args #5 varibale length keyword args # LINEAR SEARCH : def linear_search(l,key): for value in l: if value == key: return True else: return False l = [100,200,300,400,500] key = 400 result = linear_search(l,key) print(result) # password gen import random def gen_password(): l = ['@','#','$','&'] upper = chr(random.randint(65,90)) lower = chr(random.randint(97,122)) special = random.choice(l) digit = random.randint(10000,99999) password = upper + lower + special + str(digit) return password result = gen_password() print(result) def gen_password(length = 8): l = ['@','#','$','&'] upper = chr(random.randint(65,90)) lower = chr(random.randint(97,122)) special = random.choice(l) digit = random.randint(10000,99999) password = upper + lower + special + str(digit) l = random.sample(password,length) password = ("").join(l) return password result = gen_password(5) print(result) # keyword argument def validate(username,password): if username == "ABC" and password == "Abc@123": print("Valid password") else: print("invalid password") validate("ABC","Abc@123") validate(password = "Abc@123",username="ABC") help(print) print(100,200,sep=",",end=" ") print("HIs") #4 variable length argument in py def add_value(*args): l = [] for value in args: l.append(value) return l result = add_value(100,200,300,400,500) print(result) result = add_value(100,200,300,400,500,39904,435363,6,54546) print(result) #5 def get_details(**l): print(l) get_details(name="Gaurav",email = "gaurav@gmail.com",mob_no= 7875239235,dob = "12-07-2001") get_details(name="Gaurav",email = "gaurav@gmail.com",mob_no= 7875239235) get_details(name="Gaurav",mob_no= 7875239235)
# Conditional statements #1 if_else : #if [condition]: # statements #else : # statements a = 100 b = 200 if a > b: print("a is greater") elif b > a: print("b is greater") else: print("both equal") #2 For loop # Iterable datatypes : str , list , tuple , dict # for [variable_name] in [Iterable datatype]: l = [10,20,30,40,50] for value in l: print(value) # for counting sum sum = 0 for value in l: sum = sum + value print(sum) # for sum of 1st 20 num : 1-20 # by using range function sum = 0 for value in range(1,20): print(value) for value in range(20,1000,20): print(value) #break #continue l = [1,2,3,4,5,6] key = 4 for value in l: if value == key: print("element found") break else: continue else: print ("Element not found") print("Gaurav") # enumerate # pass for index,value in enumerate(l): print(index,value) if value == key: print("element found") break else: pass print("Gaurav") else: print ("Element not found") # 3 While loops in python # while [condition]: # [statments] #else # sum of 1-20 num count = 1 sum = 0 while count <= 20: sum = sum +count count = count +1 print(sum)
#1 map def sqr(num): return num**2 l = [10,20,30,40,50] result = list(map(sqr,l)) print(result) for value in result: print(value) def add(a,b): return a + b l1 = [100,200,300,400,500] l2 = [10,20,30,40,50] result = list(map(add,l1,l2)) print(result) def check_num(num): if num % 2== 0: return True else: return False l = [100,115,200,117,402,408] result = list(map(check_num,l)) print(result) #2 filter def check_num(num): if num % 2== 0: return True else: return False l = [100,115,200,117,402,408] result = list(filter(check_num,l)) print(result) #3 lambda l = [10,20,30,40,50] result = list(map(lambda num1:num1**2,l)) print(result) l = [100,115,200,117,402,408] result = list(filter(lambda num:num % 2== 0,l)) print(result) d = {1:50,2:40,3:30,4:20,5:50} l = sorted(d.items()) print(l) d = {8:50,3:40,2:30,1:20,5:10} l = dict(sorted(d.items(),key = lambda x: x[1])) print(l)
""" Summation of primes """ import math def is_prime(number): n = 2 while n <= math.sqrt(number): if number % n == 0: return False n += 1 return True primes = [n for n in range(2, 2_000_000) if is_prime(n)] print('Sum of primes:', sum(primes))
""" Sum square difference """ import argparse parser = argparse.ArgumentParser() parser.add_argument('number', type=int) def sum_of_squares(limit): """ Limit is inclusive """ result = 0 for n in range(1, limit+1): result += n**2 return result def square_of_sum(limit): """ Limit is inclusive """ result = 0 for n in range(1, limit+1): result += n return result**2 if __name__ == '__main__': args = parser.parse_args() difference = abs(square_of_sum(args.number) - sum_of_squares(args.number)) print('difference:', difference)
#Write a program which reads user input until they say done #Then print largest and smallest numbers largest = None smallest = None while True: CurrentValue = input("Enter a number: ") if CurrentValue == 'done': break else: try: CurrentValue = int(CurrentValue) if largest == None: largest = CurrentValue elif CurrentValue > largest: largest = CurrentValue if smallest == None: smallest = CurrentValue elif CurrentValue < smallest: smallest = CurrentValue except: print('Invalid input') continue print('Maximum is ',largest) print('Minimum is ',smallest)
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Author : Vant # @Time : 2018/1/23 15:51 # @Email : 944921374@qq.com # @File : demo5.py # @Description:索引,根据位置找到对应的值 import numpy as np A = np.arange(3,15) print(A) print(A[3]) B = A.reshape((3,4)) print(B) print(B[1][1]) print(B[2][1]) print(B[2,:])#输出第三行所有数 #只能输出行,不能输出列,另一种方法输出列 for row in B: print(row) #这是输出列,每一个迭代出来 for col in B.T: print(col) #迭代出项目,只输出一行 for item in B.flat: print(item)
def mainMenu(): message =""" Main Menu:\n ----------------------------------------\n Press 1 to add a task Press 2 to view all tasks Press 3 to delete a task Press q to quit ****************************************\n """ print(message) tasks = [] def addTask(): task = input("What task do you need to complete?\n") priority = input("Is this task a high, medium, or low priority?\n") taskItem = {"task": task, "priority": priority} tasks.append(taskItem) print("|Task: %s - Priority: %s| has been added successfully!\n****************************************\n" % (task, priority)) startApp() def viewTask(): print("List of Tasks\n****************************************\n") counter = 1 for item in tasks: print(counter,": ", item) counter += 1 startApp() def delTask(): print("List of Tasks to be Deleted\n****************************************\n") counter = 1 for item in tasks: print(counter,": ", item) counter += 1 delete = int(input("Please select the number of the task you would like to delete.\n")) tasks.pop(delete - 1) print("Task was deleted successfully!\n****************************************\n") startApp() def startApp(): mainMenu() action = input("Please select a menu option.\n****************************************\n") if action == "1": addTask() elif action == "2": viewTask() elif action == "3": delTask() elif action == "q": exit() else: print("****************************************\nPlease enter a valid menu option.\n****************************************\n") startApp() startApp()
import matplotlib.pyplot as plt import numpy as np #Multivariate normal distribution is used when we have more than one feature # Suppose we have two features, then we need to provide two means and 2*2 covariance matrix u1=np.array([2,4]) cov_1=np.array([[1,-0.6],[-0.6,1]]) apple=np.random.multivariate_normal(u1,cov_1,400) print(apple.shape) u2=np.array([7,12]) cov_2=np.array([[1,0],[0,1]]) mango=np.random.multivariate_normal(u2,cov_2,300) print(mango.shape) plt.scatter(mango[:,0],mango[:,1],label="Mango") plt.scatter(apple[:,0],apple[:,1],label="Apple") plt.legend() plt.show() #Generating Y and combining apples and mangoes into fruits Y=np.zeros(700) Y[:400]=1 X=np.vstack((apple,mango)) plt.scatter(X[:,0],X[:,1],c=Y) plt.show() print(X.shape)
#Given an array of strings, return another array containing all of its longest strings. def allLongestStrings(inputArray): # find longest string in array and return all strings of that len #keep longest out of for loop to keep it from changing longest = 0 #finds the longest array in inputArray for i in inputArray: length = len(i) if length > longest: longest = length #make array to return arr = [] #append all from inputArray where len == longest for i in inputArray: if len(i) == longest: arr.append(i) #return arr return arr
# You are given an array of integers representing coordinates of obstacles situated on a straight line. # Assume that you are jumping from the point with coordinate 0 to the right. # You are allowed only to make jumps of the same length represented by some integer. # Find the minimal length of the jump enough to avoid all the obstacles. # Example # For inputArray = [5, 3, 6, 7, 9], the output should be # avoidObstacles(inputArray) = 4. def avoidObstacles(inputArray): i = 0 j = 1 while i < max(inputArray): i += j if i in inputArray: j += 1 i = 0 return j
# Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. # One of your friends has an awful writing style: he almost never starts a message with a # capital letter, but adds uppercase letters in random places throughout the message. # It makes chatting with him very difficult for you, so you decided to write a plugin # that will change each message received from your friend into a more readable form. # Implement a function that will change the very first symbol of the given message to # uppercase, and make all the other letters lowercase. # Example # For message = "you'll NEVER believe what that 'FrIeNd' of mine did!!1", # the output should be # fixMessage(message) = "You'll never believe what that 'friend' of mine did!!1". def fixMessage(message): return message[0].upper() + message[1:].lower() #return message...()
from main import * def beta98_landed(player): os.system('cls') slowText("\n\nYou have arrived at Planet Beta-98. On this planet, there are multiple places that you can go. You can go to the Launch Pad, the Supply Store, the Hotel, or to the Cryo-Sleep Station.") beta98_main(player) def beta98_main(player): repeat = True while repeat: repeat = False slowText("\nWhat would you like to do? ") choice = input(">") choice = choice.strip() choice = choice.lower() if otherWords(player, choice): repeat = True elif choice.find("launch") > -1 or choice.find("pad") > -1 or choice.find("travel") > -1: beta98_launchPad(player) elif choice.find("store") > -1 or choice.find("supplies") > -1 or choice.find("buy") > -1: beta98_store(player) elif choice.find("hotel") > -1 or choice.find("rest") > -1: beta98_hotel(player) elif choice.find("cryo") > -1 or choice.find("sleep") > -1: beta98_cryoSleep(player) else: repeat = True slowText("Sorry that is not a command.") def beta98_launchPad(player): slowText("\n\nWelcome to the Launch Pad on Planet Beta-98. For each planet that you visit, you will use up some of your fuel. Since the distances to each of the planets are not known right now, you will not know the amount of fuel used until you have reached your destination. Some of the planets will have resupply stations and some will not.") repeat = True while repeat: repeat = False slowText("\nWould you like to travel or leave the Launch Pad? ") choice = input(">").strip().lower() if otherWords(player, choice): repeat = True elif choice.find("resupply") > -1 or choice.find("buy fuel") > -1: repeat = True if player.money < (100-player.fuel): amount = player.money else: amount = 100 - player.fuel slowText("\nYou can purchase {} of fuel. How much would you like to purchase? ".format(amount)) fuel = input(">") try: player.money -= int(fuel) player.fuel += int(fuel) slowText("\nYou purchased {}% amount of fuel for ${}. Your fuel is now at {}% and you have ${} left.".format(fuel, fuel, player.fuel, player.money)) except: slowText("\nSorry but you must type a number in. ") elif choice.find("leave") > -1 or choice.find("go away") > -1 or choice.find("go back") > -1: slowText("\nLeaving the Launch Pad. ") beta98_main(player) elif choice.find("travel") > -1 or choice.find("fly") > -1: slowText("\nYou have the option to travel north, south, east, west, up, or down from Planet Beta-98. Which direction would you like to go? ") choice = input(">") if otherWords(player, choice): repeat = True elif choice.find("north") > -1: travel(player, "beta98", "north") elif choice.find("south") > -1: travel(player, "beta98", "south") elif choice.find("east") > -1: travel(player, "beta98", "east") elif choice.find("west") > -1: travel(player, "beta98", "west") elif choice.find("up") > -1: travel(player, "beta98", "up") elif choice.find("down") > -1: travel(player, "beta98", "down") else: repeat = True slowText("Sorry that is not a command.") else: repeat = True slowText("Sorry that is not a command.") def beta98_store(player): slowText("\n\nWelcome to the Beta-98 store. We have several items in our store at various prices.") repeat = True while repeat: repeat = False slowText("\nWhat would you like to purchase? ") choice = input(">").strip().lower() if otherWords(player, choice): repeat = True elif choice.find("leave") > -1 or choice.find("go away") > -1 or choice.find("go back") > -1: slowText("\nLeaving the store. ") beta98_main(player) else: if choice.find("food") > -1: slowText("\nFood cost $5 per unit. Would you like to purchase a unit of food? ") decision = input(">").strip().lower() if decision == "y" or decision == "yes": if player.money < 5: slowText("\nI'm sorry but you do not have enough money to buy food. ") repeat = True else: player.currentObjects.append("food") player.money -= 5 slowText("\nYou just purchased a unit of food.") repeat = True else: repeat = True elif choice.find("blaster") > -1: slowText("\nBlasters cost $100. Would you like to purchase a blaster? ") decision = input(">").strip().lower() if decision == "y" or decision == "yes": if player.money < 100: slowText("\nI'm sorry but you do not have enough money to buy a blaster. ") repeat = True else: player.currentObjects.append("blaster") player.money -= 100 slowText("\nYou just purchased a blaster.") repeat = True else: repeat = True elif choice.find("kit") > -1 or choice.find("emergency") > -1: slowText("\nEmergency kits cost $50. Would you like to purchase an emergency kit? ") decision = input(">").strip().lower() if decision == "y" or decision == "yes": if player.money < 50: slowText("\nI'm sorry but you do not have enough money to buy an emergency kit. ") repeat = True else: player.currentObjects.append("emergency kit") player.money -= 50 slowText("\nYou just purchased an emergency kit.") repeat = True else: repeat = True else: slowText("\nI'm sorry but we do not have a {}. ".format(choice)) repeat = True def beta98_hotel(player): #boost health 5% each night, costs $20/night, time.sleep(30)/night slowText("\n\nWelcome to the Hotel. You can sleep for as many nights as you can afford. The rate per night is $20 per night.") repeat = True while repeat: repeat = False slowText("\nHow many nights would you like to stay for? ") choice = input(">").strip().lower() if otherWords(player, choice): repeat = True elif choice.find("leave") > -1 or choice.find("go away") > -1 or choice.find("go back") > -1: slowText("\nLeaving the Hotel. ") beta98_main(player) else: try: days = int(choice) if player.money < days*20: slowText("\nI'm sorry but you do not have enough money to stay for {} nights.".format(days)) repeat = True else: slowText("\nYou are going to stay here for {} nights. Your stay will cost you ${}.".format(days, days*20)) player.money -= int(days*20) time.sleep(days*10) player.health += 5 if player.health > 100: player.health = 100 slowText("\nThat rest was great, your health is now at {}% and now you have ${}.".format(player.health, player.money)) beta98_hotel(player) except: repeat = True slowText("Sorry that is not a command.") def beta98_cryoSleep(player): #boost health to 100 slowText("\n\nWelcome to the Cryo Sleep Station. You can sleep for as many days as you would like. Since you are a traveler of this new system, there is no charge for the Cryo Sleep, but you will have to wait for the Cryo Sleep to take effect.") repeat = True while repeat: repeat = False slowText("\nHow many days would you like to sleep for? ") choice = input(">").strip().lower() if otherWords(player, choice): repeat = True elif choice.find("leave") > -1 or choice.find("go away") > -1 or choice.find("go back") > -1: slowText("\nLeaving the Cryo Sleep Station. ") beta98_main(player) else: try: days = int(choice) slowText("\nGet ready, you are about to step into the Cryo Sleep for {} days. Enjoy your rest!".format(days)) time.sleep(days) player.health = 100 slowText("\nThat rest was great, your health is now at {}%.".format(player.health)) beta98_cryoSleep(player) except: repeat = True slowText("Sorry that is not a command.")