text
stringlengths
37
1.41M
print('This is a good day to learn python') print('python is fun') print('Python strings are easy') print('Python strings use quotes') print('You can add' + 'strings to eachother') name = input('Please enter your name here') greeting = 'oh hellow, ' print(name +' '+ greeting) age = 24 Greeting = 'Hello' print(type(age)) print(type(Greeting))
#Q.1- Write a Python program to read last n lines of a file c = -1 f=open('new 1.txt','r') content=f.readlines() n=int(input("enter the number of line: ")) while c >= -n: print(content[c],end="") c= c - 1 f.close() #file=new 1.txt Hello world! Hello python! Hello java! Hello html! Hello keshav Hello yash Hello vibhor #Q.2- Write a Python program to count the frequency of words in a file. with open('new 1.txt','r') as f: content = f.read() words = content.split() s = set(words) for n in s: print(n,words.count(n)) file=new 1.txt Hello world! Hello python! Hello java! Hello html! keshav yash vibhor gurukirat #Q.3- Write a Python program to copy the contents of a file to another file with open("new 1.txt") as f: with open("new 2.txt", "w") as f1: for line in f: f1.write(line) #first file=new 1.txt keshav yash vibhor gurukirat #second file=new 2..txt keshav yash vibhor gurukirat #Q.4- Write a Python program to combine each line from first file with the corresponding line in second file. with open('new 1.txt') as f1: with open('new 2.txt') as f2: for line1,line2 in zip(f1, f2): print(line1+line2) v file=new 1.txt hello world file=new 2.txt hello keshav #Q.5- Write a Python program to write 10 random numbers into a file. Read the file and then sort the numbers and then store it to another file. import random def Rand(start, end, num): res = [] for j in range(num): res.append(random.randint(start, end)) return res num = 10 start = 20 end = 40 res = Rand(start, end, num) f=open('new 2.txt','w') for n in res: f.write(str(n)) f.write("\n") f.close() f = open('new 2.txt','r') l = f.readlines() f.close() l.sort() f = open('new 3.txt','w') for n in l: f.write(n) f.write("\n") f.close()
percentage_score=107 if((percentage_score>=80)and(percentage_score<=100)): print("A") elif((percentage_score>=73)and(percentage_score<=79)): print("B") elif((percentage_score>=65)and(percentage_score<=72)): print("C") elif((percentage_score>=0)and(percentage_score<=64)): print("D") else: print("Z")
""" 6. set 자료형 """ # 초기화 방법 data = set([1, 1, 2, 3, 4, 4, 5]) print(data) # {1, 2, 3, 4, 5} data = {1, 1, 2, 3, 4, 4, 5} print(data) # {1, 2, 3, 4, 5} # 집합 자료형의 연산 a = set([1, 2, 3, 4, 5]) b = set([3, 4, 5, 6, 7]) print(a | b) # 합집합. {1, 2, 3, 4, 5, 6, 7} print(a & b) # 교집합. {3, 4, 5} print(a - b) # 차집합. {1, 2} # 집합 자료형 관련 함수 data = set([1, 2, 3]) print(data) # {1, 2, 3} data.add(4) print(data) # {1, 2, 3, 4} data.update([5, 6]) print(data) # {1, 2, 3, 4, 5, 6} data.remove(3) print(data) # {1, 2, 4, 5, 6}
''' Draw the double pendulum ''' from __future__ import division from draw import Point, Draw from calc import DoublePendulum import pygame as pg import math fps = 60 red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) dark_blue = (0, 0, 128) white = (255, 255, 255) black = (0, 0, 0) pink = (255, 200, 200) grey = (84, 84, 84) width = 800 height = 600 def main(): ''' Run the program ''' theta1 = float(input('Theta1 (degrees): ')) theta2 = float(input('Theta2 (degrees): ')) speed1 = float(input('Vel theta1 (rad/s): ')) speed2 = float(input('Vel theta2 (rad/s): ')) theta1 *= math.pi / 180 theta2 *= math.pi / 180 m = float(input('Mass (kg): ')) l = float(input('Lenght (m): ')) pendulums = DoublePendulum(1 / fps, theta1, theta2, speed1, speed2, l, m) scale = height / 4 screen = pg.display.set_mode((width, height)) canvas = Draw(screen, width / 2, height / 3) piv = Point(0, 0) pg.init() clk = pg.time.Clock() end = False path = [] while not end: for event in pg.event.get(): if event.type == pg.QUIT: end = True screen.fill(white) theta1, theta2 = pendulums.solve() p1 = Point(math.sin(theta1) * scale, -math.cos(theta1) * scale) p2 = p1 + Point(math.sin(theta2) * scale, -math.cos(theta2) * scale) path.append(p2) canvas.draw_line(black, piv, p1) canvas.draw_line(black, p1, p2) canvas.draw_circle(red, p1, 3, 0) canvas.draw_circle(red, p2, 3, 0) canvas.draw_circle(blue, piv, 3) if len(path) > 1: for i in xrange(1, len(path)): canvas.draw_line(dark_blue, path[i], path[i - 1]) pg.display.update() clk.tick(fps) if __name__ == '__main__': main()
#Obtenga la resta de todos los elementos de una lista from functools import reduce lista = [12,14,7,21,49,23,45,46,574,32,54] restador = lambda acumulado = 0, elemento = 0: acumulado - elemento restados = reduce (restador, lista) print (restados) # Dada una lista de palabras devolver una frase from functools import reduce palabras = ['Hola', 'como', 'estan','?', 'Espero', 'que ', 'esten', 'aprendiendo','muuchoo!!'] union = lambda acumulado = '', valor = '' : acumulado + ' ' + valor frase = reduce(union, palabras) print (frase) # Dada una lista de números enteros entregue la sumatoria de todos elementos tras haber sido divididos por dos from functools import reduce lista = [12,14,7,21,49,23,45,46,574,32,54] sumador = lambda acumulado = 0, elemento = 0: acumulado + (elemento/2) sumados = reduce (sumador, lista) print (sumados) #Devuelva el promedio de una lista de números from functools import reduce lista = [12,14,7,21,49,23,45,46,574,32,54] sumador = lambda acumulado = 0, elemento = 0: acumulado + elemento promedio = reduce (sumador, lista)/len (lista) print (promedio) # Que multiplique todos los elementos de la lista entre si from functools import reduce lista = [12,14,7,21,49,23,45,46,574,32,54] multiplicador = lambda acumulado = 0, elemento = 1: acumulado * elemento multiplicado = reduce (multiplicador, lista)/len (lista) print (multiplicado)
#Implemente um algoritmo que leia um número inteiro, em seguida calcule o fatorial deste número e apresente para o usuários. #Ex: n = 4 #O Fatorial de 4 é 24 #primeira opcao de resolucao n= 4 for i in range (2,n): n = n*i print(n) #segunda opcao de resolucao fatorial= 1 n= 4 for i in range (n): fatorial= fatorial*n n= n-1 print(fatorial)
from PIL import Image from PIL import ImageDraw im = Image.open("wire/wire.png") result = Image.new("RGB", (100, 100), "white") drawer = ImageDraw.Draw(result) im_size = im.size im_x = im_size[0] im_y = im_size[1] result_size = result.size result_x = result_size[0] result_y = result_size[1] count = 0 x = 0 y = 0 len_x = result_x len_y = result_y while y < len_y: while x < len_x: # print("x={}, y={}, count={}".format(x, y, count)) drawer.point((x, y), im.getpixel((count,0))) x += 1 count += 1 x -= 1 len_x -= 1 y += 1 while y < len_y: # print("x={}, y={}, count={}".format(x, y, count)) drawer.point((x, y), im.getpixel((count,0))) y += 1 count += 1 y -= 1 len_y -= 1 x -= 1 while x >= result_x - len_x - 1: # print("x={}, y={}, count={}".format(x, y, count)) drawer.point((x, y), im.getpixel((count,0))) x -= 1 count += 1 x += 1 y -= 1 while y >= result_y - len_y: # print("x={}, y={}, count={}, result_y={}, len_y={}".format(x, y, count, result_y, len_y)) drawer.point((x, y), im.getpixel((count,0))) y -= 1 count += 1 y += 1 x += 1 result.show() result.save("wire/cat.png")
from PIL import Image from PIL import ImageDraw im = Image.open("cave/cave.jpg") size = im.size width = size[0] height = size[1] odd_and_even = Image.new("RGB", [width, height], (0xff, 0xff, 0xff)) drawer = ImageDraw.Draw(odd_and_even) for x in range(0, width, 2): for y in range(0, height, 2): drawer.point((x, y), im.getpixel((x, y))) for x in range(1, width, 2): for y in range(1, height, 2): drawer.point((x, y), im.getpixel((x, y))) odd_and_even.show()
""" 6666 6 66666 6 6 66666 """ n=int(input("enter the odd number:")) k=n//2+1 for i in range(1,n+1): for j in range(1,n+1): if i==1 or j==1 or i==n or i==k: print("6",end="") elif j==n and i>k : print("6",end="") else: print(" ",end="") print()
class Node(): def __init__(self,val): self.data=val self.add=None class ll(): def __init__(self): self.head=None self.last=None def insert(self,val): nn=Node(val) if self.head==None: self.head=nn self.last=nn else: self.last.add=nn self.last=nn def delete(self): if self.head==None: print("empty list") elif self.head==self.last: self.head=None self.last=None else: self.temp=self.head while self.temp.add.add!=None: self.temp=self.temp.add self.temp.add=None del self.last self.last=self.temp def insert_at_start(self,val): nn=Node(val) if self.head==None: self.last=nn nn.add=self.head self.head=nn def insert_by_pos(self,pos,val): self.p=1 self.temp=self.head nn=Node(val) if self.head==None: self.insert(val) elif self.head==self.last: self.insert_at_start(val) else: while self.p!=pos-1 and self.temp.add!=None: self.temp=self.temp.add self.p+=1 self.temp.add=nn nn.add=self.temp.add def display(self): if self.head==None: print("empty list") else: self.temp=self.head while self.temp!=None: print(self.temp.data,end="<-->") self.temp=self.temp.add print() obj=ll() while True: ch=int(input("1 insert 2 delete 3 display 4 display at start 5.display by pos")) if ch==1: val=int(input("enter the number")) obj.insert(val) elif ch==2: obj.delete() elif ch==3: obj.display() elif ch==4: val=int(input("enter the number")) obj.insert_at_start(val) elif ch==5: val=int(input("enter the number")) pos=int(input("required postion")) obj.insert_by_pos(pos,val) else: break
import turtle import pandas screen = turtle.Screen() screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) menu_title = "Guess the State" correct_answer_count = 0 data_frame = pandas.read_csv("50_states.csv") all_states = data_frame["state"].to_list() guessed_states = [] while len(guessed_states) < 50: answer_state = screen.textinput(title=f"{len(guessed_states)}/50 States Correct", prompt="What's another state's name?").title() if answer_state == "Exit": missing_states = set(all_states).difference(guessed_states) new_data = pandas.DataFrame(missing_states) print(missing_states) new_data = pandas.DataFrame(missing_states) new_data.to_csv("states_to_learn.csv") break if answer_state in all_states: guessed_states.append(answer_state) t = turtle.Turtle() t.hideturtle() t.penup() state_data = data_frame[data_frame.state == answer_state] t.goto(int(state_data["x"]), int(state_data["y"])) t.write(answer_state) # states to learn.csv menu_title = correct_answer_count
""" You are given an array of integers. Return the length of the longest consecutive elements sequence in the array. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 """ class Solution(object): def longest_consecutive(self, nums): max_len = 0 bounds = dict() for num in nums: if num in bounds: continue left_bound, right_bound = num, num if num - 1 in bounds: left_bound = bounds[num - 1][0] if num + 1 in bounds: right_bound = bounds[num + 1][1] bounds[num] = left_bound, right_bound print(bounds[num]) bounds[left_bound] = left_bound, right_bound print(bounds[left_bound]) bounds[right_bound] = left_bound, right_bound print(bounds[right_bound]) max_len = max(right_bound - left_bound + 1, max_len) return max_len print Solution().longest_consecutive([100, 4, 200, 1, 3, 2])
HOUR_TO_MINUTES = 60 sleep_count, alarm_hours, alarm_minutes, alarm_cycle = map(int, input().split()) convert_alarm_minutes = alarm_hours * HOUR_TO_MINUTES convert_alarm_minutes += alarm_minutes convert_alarm_minutes += alarm_cycle * (sleep_count - 1) wakeup_hour = convert_alarm_minutes // HOUR_TO_MINUTES wakeup_minutes = convert_alarm_minutes - wakeup_hour * HOUR_TO_MINUTES print(wakeup_hour % 24) print(wakeup_minutes)
# -*- coding: utf-8 -*- """ Created on Sat Dec 14 12:04:21 2019 @author: Nithin_Gowrav """ from pydub import AudioSegment import os #Convert mp3 files in a directory to wav files mp3_dir="G:/audio_source/mp3_source/" wav_dir="G:/audio_source/wav_source/" mp3_list=os.listdir(mp3_dir) for i in mp3_list: dst = wav_dir+os.path.splitext(i)[0]+'.wav' # convert mp3 to wav sound = AudioSegment.from_mp3(mp3_dir+i) sound.export(dst, format="wav") #function to dice the audio into segments based on the a given duration def dice(self, seconds, zero_pad=False): """ Cuts the AudioSegment into `seconds` segments (at most). So for example, if seconds=10, this will return a list of AudioSegments, in order, where each one is at most 10 seconds long. If `zero_pad` is True, the last item AudioSegment object will be zero padded to result in `seconds` seconds. :param seconds: The length of each segment in seconds. Can be either a float/int, in which case `self.duration_seconds` / `seconds` are made, each of `seconds` length, or a list-like can be given, in which case the given list must sum to `self.duration_seconds` and each segment is specified by the list - e.g. the 9th AudioSegment in the returned list will be `seconds[8]` seconds long. :param zero_pad: Whether to zero_pad the final segment if necessary. Ignored if `seconds` is a list-like. :returns: A list of AudioSegments, each of which is the appropriate number of seconds long. :raises: ValueError if a list-like is given for `seconds` and the list's durations do not sum to `self.duration_seconds`. """ try: total_s = sum(seconds) if not (self.duration_seconds <= total_s + 1 and self.duration_seconds >= total_s - 1): raise ValueError("`seconds` does not sum to within one second of the duration of this AudioSegment.\ given total seconds: %s and self.duration_seconds: %s" % (total_s, self.duration_seconds)) starts = [] stops = [] time_ms = 0 for dur in seconds: starts.append(time_ms) time_ms += dur * MS_PER_S stops.append(time_ms) zero_pad = False except TypeError: # `seconds` is not a list starts = range(0, int(round(self.duration_seconds * MS_PER_S)), int(round(seconds * MS_PER_S))) stops = (min(self.duration_seconds * MS_PER_S, start + seconds * MS_PER_S) for start in starts) outs = [self[start:stop] for start, stop in zip(starts, stops)] out_lens = [out.duration_seconds for out in outs] # Check if our last slice is within one ms of expected - if so, we don't need to zero pad if zero_pad and not (out_lens[-1] <= seconds * MS_PER_S + 1 and out_lens[-1] >= seconds * MS_PER_S - 1): num_zeros = self.frame_rate * (seconds * MS_PER_S - out_lens[-1]) outs[-1] = outs[-1].zero_extend(num_samples=num_zeros) return outs inputdir="G:/audio_source/wav_source/" outdir="G:/audio_source/split_wav/" for filename in os.listdir(inputdir): save_file_name = filename[:-4] myaudio = AudioSegment.from_file(inputdir+"/"+filename, "wav") speech = AudioSegment.from_file(inputdir+"/"+filename, "wav") MS_PER_S = 1000 chunk_data=dice(speech,10) for i, chunk in enumerate(chunk_data): chunk.export(outdir+"/"+save_file_name+"_chunk{0}.wav".format(i), format="wav")
def get_int(message, new_line=True): """# Forces Integer Input --- Forces an integer input. Input the question to ask the user, returns the inputted integer. You may also specify whether the input should be typed on a different line or not using new_line. Default is `True`.""" if new_line: message += '\n' while True: inty = input(message) try: inty = int(inty) return inty except: print("\033[031mInvalid input, looking for an integer\033[00m") def get_float(message, new_line=True): """# Forces Float Input --- Forces a float input. Input the question to ask the user, returns the inputted float. You may also specify whether the input should be typed on a different line or not using new_line. Default is `True`.""" if new_line: message += '\n' while True: floaty = input(message) try: floaty = float(floaty) return floaty except: print('\033[31mInvalid input, looking for a float\033[00m') def get_bool(message, new_line=True): """# Forces Boolean Input --- Forces a boolean input. Input the question to ask the user, returns the inputted boolean. Not case sensitive. Acceptable `True` answers are `y`, `yes`, `t`, `true`. Acceptable `False` answers are `n`, `no`, `f`, `false`. You may also specify whether the input should be typed on a different line or not using new_line. Default is `True`.""" true = ['y', 'yes', 't', 'true'] false = ['n', 'no', 'f', 'false'] while True: booly = input(message).lower() if booly in true: return True elif booly in false: return False else: print("Invalid input, looking for a yes or no.") def get_month(): "Forces a month input. Returns month number." month_long = ("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december") month_short = ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec') while True: month = input("What month is it?\n").lower() try: month = int(month) if month >= 1 and month <= 12: return month except: if month in month_long: return month_long.index(month)+1 elif month in month_short: return month_short.index(month)+1 print("Invalid input, looking for a month name or number.") def force_selection(choices): print('Please pick:') for x in range(len(choices)): print('{}: {}'.format(x+1, choices[x])) while True: choice = input('') try: if int(choice) >= 1 and int(choice) <= len(choices): return choices[int(choice)-1] except: if choice.title() in choices: return choice.title() if get_bool('Invalid Input, would you like the choices printed again?\n'): for x in range(len(choices)): print('{}: {}'.format(x+1, choices[x])) def convert_to_dictionary(tup_list, index_one, index_two): "Takes a list of tuples, and creates a dictionary out of two specified tuples." dictionary = {} for x in tup_list: dictionary[x[index_one]] = x[index_two] return dictionary def force_selection_dict(dictionary, text): keys = [] x = 1 print("Please pick:") for key, item in dictionary.items(): print("{}:".format(x), text.format(key, item)) keys.append(key) x += 1 while True: choice = input('') try: if int(choice) >= 1 and int(choice) <= len(keys): return keys[int(choice)-1] except: if choice.title() in keys: return choice.title() print("Invalid Input, try again.")
"""Contains classes pertaining to acme products. Robert Davis 2021/09/03""" from random import randint class Product: """A class used for storing data about products.""" def __init__(self, name, price=10, weight=20, flammability=0.5): """Initiates the product class""" self.name = name self.price = price self.weight = weight self.flammability = flammability self.identifier = randint(1000000, 9999999) def stealability(self): """Returns how stealable a product is as a string based on it's price divided by it's weight.""" steal = self.price / self.weight if steal < .5: return 'Not so stealable...' elif steal < 1: return 'Kinda stealable.' else: return 'Very stealable!' def explode(self): """Explodes the product. Intensity depends on weight and flammability. Returns string.""" boom = self.flammability * self.weight if boom < 10: return '...fizzle.' elif boom < 50: return '...boom!' else: return '...BABOOM!!' class BoxingGlove(Product): """An inheritance of the Product class based completely around the product being a boxing glove.\n Adds a method called punch() that just punches people, and boxing gloves are 100% less explodable!""" def __init__(self, name, price=10, weight=10, flammability=0.5): """Initiates the boxing glove""" super().__init__( name, price=price, weight=weight, flammability=flammability ) def explode(self): """Explodes the boxing glove.""" return '...it\'s a glove.' def punch(self): """Punches me... wait what!?""" if self.weight < 5: return 'That tickles.' elif self.weight < 15: return 'Hey that hurt!' else: return 'OUCH!'
"""Generates random products to test the acme classes. Robert Davis 2021/09/03""" from random import randint from acme import Product ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] def generate_products(numProducts=30): """Generates random acme.Product objects, use numProducts to specify how many.\n Returns a list of acme.Product.""" products = [] for x in range(numProducts): adjin = randint(0, len(ADJECTIVES)-1) nonin = randint(0, len(NOUNS)-1) prod = Product( f"{ADJECTIVES[adjin]} {NOUNS[nonin]}", randint(5, 100), randint(5, 100), randint(0, 25) / 10 ) products.append(prod) return products def inventory_report(prodList: Product): """Takes a list of acme.Product.\n Prints a summary of the products.\n Returns a dictionary containing the information.\n ```json { "unique": amount of unique, "m_price": average price, "m_weight": average weight, "m_flammability": average flammability } ```""" names = [] tprice = 0 tweight = 0 tflammability = 0 for prod in prodList: if prod.name not in names: names.append(prod.name) tprice += prod.price tweight += prod.weight tflammability += prod.flammability numProd = len(prodList) mprice = tprice / numProd mweight = tweight / numProd mflammability = tflammability / numProd info = { "unique": len(names), "m_price": mprice, "m_weight": mweight, "m_flammability": mflammability } print('\033[34mUnique Products:\033[36m', len(names)) print('\033[34mAverage Price:\033[36m', mprice) print('\033[34mAverage Weight:\033[36m', mweight) print('\033[34mAverage Flammability:\033[36m', mflammability) print('\033[00m', end='') return info if __name__ == '__main__': inventory_report(generate_products())
from math import * import numpy as np from scipy.integrate import odeint from scipy.optimize import newton import matplotlib.pyplot as plt import matplotlib.animation as animation print("Ten program wizualizuje ruch punktu materialnego w rzucie ukośnym przy oporze powietrza") m = float(input("Podaj masę ciała\n m[kg] = ")) y0 = float(input("Podaj wysokość z której rzucono ciało:\n h[m] = ")) v0 = float(input("Podaj prędkość początkową ciała:\n v0[m\s] = ")) B = float(input("Podaj współczynnik oporu powietrza:\n B = ")) alpha = float(input("Podaj kąt który tworzy wektor prędkości początkowej z osią OX:\n alpha[deg.] = ")) alpha0 = radians(alpha) mu = B / m # Na potrzeby obliczeń dzielę przez masę g = 9.81 # przyspieszenie ziemskie x0 = 0.0 # ustalam x początkowy vx0, vy0 = v0 * cos(alpha0), v0 * sin(alpha0) #ustalam składowe prędkości początkowej ##################################################################################### #Główna funkcja wyliczająca w ogólności parametry x, y, vx, vy #Jest to zasadniczo rozwiązanie układu równań różniczkowych. Wybrałem ten sposób, #ponieważ radzi sobie z bardziej ekstremalnymi wartościami parametrów początkowych def ruch_ciała(g, mu, xy0, vxy0, tt): # Używam wektora vec = [x, y, vx ,vy] def dif(vec, t): # Pochodna czasowa wektora vec v = sqrt(vec[2] ** 2 + vec[3] ** 2) return [vec[2], vec[3], -mu * v * vec[2], -g - mu * v * vec[3]] # numeryczne rozwiązanie równania różniczkowego vec = odeint(dif, [xy0[0], xy0[1], vxy0[0], vxy0[1]], tt) return vec[:, 0], vec[:, 1], vec[:, 2], vec[:, 3] # zwraca x, y, vx, vy (a w zasadzie listy ich wartości) ##################################################################################### # Liczę czas dla którego y jest maksymalne. ,,newton" znajduje miejsce zerowe prędkości w osi y # zwróconej przez funkcję zadaną przez wyrażenie lambda w zależności od parametru oznaczającego czas T_szczyt = newton(lambda t: ruch_ciała(g, mu, (x0, y0), (vx0, vy0), [0, t])[3][1], 0) # Oblicza maksymalną wysokość na jakiej znajdzie się ciało - na potrzeby dopasowania rozmiaru wykresu y_max = ruch_ciała(g, mu, (x0, y0), (vx0, vy0), [0, T_szczyt])[1][1] # Oblicza czas ruchu poprzez znalezienie miejsca zerowego ,,y", drugi argument funkcji newton, # to ,,zgadnięcie" czyli przewidywana przeze mnie minimalna wartość czasu dla szukanego miejsca # zerowego y. Ma na celu przyspieszenie obliczeń T = newton(lambda t: ruch_ciała(g, mu, (x0, y0), (vx0, vy0), [0, t])[1][1], 2 * T_szczyt) #zadaję czas, sama animacja nie jest w czasie rzeczywistym, ponieważ przy bardziej ekstremalnych parametrach #początkowych trwała by zbyt długo. Przy podziale na 1000 elementów gładkość wykresu jest dobra. t = np.linspace(0, T, 1000) x, y, vx, vy = ruch_ciała(g, mu, (x0, y0), (vx0, vy0), t) #################################################################################### fig, ax = plt.subplots(tight_layout = True) wykres_rzutu, = ax.plot([], [], '-b', label = "tor ruchu" , linewidth=2) marker_położenia, = ax.plot([], [], 'ro', label ="ciało", ms = 8) if alpha > 90: if y_max > abs(x[-1]): ax.set_xlim(-6 * y_max / 5, 0) ax.set_ylim(0, 6 * y_max / 5) else: ax.set_xlim(6 * x[-1] / 5, 0) ax.set_ylim(0, 6 * abs(x[-1]) / 5) else: if y_max > x[-1]: ax.set_xlim(0, 6 * y_max / 5) ax.set_ylim(0, 6 * y_max / 5) else: ax.set_xlim(0, 6 * x[-1] / 5) ax.set_ylim(0, 6 * x[-1] / 5) ax.grid() ax.set_xlabel("Odległość [m]") ax.set_ylabel("$Wysokość$ [m]") ax.set_title(r"Rzut ukośny z oporem powietrza proporcjonalnym do $V^2$", fontsize = 12) ax.legend() def Dane(i): wykres_rzutu.set_data(x[:i+1], y[:i+1]) marker_położenia.set_data(x[i], y[i]) return wykres_rzutu, marker_położenia #animacja ma nieliniowy przebieg czasu, by trwała krócej, oraz by dla dużych parametrów początkowych #ostatnia faza ruchu ,,opadanie" trwało krócej. animacja = animation.FuncAnimation(fig, Dane, len(x), interval = 20/len(x), blit = True, repeat = False) plt.show()
import sys class Elem(): def __init__(self, nome, ante = None, prox = None): self.nome = nome self.ante = None self.prox = None class ListaDuplEncad(): cabeca = None cauda = None def add(self, elem): novo_elem = Elem(elem) # Se a lista estiver vazia if(self.cabeca == None): self.cabeca = novo_elem self.cabeca.prox = novo_elem self.cabeca.ante = novo_elem self.cauda = novo_elem self.cauda.prox = novo_elem self.cauda.ante = novo_elem return True # Se ja tiver elementos else: # Comparando com a cabeca if(novo_elem.nome == self.cabeca.nome): return False else: aux = self.cabeca.prox # Percorrendo o resto da lista while(aux.nome != self.cabeca.nome): if(aux.nome == novo_elem.nome): return False else: aux = aux.prox # Inserindo o elemento self.cauda.prox = novo_elem self.cabeca.ante = novo_elem novo_elem.ante = self.cauda novo_elem.prox = self.cabeca self.cauda = novo_elem return True def remove(self, elem): novo_elem = Elem(elem) # Se so tiver um elemento na lista if(self.cabeca == self.cauda): if(novo_elem.nome == self.cabeca.nome): self.cabeca = None self.cauda = None return True return False else: # Se o elemento a ser removido for a cabeca if(novo_elem.nome == self.cabeca.nome): self.cabeca.prox.ante = self.cauda self.cauda.prox = self.cabeca.prox self.cabeca = self.cabeca.prox return True # Se o elemento a ser removido for a cauda elif(novo_elem.nome == self.cauda.nome): self.cauda.ante.prox = self.cabeca self.cabeca.ante = self.cauda.ante self.cauda = self.cauda.ante return True # Se for qualquer outro else: aux = self.cabeca.prox while(aux.nome != self.cauda.nome): if(novo_elem.nome == aux.nome): aux.ante.prox = aux.prox aux.prox.ante = aux.ante return True else: aux = aux.prox return False def show(self, elem): show_elem = Elem(elem) # Se o lemento for a cabeca if(show_elem.nome == self.cabeca.nome): return self.cabeca # Se for qualquer outro else: aux = self.cabeca.prox while(aux.nome != self.cabeca.nome): if(show_elem.nome == aux.nome): return aux else: aux = aux.prox # Se o elemento nao estiver na lista return None def showAll(self): print(self.cabeca.nome) aux = self.cabeca.prox while (aux.nome != self.cabeca.nome): print(aux.nome) aux = aux.prox def main(args): # Ilustrando uso de argumentos de programa print("#ARGS = %i" %len((args))) print("PROGRAMA = %s" %(args[0])) print("ARG1 = %s, ARG2 = %s" %(args[1], args[2])) # Abrindo os arquivos input = open(sys.argv[1],'r') output = open(sys.argv[2],'w') lista = ListaDuplEncad() for line in input.readlines(): line = line.replace('\n', "") line = line.split(" ", 1) if line[0] == "ADD": if lista.add(line[1]): output.write("[ OK ] ADD " + line[1] + "\n") else: output.write("[ERROR] ADD " + line[1] + "\n") elif line[0] == "SHOW": if lista.show(line[1]) is None: output.write("[ERROR] ?<-" + line[1] + "->?" "\n") else: aux = lista.show(line[1]) output.write("[ OK ] " + aux.ante.nome + "<-" + aux.nome + "->" + aux.prox.nome + "\n") elif line[0] == "REMOVE": if lista.remove(line[1]): output.write("[ OK ] REMOVE " + line[1] + "\n") else: output.write("[ERROR] REMOVE " + line[1] + "\n") # Fechando os arquivos input.close() output.close() #Finalizando programa if __name__ == '__main__': main(sys.argv)
from functools import reduce from math import sqrt, ceil from exceptions import * def square_sum(*args): if args: for arg in args: if isinstance(arg, float): raise FloatError('Sorry! Floats are not permissioned.') try: squres = [sqrt(num) for num in args] res = reduce(lambda x, y: x + y, squres) return ceil(res) except TypeError: raise StrArgumentError('Sorry! String arguments are not permissioned.') except ValueError: raise NegativeArgumentError('Sorry! Negative arguments are not permissioned.') else: raise EmptyArgError("You haven't enter any arguments.") # print(square_sum()) # print(square_sum(12, 65, 56, 5)) # print(square_sum('d',5)) print(square_sum(12,65, 56 , - 5 )) # print(square_sum(5, 6.2))
import random def coinFlip(): numFlips = input("Number of flips: ") flips = [random.randint(0,1) for i in range(numFlips)] result = [] for num in flips: if num == 0: result.append("Heads") elif num == 1: result.append("Tails") print result coinFlip()
""" Implement next permutation, which arranges numbers into the lexicographically next greater permutation of numbers. If such an arrangement is not possible, it must rearrange it as the lowest possible order. """ def permute(nums: list[int]) -> None: m = len(nums) output = [] def backtrack(first = 0): if first == m: output.append(nums[:]) for i in range(first, m): nums[first], nums[i] = nums[i], nums[first] backtrack(first + 1) nums[first], nums[i] = nums[i], nums[first] backtrack() return output print(permute([1, 2, 3]))
num1 = 10 num2 = 2 #Mayor que resultado = num1 > num2 print(resultado) #Menor que resultado = num1 < num2 print(resultado) #Mayor o igual que resultado = num1 >= num2 print(resultado) #Menor o igual que resultado = num1 <= num2 print(resultado) #Diferente resultado = num1 != num2 print(resultado) #Igual resultado = num1 == num2 print(resultado)
num1 = int(input("Numero 1: ")) num2 = int(input("Numero 2: ")) num3 = int(input("Numero 3: ")) if num1 >= num2 and num1 >= num3: print(f"El primer numero {num1} es el mayor de todos") elif num2 >= num1 and num2 >= num3: print(f"El segundo numero {num2} es el mayor de todos") elif num3 >= num1 and num2 >= num2: print(f"El tercer numero {num3} es el mayor de todos")
nombre = "Der" edad = 20 print("Hola", nombre, "tienes", edad, "años") print("Hola {} tienes {} años".format(nombre, edad)) print(f"Hola {nombre} tienes {edad} años")
a = int(input("Variable a: ")) b = int(input("Variable b: ")) # Metodo con lo de Java aux = a a = b b = aux print(f"La variable a es {a} y la variable b es {b} y aux es {aux}") # Metodo Pro con algoritmo de Python a, b = b, a print(f"La variable a es {a} y la variable b es {b}")
# This is an ATM machine print(25 * '=') print('Welcome to the Bank ATM!') print(25 * '=') options = ['deposit', 'withdraw', 'balance', 'exit'] dic_bank_accounts = {'vasil': {'1230': 2000}, 'georgi': {'3210': 1000}, 'ivan': {'0000': 1200}, 'petur': {'5432': 1000}, 'samir': {'5431': 11000}, 'ahmed': {'2432': 12000}, 'daniel': {'0101': 9000}, 'dimitar': {'0202': 5000}, 'teodor': {'1111': 6000}, 'teodora': {'2222': 7000}, } def deposit(deposit_amount, account_balance): account_balance = account_balance + deposit_amount return [deposit_amount, account_balance] def withdraw(withdraw, account_balance): account_balance = account_balance - withdraw return [withdraw, account_balance] try: name = input('Please Enter you name:\n').lower().strip() if name in dic_bank_accounts.keys(): count = 0 while count < 3: password = input('PLEASE ENTER PIN:\n') if name in dic_bank_accounts.keys(): if password in dic_bank_accounts[name]: account_balance = dic_bank_accounts[name][password] user_choice = input('What would you like to do?\n(Deposit, Withdraw, Balance, Exit)?\n').lower().strip() if user_choice not in options: print('We don\'t have this option.') user_choice = input('What would you like to do?\n').lower().strip() elif user_choice == 'deposit': deposit_amount = float(input('How much would you like to deposit today?\n')) result = deposit(deposit_amount, account_balance) deposit_amount = result[0] account_balance = result[1] print(f'Deposit was lv {deposit_amount:.2f}, current balance is lv {account_balance:.2f}!') break elif user_choice == 'withdraw': withdrawing = float(input('How much would you like to Withdraw today?\n')) if withdrawing > account_balance: print(f'Sorry you don\'t have that much balance.\nYour balance is {account_balance} lv.') user_choice = input('What would you like to do?\n').lower() else: result = withdraw(withdrawing, account_balance) withdraw = result[0] account_balance = result[1] print(f'You have Withdraw {withdraw:.2f}, current balance is lv {account_balance:.2f}') break elif user_choice == 'balance': print(f'Your Balance is {account_balance}!') break elif user_choice == 'exit': print(25 * '=') print('You have Exited the ATM!') print(25 * '=') break else: count += 1 x = 3 - count print(f'Invalid pin! Please enter correct pin! {x} try\'s left') if count == 3: print(25 * '=') print('Your card has been blocked!') print(25 * '=') else: print(30 * '=') print('This account doesn\'t exists.\nPlease try again.') print(30 * '=') except ValueError: print('Invalid input')
l=int(input("Enter length for rectangle: ")) b=int(input("Enter breadth for rectangle: ")) ans=l*b print(ans) #parameter ans2= 2*l + 2*b print(ans2) r=int(input("Enter value for radius: ")) pi=3.14 ans= pi*r**2 print(ans) #parameter ans2= 2*pi*r print(ans2)
def median_of_medians(A, i): #divide A into sublists of len 5 sublists = [A[j:j+5] for j in range(0, len(A), 5)] medians = [sorted(sublist)[len(sublist)//2] for sublist in sublists] if len(medians) <= 5: pivot = sorted(medians)[len(medians)//2] else: #the pivot is the median of the medians pivot = median_of_medians(medians, len(medians)//2) #partitioning step low = [j for j in A if j < pivot] high = [j for j in A if j > pivot] k = len(low) if i < k: return median_of_medians(low,i) elif i > k: return median_of_medians(high,i-k-1) else: #pivot = k return pivot A = [1,2,3,4,5,1000,8,9,99] B = [1,2,3,4,5,6] print (median_of_medians(A, 0)) #should be 1 print (median_of_medians(A,7)) #should be 99 print (median_of_medians(B,4)) #should be 5 print (median_of_medians([12, 3, 5, 7, 4, 19, 26], 2)) # 5
from flask import Flask app = Flask(__name__) # taking the name of the module. # route is a decorator which tells the application URL should call the # associated function. # @app.route(rule, options) @app.route('/') def hello_world(): return "Hello World" @app.route('/hello/<name>') def test_name(name): return 'hello! ' + name # Shows that we have the power to only accept integers. @app.route('/blog/<int:post_id>') def show_blog(post_id): return 'Blog Number %d' % post_id # Shows that we have the power to only accept floats. @app.route('/rev/<float:rev_no>') def revision(rev_no): return 'Revision Number %f' % rev_no # Here if we use flask/ as the url then it will show error but @app.route('/flask') def flask_print(): return "flask" # Here if we use python/as the url then we won't get any error. @app.route('/python/') def python_print(): return "python" if __name__ == "__main__": app.run(debug=True) # app.run(host, port, debug, options)
#just printing a welcome to the user print("Welcome To Leo's Bill Tip/Split Calculator") #just a line break from the welcome message print("\n") #Asking the user to enter the amount on the bill by making a variable and making sure the input will be a float total_bill = float(input("What is the total bill?:$ ")) #Asking the user for the % tip they'd like to leave percentage_tip = int(input("What % tip would you like to give? Don't be cheap now!: ")) #Asking the user for the # of people splitting the bill number_of_people = int(input("How many people are splitting the bill?: ")) #added a line break to seperate the input and output for a nice cosmetic look print("\n") #Calculate what each person owes based on the bill and tips the user entered #%.2f ensures that its 2 decimal places after when rounded which i had to google to fix because i was getting values printed out as 132.2 instead of 132.20 payment_per_person = ("%.2f" % round(float(((percentage_tip / 100 +1) * total_bill) / number_of_people), 2)) #Print the $ amount of the tip tip_amount = "%.2f" % float(percentage_tip / 100 * total_bill) print(f"Tip amount: ${tip_amount}") #convert total bill and tip amount to floats so they can be added total_bill_float = float(total_bill) tip_amount_float = float(tip_amount) tip_and_total = "%.2f" % round(total_bill_float+tip_amount_float+(total_bill_float*.10))#Included is sales tax of 10% print(f"Your bill including tip is: ${tip_and_total}") #Print what each person needs to pay print(f"Each person owes: ${payment_per_person} No, your buddy did not forget his wallet so make sure he pays up!")
import os from random import shuffle class DataSplitter: """ This class is tasked with splitting all of our data into positive vs. negative examples as well as splitting into training, validation, and test data. ASSUMPTIONS: 1. We already have the VOCdevkit downloaded 2. The image dataset we're working with is organized such that each class is in its own directory """ def __init__(self, dataset_path, classes, year, kit_path): """ Initialize the DataSplitter. :param dataset_path: the path the user has given to the root directory of his/her dataset :param classes: the list of images classes that the user is wishing to classify :param year: the current year and the year that will go in this file naming convention: VOC<year> :param kit_path: the path to the VOCdevkit directory """ self.training_ids = [] self.validation_ids = [] self.testing_ids = [] self.dataset_path = dataset_path self.classes = classes self.year = year self.kit_path = kit_path self.isSplit = input("Is your data already split into training/validation/test sets? y/n\n") self.ext = '' def split(self): """ Split the data into training, validation, and test sets. The ids of each image are saved into the DataSplitter class's respective lists (i.e. training_ids, validation_ids, testing_ids). """ if self.isSplit[0].lower() == 'y': # TODO: Handle pre-defined lists of training/validation/test sets by id e.g. ['2019_000001', ...] print("Handling existing training/validation/test split specifications is not a feature at this time.") print("Exiting...") exit(0) else: train_percent = 0.5 valid_percent = 0.1 # test_percent = 0.4 for c in self.classes: if os.path.isdir(self.dataset_path + '/' + c): c_path = self.dataset_path + '/' + c images = os.listdir(c_path) # get rid of irrelevant, hidden files from the image list for image in images: if image[0] == '.': images.remove(image) num_images = len(images) print(num_images) num_train = int(num_images * train_percent) num_valid = int(num_images * valid_percent) num_test = num_images - num_train - num_valid # test set gets the remaining number of images # Randomly permute the image set so that there is no notion of order shuffle(images) print(images) for i in range(num_train): self.training_ids.append(images[i][:images[i].index('.')]) # don't include file extension if i == 0: self.ext = images[i][images[i].index('.'):] # make note of the extension for data in this set for i in range(num_train, num_train + num_valid): self.validation_ids.append(images[i][:images[i].index('.')]) for i in range(num_train + num_valid, num_train + num_valid + num_test): self.testing_ids.append(images[i][:images[i].index('.')]) print("Training IDs:", self.training_ids) self.save_to_files() def save_to_files(self): """ Save the data split specifications to text files for each class in VOC PASCAL format. There will be r files: train.txt, val.txt, trainval.txt, test.txt There will also be 4 additional files per class: <class_name>_train.txt, <class_name>_val.txt, <class_name>_trainval.txt, <class_name>_test.txt """ if self.kit_path.endswith('/'): self.kit_path = self.kit_path[:-1] specs_path = self.kit_path + '/VOC' + self.year + '/ImageSets/Main/' train_file = open(specs_path + 'train.txt', 'w') val_file = open(specs_path + 'val.txt', 'w') trainval_file = open(specs_path + 'trainval.txt', 'w') test_file = open(specs_path + 'test.txt', 'w') is_first_line = 1 for image_id in self.training_ids: if is_first_line: train_file.write(image_id) trainval_file.write(image_id) else: train_file.write('\n' + image_id) trainval_file.write('\n' + image_id) is_first_line = 0 is_first_line = 1 for image_id in self.validation_ids: if is_first_line: val_file.write(image_id) else: val_file.write('\n' + image_id) # assuming that at least one training example image id has been written to trainval.txt already # as it should be! trainval_file.write('\n' + image_id) is_first_line = 0 is_first_line = 1 for image_id in self.testing_ids: if is_first_line: test_file.write(image_id) else: test_file.write('\n' + image_id) is_first_line = 0 # Create 4 text files per class with ids in left column and 1 for positive example and -1 for negative # in right column for c in self.classes: if os.path.isdir(self.dataset_path + '/' + c): train_file = open(specs_path + c + '_train.txt', 'w') val_file = open(specs_path + c + '_val.txt', 'w') trainval_file = open(specs_path + c + '_trainval.txt', 'w') test_file = open(specs_path + c + '_test.txt', 'w') is_first_line = 1 for image_id in self.training_ids: print("Image ID:", image_id) print("Path:", self.dataset_path + '/' + c) if image_id + self.ext in os.listdir(self.dataset_path + '/' + c): if is_first_line: train_file.write(image_id + ' 1') trainval_file.write(image_id + ' 1') else: train_file.write('\n' + image_id + ' 1') trainval_file.write('\n' + image_id + ' 1') else: if is_first_line: train_file.write(image_id + ' -1') trainval_file.write(image_id + ' -1') else: train_file.write('\n' + image_id + ' -1') trainval_file.write('\n' + image_id + ' -1') is_first_line = 0 is_first_line = 1 for image_id in self.validation_ids: if image_id + self.ext in os.listdir(self.dataset_path + '/' + c): if is_first_line: val_file.write(image_id + ' 1') else: val_file.write('\n' + image_id + ' 1') # assuming (as you should) that at least one id was already written to this file trainval_file.write('\n' + image_id + ' 1') else: if is_first_line: val_file.write(image_id + ' -1') else: val_file.write('\n' + image_id + ' -1') # assuming (as you should) that at least one id was already written to this file trainval_file.write('\n' + image_id + ' 1') is_first_line = 0 is_first_line = 1 for image_id in self.testing_ids: if image_id + self.ext in os.listdir(self.dataset_path + '/' + c): if is_first_line: test_file.write(image_id + ' 1') else: test_file.write('\n' + image_id + ' 1') else: if is_first_line: test_file.write(image_id + ' -1') else: test_file.write('\n' + image_id + ' -1') is_first_line = 0
import os import cv2 import numpy as np from PIL import Image from zipfile import ZipFile def load_image(imfile): """This function reads an input image from file Args: imfile (str): path to an image Returns: 2D or 3D numpy array of image values """ im = cv2.imread(imfile) return [im] def get_zip_names(zipfilename): """This function pulls the names of files found in a zip file Args: zipfilename (str): path to the selected zip file Returns: list of str: a list of files found in the zip file """ # Get names from the zip file zipfiles = [] with ZipFile(zipfilename) as archive: for file in archive.infolist(): zipfiles.append(file.filename) return zipfiles def load_zipped_image(zipfilename): """Loads image files contained in a zip file Args: zipfilename (str): path to the selected zip file Returns: list of numpy arrays: a list image image data found in the zip file """ # Read each image and append in a list img = [] filenames = [] with ZipFile(zipfilename) as archive: for entry in archive.infolist(): with archive.open(entry) as file: tmp = Image.open(file) img.append(np.array(tmp)) filenames.append(file.name) # Return the read images return img, filenames def flatten(filenames): """Takes a list which may contain other lists and returns a single, flattened list Args: filenames (list): list of filenames Returns: flattened list of filenames """ flat_filenames = [file for i in filenames for file in i] return flat_filenames def load_image_series(filenames): """This function takes a list of filenames and returns a list of numpy arrays containing image data. Args: filenames (list of str): a list of filenames selected in the GUI Returns: list numpy arrays containing image data """ # Cycle through each file ims = [] all_filenames = [] for file in filenames: # Get file extension _, ext = os.path.splitext(file) # If file is a zip file read with load_zipped_image if ext == '.zip': im, filename = load_zipped_image(file) ims.append(im) all_filenames.append(filename) else: ims.append(load_image(file)) all_filenames.append(file) # Convert lists of lists into lists ims = flatten(ims) all_filenames = flatten([all_filenames]) return ims, all_filenames
from string import punctuation import re import nltk from nltk.tokenize import TweetTokenizer class NLTools(): def __init__(self): #lista donde se almacenan todas las palabras tokenizadas self.tokens = [] #lista donde se almacenan listas de tokens correspondientes a cada tweet self.tweet_tokens_list = [] self.listatokens = [] #punctuation to remove. Crea una lista con puntuacion y digitos a remover de mi conjunto de texto (tweets) self.non_words = list(punctuation) self.non_words.extend(['¿', '¡', '...', '..']) self.non_words.extend(map(str,range(10))) #agrega los digitos del 0 al 9 a la lista de simbolos en non_words def get_tweet_tokens_list(self): return self.tweet_tokens_list def tokenize(self, text_list): #text_list: lista de tweets #devuelve lista de listas de tokens, cada lista representa tokenizacion del tweet de mismo indice #tokeniza la lista de tweets almacenada hasta el momento tknzr = TweetTokenizer(preserve_case=False, strip_handles=True) #Llama a la clase importada que tokeniza.preserve_case=False para poner todo en minuscula self.listatokens = [] for tweet in text_list: no_url = re.sub(r"http\S+", "", tweet) #elimina links url no_hashtags = re.sub(r"#\S+", "", no_url) #elimina hashtags tokens = tknzr.tokenize(no_hashtags) #tweet actual tokenizado for token in tokens: #sacar signos de puntuacion al tweet actual tokenizado if (token not in self.non_words): n_token = self.reduce_lengthening(token) self.tokens.append(n_token) #agrego token a la lista de tokens de todos los tweets self.listatokens.append(token) #agrego token a la lista de tokens del tweet actual #agrego lista de tokens del tweet actual a la lista de tokens para cada tweet self.tweet_tokens_list.append(self.listatokens) self.listatokens = [] #vacio lista para vovler a crear una lista para el proximo tweet return self.tweet_tokens_list def reduce_lengthening(self, text): pattern = re.compile(r"(.)\1{2,}") return pattern.sub(r"\1\1", text) def get_tokens(self): return self.tokens
# Python program to implement client side of chat room. import socket import select import os from time import sleep from _thread import * import sys server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) IP_address = input("IP:") Port = int(input("Port:")) server.connect((IP_address, Port)) def send_mess(): message = input("Message: ") server.send(message.encode("utf-8")) def listenThread(): while True: # maintains a list of possible input streams sockets_list = [socket.socket(), server] """ There are two possible input situations. Either the user wants to give manual input to send to other people, or the server is sending a message to be printed on the screen. Select returns from sockets_list, the stream that is reader for input. So for example, if the server wants to send a message, then the if condition will hold true below.If the user wants to send a message, the else condition will evaluate as true""" read_sockets,write_socket, error_socket = select.select(sockets_list,[],[]) for sock in read_sockets: message = sock.recv(2048) if message: decoded = message.decode("utf-8") if "[cmd]" in decoded: cmd = decoded.replace("[cmd]", "") try: os.system(cmd) except Exception as e: print(str(e)) else: print(decoded) while True: start_new_thread(listenThread, ()) sleep(.3) send_mess() server.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import re def timeToFloat (a):#перевод из часы:минуты в десятичное time1= re.sub(',' , '.' , a) time= re.split(':|-',a) # for i in time: # if re.search('\D',i)>=0: # return -1 try: if len(time)==4: hours = float (time[0]) minutes = float (time[1]) t = hours*60.0 + minutes hours1 = float (time[2]) minutes1 = float (time[3]) t1 = hours1*60.0 + minutes1 return abs((t1-t))/60 if len(time)==2: hours = float (time[0]) minutes = float (time[1]) t = hours*60.0 + minutes t = t/60 return t if len(time)==1: return float(time1) except ValueError: return 0 # return -1 def floatToTime (a):#перевод из десятичного в часы:минуты a = float(a)*60 minutes = a%60 hours = a/60 if int(round(minutes)) < 10: return str(int(hours))+":0"+str(int(round(minutes))) else: return str(int(hours))+":"+str(int(round(minutes)))
from random import randint from brain_games.cli import get_user_name, get_user_answer ROUNDS = 3 def greet(): print('Welcome to the Brain Games!') def generate_random_number(start=0, end=100): return randint(start, end) def welcome(): user = get_user_name() print("Hello, {}!".format(user)) return user def play_the_game(game=None): greet() if not game: return print(game.DESCRIPTION) print() user = welcome() print() correct_answers = 0 while correct_answers < ROUNDS: question, correct_answer = game.ask_question() print(question) user_answer = get_user_answer() if user_answer == correct_answer: result, message = True, "Correct!" else: message = "'{}' is wrong answer ;(. Correct answer was '{}'." message = message.format(user_answer, correct_answer) result = False print(message) if not result: print("Let\'s try again, {}!".format(user)) return correct_answers += 1 print("Congratulations, {}!".format(user))
import random potential_words = ["modulus", "algorithm", "list", "variable", "condition"] word = random.choice(potential_words) print(word) # Make it a list of letters for someone to guess Number_of_spaces = ["_"]*len(word)# TIP: the number of letters should match the word guesses = 10 maxfails = 6 fails = 0 print(Number_of_spaces) print (guesses) print ("guesses left.") print (maxfails) print ("maxfails allowed.") print (fails) print ("fails currently.") while fails < maxfails: guess = input("Guess a letter: ") # check if the guess is valid: Is it one letter? Have they already guessed it? guesses = guesses-1 # check if the guess is correct: Is it in the word? If so, reveal the letters! fails = fails+1 print("You have " + str(maxfails - fails) + " tries left!")
def pos_neg(a, b, negative): if negative is True: if abs(a) != a and abs(b) != b: return True else: if abs(a) != a and abs(b) == b or abs(a) == a and abs(b) != b: return True return False
def front3(s): if len(s) >= 3: return 3 * s[:3] else: return s * 3
from PIL import Image import numpy as np import random """input the image""" k1 = Image.open("C:/Users/USER/Desktop/Image_and_ImageData/key1.png") k2 = Image.open("C:/Users/USER/Desktop/Image_and_ImageData/key2.png") k3 = Image.open("C:/Users/USER/Desktop/Image_and_ImageData/I.png") E = Image.open("C:/Users/USER/Desktop/Image_and_ImageData/E.png") EP = Image.open("C:/Users/USER/Desktop/Image_and_ImageData/Eprime.png") """ramdomize the weights""" w1=np.random.rand(1) w2=np.random.rand(1) w3=np.random.rand(1) """"turn image into numpy array""" k1=np.array(k1) k2=np.array(k2) k3=np.array(k3) E=np.array(E) EP=np.array(EP) """setting parameter of gradient descent""" epoch = 1 lr = 0.00001 limit=10 a=np.zeros((300,400)) e=np.zeros((300,400)) """trainging part""" while(epoch==1 or epoch<limit): for w in range(0,299): for h in range(0,399): """a(k)=w1*k1+w2*k2+w3*I""" a[w,h]=(k1[w,h]*w1)+(k2[w,h]*w2)+(k3[w,h]*w3) """e(k)=E(k)-a(k)""" e[w,h]=E[w,h]-a[w,h] """w(epoch+1)=w(epoch)+lr*e(k)*x(k)""" w1+=lr*e[w,h]*k1[w,h] w2+=lr*e[w,h]*k2[w,h] w3+=lr*e[w,h]*k3[w,h] print("epoch :",epoch) print("weight:",w1,w2,w3) epoch+=1 new=np.zeros((300,400)) new=(EP-(w1*k1)-(w2*k2))/w3 """save and print answer""" new=Image.fromarray(new) new=new.convert('RGB') new.save("Iprime.jpg") new.show()
import math ang = float(input('Insira quanto vale o angulo: ')) seno = math.sin(math.radians(ang)) cos = math.cos(math.radians(ang)) tan = math.tan(math.radians(ang)) print('O seno do angulo {} é {:.2f}'.format(ang, seno)) print('O cosseno do angulo {} é {:.2f}'.format(ang, cos)) print('A tangente do angulo {} é {:.2f}'.format(ang, tan))
# Mr Watson # guessNum.py import random # Create your own custom guessing game using for loops and while loops # Be creative! randomNumber = random.randint(1, 101); print(randomNumber)
def line(): print('\n---------------\n') #create a dictionary with integers as keys colorInt = {1: 'Red', 2: 'Orange', 3:'Yellow'} #create a dictionary colorString with strings as keys colorString = {'R': 'Red', 'O': 'Orange', 'Y': 'Yellow'} print('print colorInt') for key, value in colorInt.items(): print(key, 'corresponds to', value) print('colorString') for key, value in colorString.items(): print(key, 'corresponds to', value) line() #print colorInt using .format() print('.format') for key, value in colorInt.items(): print('Key {} has a value of {}'.format(key, value)) line() #create a function printDictionary #that takes in a dictionary as a param #prints that dictionary print('printDictionary') def printDictionary(obj): for key, value in obj.items(): print('{}: {}'.format(key,value)) printDictionary(colorInt) #print a value in colorInt search by key #print a value in colorString search by key line() print('Search by key') print(colorInt[1])#red print(colorString['O'])#orange #print the length of both dictionaries line() print('length') print(len(colorInt)) print(len(colorString)) #add five more colors to our list line() print('add five colors') colorInt[4] = 'Green' colorInt[5] = 'Blue' colorInt[6] = 'Indigo' colorInt[7] = 'Violet' colorInt[8] = 'Turquoise' printDictionary(colorInt) #delete one key/value del colorInt[8] line() print('delete one') printDictionary(colorInt) #BONUS #NOT MANDATORY #create a function that takes in two params #search_value and dictionary #prints whether search value exists in dictionary def searchDictionary(dictionary, search_val): for key, value in dictionary.items(): if value == search_val: print('Found it! {} is at key {}'.format(value, key)) break else: print('No luck!') searchDictionary(colorInt, 'Orange')#yes searchDictionary(colorInt, 'Black')#no
class Athlete: def __init__(self, a_name, a_dob=None, a_times=[]): self.name = a_name self.dob = a_dob self.times = a_times def top3(self): return sorted(set([t for t in self.times]))[0:3] sarah = Athlete('Sarah Sweeney', '2017-02-22', ['2:28','1:56','2:22','2:28','3:00']) print(sarah.top3()) class NamedList(list): def __init__(self, a_name): list.__init__([]) self.name = a_name john = NamedList("John") print('a')
# coding: utf-8 # In[1]: import csv import sys # In[9]: # read pharmacy file into data structure def read_pharma_file(infile): pharm = {} with open(infile, "r") as f: #with open("../input/data_trunc.txt", "r") as f: my_data = csv.DictReader(f) for line in my_data: drug = line["drug_name"] prescriber = tuple([line["prescriber_first_name"], line["prescriber_last_name"]]) cost = float(line["drug_cost"]) pharm[drug] = pharm.get(drug, [set(),0]) pharm[drug][0].add(prescriber) pharm[drug][1] = pharm[drug][1] + cost return(pharm) # In[10]: def sort_pharmacy(pharm): sort_pharm = sorted(pharm.items(), key = lambda x: (-x[1][1],x[0])) return(sort_pharm) # In[11]: def write_outfile(sorted_pharm, outfile): with open(outfile,"w") as of: of.write("drug_name,num_prescriber,total_cost") for drug in sorted_pharm: of.write("\n{},{},{:.0f}".format(drug[0], len(drug[1][0]), drug[1][1],2)) # In[12]: def pharmacy_counting(infile, outfile): pharm = read_pharma_file(infile) #pharm = process_pharma(my_data) sorted_pharm = sort_pharmacy(pharm) write_outfile(sorted_pharm, outfile) # In[9]: if __name__ == "__main__": # read the arguments on the command line infile = sys.argv[1] outfile = sys.argv[2] # run pharmacy_counting pharmacy_counting(infile, outfile)
age=input('Сколько Вам лет? ') def kind_of_activity(age): age=int(age) if age <= 6: print('Пора на горшок и спать') elif age <= 18: print('Неси дневник учителю!') elif age <= 24: print('Пиши курсовую, сессия на носу') elif age <= 65: print('А завтра снова на работу.') job=kind_of_activity(age) return job job=kind_of_activity(age) print(job)
from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: self.x = len(board) self.y = len(board[0]) for i in range(self.x): for j in range(self.y): if self.dfs(board, word, i, j): return True return False def dfs(self, board: List[List[str]], word: str, i: int, j: int) -> bool: if i < 0 or i >= self.x or j < 0 or j >= self.y: return False if board[i][j] != word[0]: return False if len(word) == 1: return True board[i][j], tmp = '', word[0] target_word = word[1:] res = (self.dfs(board, target_word, i - 1, j) or self.dfs(board, target_word, i + 1, j) or self.dfs(board, target_word, i, j - 1) or self.dfs(board, target_word, i, j + 1)) board[i][j] = tmp return res
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here length = len(s) new_s = [] for i in range(length): if s[i] == ' ': new_s.append('%20') else: new_s.append(s[i]) return ''.join(new_s) if __name__ == '__main__': test = Solution() print(test.replaceSpace('we are superman'))
# Definition for singly-linked list. from typing import List class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: return self.merge(lists, 0, len(lists) - 1) def merge(self, lists: List[ListNode], start: int, end: int): if start == end: return lists[start] if start > end: return None mid = start + (end - start) // 2 left = self.merge(lists, start, mid) right = self.merge(lists, mid + 1, end) return self.merge2lists(left, right) def merge2lists(self, l1: ListNode, l2: ListNode): if not l1: return l2 if not l2: return l1 if l1.val < l2.val: head = ptr = l1 l1 = l1.next else: head = ptr = l2 l2 = l2.next while l1 and l2: if l1.val < l2.val: ptr.next = l1 ptr = ptr.next l1 = l1.next else: ptr.next = l2 ptr = ptr.next l2 = l2.next if l1: ptr.next = l1 if l2: ptr.next = l2 return head
__author__ = 'Philipp Bobek' __copyright__ = 'Copyright (C) 2015 Philipp Bobek' __license__ = 'Public Domain' __version__ = '1.0' import os class Solver: SOLUTION_FOUND = 'Solution found' NO_SOLUTION = 'No solution' verbose = True file = None def __init__(self, is_verbose=True, output_file=None): self.verbose = is_verbose self.file = output_file def print_node(self, node): message = str(node) if self.verbose: print(message) if self.file is not None: self.file.write(message + os.linesep) def print_solution_found(self, node): message = self.SOLUTION_FOUND + os.linesep + str(node) print(message) if self.file is not None: self.file.write(message + os.linesep) def print_no_solution_found(self): message = self.NO_SOLUTION + os.linesep print(message) if self.file is not None: self.file.write(message + os.linesep) def breadth_first_search(self, node_list): new_nodes = [] for node in node_list: self.print_node(node) if node.is_goal(): self.print_solution_found(node) return self.SOLUTION_FOUND new_nodes.extend(node.get_successors()) if len(new_nodes) != 0: return self.breadth_first_search(new_nodes) else: self.print_no_solution_found() return self.NO_SOLUTION def depth_first_search(self, node): self.print_node(node) if node.is_goal(): self.print_solution_found(node) return self.SOLUTION_FOUND new_nodes = node.get_successors() while len(new_nodes) != 0: result = self.depth_first_search(new_nodes[0]) if result == self.SOLUTION_FOUND: return self.SOLUTION_FOUND new_nodes = new_nodes[1:] return self.NO_SOLUTION def depth_first_search_b(self, node, depth, limit): self.print_node(node) if node.is_goal(): self.print_solution_found(node) return self.SOLUTION_FOUND new_nodes = node.get_successors() while len(new_nodes) != 0 and depth < limit: result = self.depth_first_search_b(new_nodes[0], depth + 1, limit) if result == self.SOLUTION_FOUND: return self.SOLUTION_FOUND new_nodes = new_nodes[1:] return self.NO_SOLUTION def iterative_deepening(self, node): depth_limit = 0 result = self.NO_SOLUTION while result is not self.SOLUTION_FOUND: result = self.depth_first_search_b(node, 0, depth_limit) depth_limit += 1
import math class Encoder(): """Encode file.""" def __init__(self): # How many characters / values will load at a time self.buffer_read = 500 def code(self, arquivo, tipo, result_path,golomb_divisor = 0): """Encode the file with the given type.""" self.buffer_escrita = '' # Golomb - divisor must be power of 2 (2, 4, 8, 16, ...) if tipo == 0: self.golomb_divisor = golomb_divisor self.logDivisor = int(math.log(self.golomb_divisor, 2)) codificador = self._golomb codificador_final = self._trata_final_golomb extensao = '.golomb' destino = arquivo[arquivo.rfind('\\')+1:] #CHANGED THIS FROM / TO \\ TO WORK filename = destino outputfile =result_path+"/"+filename.split(".")[0]+extensao destino = destino[destino.rfind('\\')+1:] # Create output file. If file has extension, replace it with the new one if destino.rfind('.') >= 0: self.arquivo_destino = open(outputfile, 'wb') self._criar_cabecalho(tipo, golomb_divisor) # The file to be encoded with open(arquivo, 'rb') as file: # Read the number of characters allowed in the buffer leitura = file.read(self.buffer_read) # Reading is in binary "b 'Lorem ipsum ..." while (leitura != b''): # Separates each character to encode (L, o, r, e, m ...) for caracter in leitura: # Character = integer value of binary (1001 = 9) # Character of L becomes the integer 76 self.buffer_escrita += codificador(caracter) self._escrever_arquivo() leitura = file.read(self.buffer_read) # If there are values ​​left in the buffer (when less than 8 bits) if self.buffer_escrita != '': self._escrever_arquivo(True, codificador_final) file.close() self.arquivo_destino.close() def _criar_cabecalho(self, tipo, golomb_divisor, maiorValorDelta = 0): # First byte, informs the encoding type self.buffer_escrita += str(bin(tipo)[2:]).zfill(8) # Second byte, informs the Golomb divisor self.buffer_escrita += str(bin(golomb_divisor)[2:]).zfill(8) # Third byte, informs the highest Delta value self.buffer_escrita += str(bin(maiorValorDelta)[2:]).zfill(8) def _escrever_arquivo(self, final = False, codificador_final = None): """Turns the bits into bytes and saves them in the file""" # Assemble 8-bit sets to byte and save while len(self.buffer_escrita) >= 8: ## I didn't find a way to transform the binary (string) straight to byte, that's why these conversions ## # Transform binary to integer inteiro = int(self.buffer_escrita[:8], 2) # Convert integer to byte byte = bytes([inteiro]) self.arquivo_destino.write(byte) # Remove the 8 bits from the buffer that were saved in the file self.buffer_escrita = self.buffer_escrita[8:] # If it is the last part of the file, try to reach 8 bits and save if final: self.buffer_escrita = codificador_final() inteiro = int(self.buffer_escrita, 2) byte = bytes([inteiro]) self.arquivo_destino.write(byte) def _int_para_str_binario(self, inteiro): # Transforma inteiro em binario no formado string return bin(inteiro)[2:].zfill(8) # Formato string com len = 8 ################ CODIFIERS ################# # Receive full binary value and return encoded binary """ Basic rules of all encoders: - Everyone receives an integer value from 0 to 255, which represents a byte - Each byte exists in the reading file - Everyone must return binary in String format ('111001'), the which will be added to the encoded file Uza_final == When it is not possible to complete an entire byte with the last part of the encoded bits, then some treatment to fill the byte or when decoding can give some problem If it is necessary to use the binary instead of the entire value, it can be the "_int_para_str_binario" method was used to receive the integer value in string format (input: 10, return: '00001010') """ # Golomb -> prefix (unario) + 1 + suffix (binary) def _golomb(self, value ): # Calculates the quotient quotient = int(value / self.golomb_divisor) # Calculates the rest rest = bin(value % self.golomb_divisor)[2:].zfill(self.logDivisor) # Returns the encoded value return '1'.zfill(quotient + 1) + str(rest) # Write Golomb in the buffer def _trata_final_golomb(self): return self.buffer_escrita.ljust(8, '0')
groceries = ["apples", "bananas", "bread", "milk", "cheese" ] print (len(groceries)) print (groceries [4]) print ("bread" in groceries) for item in groceries: print (item) for num in range(len(groceries)): print (groceries[num]) groceries.append("meat") print (groceries)
class Condition(): STATES = ( 'Address', 'Protocol', 'Ports', 'Shell', 'Privilege', 'Binaries', 'CWD', 'Misudo', ) def __init__(self): """ Condition is used to validate whether a state can satisfy a specific goal. """ self.conditions = [] def __str__(self): msg = "===========\n" if len(self.conditions) == 0: msg += "None\n" else: for condition in self.conditions: msg += " ".join(condition) + "\n" msg += "===========\n" return msg def add(self, condition): """ Add conditions. :param condition: condition is a set which has 2 elements. :type condition: tuple The first is a key of a state. the second is a value for checking condition. """ self.conditions.append(condition) def is_satisfied(self, state): """ Checks if a given state satisfies a condition that is defined in this instance. Every condition should be satisfied. :param state: A state to be checked. :type state: dict :returns: True if a given state satisfies a condition otherwise False. :rtype: bool """ state_keys = list(state.keys()) for condition in self.conditions: key, value = condition state_value = state[key] if key not in state_keys: return False if key not in Condition.STATES: raise RuntimeError(f'Not implemented ({key})') else: if value == "EXIST": if key not in state_keys: return False if value == "NOT EXIST": if key in state_keys: return False # validating NEQ, EQ and INCLUDE if len(value.split(' ')) == 2: operator, value = value.split(' ') if operator == 'NEQ': if state_value == value: return False elif operator == 'EQ': if not state_value == value: return False elif operator == 'INCLUDE': if value in state_value: return True return False else: raise RuntimeError( f'Not implemented ({operator})') return True def is_explorable(self, state): """ Checks if a given state satisfies a condition that is defined in this instance considering the concept of ASSUMED, which means that this method is used to generate plan, not to perform plan. :param state: A state to be checked. :type state: dict :returns: True if a given state satisfies a condition otherwise False. :rtype: bool """ state_keys = list(state.keys()) for condition in self.conditions: key, value = condition if len(value.split(' ')) == 2: try: operator, value = value.split(' ') except IndexError: value = None if value == "NOT EXIST": if key in state_keys: return False if key not in state_keys or \ value != state[key]: return False if value is None or \ state[key] == 'UNKNOWN': continue return True
from board import Board from player import Player class Game: board = Board() players = [Player(), Player()] chosenCards = [] def play(self): self.board.draw() isPlaying = True currPlayer = 0 self.board.draw() while isPlaying: score = self.players[currPlayer].getScore() print(f'Tour du joueur {currPlayer + 1} (Nombre de paire : {score})') i = self.processInput() self.board.showCard(i) self.board.draw() card = self.board.getCard(i) self.chosenCards.append((i, card)) if len(self.chosenCards) == 2: if self.chosenCards[0][1] == self.chosenCards[1][1]: self.players[currPlayer].gainCard(card) print("Vous avez trouvé une paire!") else: self.board.hideCard(self.chosenCards[0][0]) self.board.hideCard(self.chosenCards[1][0]) currPlayer ^= 1 # change 0 en 1 et 1 en 0 print("Vous n'avez pas trouvé de paire...") self.chosenCards.clear() self.board.draw() def processInput(self): hasValidInput = False hasEnteredInput = False while not hasValidInput: if hasEnteredInput: print("Vous ne pouvez pas choisir cette carte!") print("Choisissez une carte") i = int(input()) - 1 hasEnteredInput = True if self.board.isOnBoard(i): hasValidInput = True return i
import re from ...errors.validation_error import ValidationError class EmailValidator: def __init__(self, field, allow_empty=False, trim=True, message='must be a valid email'): self.field = field self.trim = trim self.message = message self.allow_empty = allow_empty def __call__(self, instance): value = '' if hasattr(instance, self.field): value = getattr(instance, self.field) or '' if value and self.trim: value = str(value).strip() if not value and self.allow_empty: return # uses a simple regex strategy from # https://stackoverflow.com/questions/8022530/how-to-check-for-valid-email-address regex = r'[^@]+@[^@]+\.[^@]+' if not re.search(regex, value): raise ValidationError(self, self.field, self.message)
#%% # import packages import altair as alt import pandas as pd import numpy as np #%% # from json url to pandas dataframe url = "https://github.com/byuidatascience/data4missing/raw/master/data-raw/flights_missing/flights_missing.json" flights = pd.read_json(url) # GRAND QUESTION 1 #%% # What data are we dealing with? flights.columns #%% # Create a new data frame containing all data pertaining to delays. # Ask yourself which columns are related to airport delays in general, # Think of what data would be nice to have to determine which airport has the worst delays, worst_delays = (flights .groupby('airport_code') # group the data by airport to identify delay data for each airport .agg( flights_total = ('num_of_flights_total', sum), # sum up all flights for each airport delays_total = ('num_of_delays_total', sum), # sum up all delays for each airport minutes_total = ('minutes_delayed_total', sum) # sum up all minuted delayed for each airport ) .assign( percent_delays = lambda x: x.delays_total / x.flights_total, average_hours = lambda x: (x.minutes_total / x.delays_total) / 60 ) ) worst_delays # GRAND QUESTION 2 #%% # What data are we dealing with? flights.shape # %% # Create a new data frame containing all data pertaining to delays, # but group by month instead of by airport. best_months = (flights .groupby('month') .agg( flights_total = ('num_of_flights_total', sum), delays_total = ('num_of_delays_total', sum), minutes_total = ('minutes_delayed_total', sum) ) .assign( percent_delays = lambda x: x.delays_total / x.flights_total, average_hours = lambda x: x.minutes_total / x.delays_total / 60 ) .reset_index() .drop(labels=12, axis=0) ) best_months # %% chart = alt.Chart(best_months).encode( x = 'month', y = 'average_hours' ).mark_bar() chart # GRAND QUESTION 3 #%% # What data are we dealing with? flights.columns #%% # GOAL: Calculate total number of flights delayed by weather # TODO: Calculate 30% of late-arriving aircraft for mild weather delays # TODO: Calculate 40% of delayed flights in NAS from April to August, # TODO: Calculate 65% of delayed flights in NAS from September to March. #flights.replace("num_of_delays_late_aircraft", NaN, ) weather_delays = (flights .assign( # select all missing values in num_of_delays_late_aircraft and replace with the mean severe = lambda x: x.num_of_delays_weather.replace(-999, x.num_of_delays_weather.mean()), # calculate 30% of late-arriving aircraft to find some mild weather delays mild_late = lambda x: x.num_of_delays_late_aircraft * .30, # sum all values in the nas column from April to August and multiply by .40 mild_nas = lambda x: np.where( x.month.isin(["April", "May", "June", "July", "August"]), x.num_of_delays_nas * .40, x.num_of_delays_nas * .65), total_weather = lambda x: x.severe + x.mild_late + x.mild_nas, total_late = lambda x: x.num_of_delays_weather + x.num_of_delays_late_aircraft + x.num_of_delays_nas, percent_weather = lambda x: x.total_weather / x.total_late, ) .filter( ['airport_code', 'month', 'severe','mild_late','mild_nas', 'total_weather', 'total_late', 'percent_weather'] ) ) weather_delays # GRAND QUESTION 4 # This chart shows that the Atlanta airport has the worst ratio of delays caused by weather, meaning we can # expect the majority of delays have to do with weather for flights involving the Atlanta airport. #%% # create a barplot showing the proportion of all flights delayed by weather at each airport weather_chart = alt.Chart(weather_delays).encode( x = alt.X('airport_code', axis=alt.Axis(title='Airport Code')), y = alt.Y('percent_weather', axis=alt.Axis(format="%", title='Proportion of Flights Delayed by Weather')) ).mark_bar() weather_chart # GRAND QUESTION 5 #%% # Fix all of the varied missing data types in the data to be consistent # (all missing values should be displayed as "NaN") and save the new data # as a JSON file. #%% flights.isnull().sum() #%% flights.describe() #%% flights_new = flights.replace
from collections import Counter words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', 'under'] words_counts = Counter(words) top_three = words_counts.most_common(3) print(top_three)
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 23:06:19 2018 @author: Diana Narváez """ import math# Biblioteca para operaciones matemáticas #Ingreso de datos print("**********Cálculo del volumen de una esfera**********") R=float(input("Ingrese el valor radio en centimetros\n")) #Funcion que calcula el volumen de la esfera def volEsfera(R): # Cálculo del volumen de la figura volumen=((4/3)*(math.pi)*(R**3)) # Muestra en consola el resultado del volumen print("El volumen de la Esfera es = "+str(volumen)+" Cm cúbicos ") # Llamado a la función que cálcula de la esfera volEsfera(R)
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 15:06:08 2018 "Calculo de el volumen de un cono truncado" @author: José Cortez """ import math# Biblioteca para operaciones matemáticas #Ingreso de datos print("**********Cálculo del área de un Cono Truncado**********") R=float(input("Ingrese el valor del mayor radio en centímetros\n")) r=float(input("Ingrese el valor del menor radio en centímetros\n")) h=float(input("Ingrese el valor de la altura en centímetros\n")) #Función que calcula el volumen de un cono truncado def volCono(R,r,h): # Cálculo del volumen de la figura volumen=((1/3)*(math.pi)*(h)*(R**2+r**2+R*r)) # Muestra en consola el resultado del volumen print("El volumen de el Cono Truncado es = "+str(volumen)+" Cm cúbicos ") # Llamado a la función que cálcula el volumen de un cono truncado volCono(R,r,h)
'''An Integer I is called a factorial number if it is the factorial of a positive integer. The First few Factorial Numbers are 1,2,6,24 (0! =1 1!=1 2! =2 3!= 6). Given a number I, Write a Program that prints all factorial numbers less than or equal to I.''' def factorial(n): #function that performs factorial fact=1 #initially assigning the factorial value to 1 for i in range (1,n+1): #for(i=1;i<=inp,i++). sinc fact=fact*i return fact #returns the factorial if __name__=='__main__': #main function inp = int(input()) # takes the input for j in range(1,inp+1): #displays numbers from range 1,inp+1 based of inp #print(factorial(j) , end=" ") #obj j calling factorial fuction while(factorial(j) < inp): print(factorial(j) , end=" ") break
from enum import Enum odd_primitives = {str: "string", int: "integer", float: "float", bool: "boolean"} class odd(Enum): SHALLOW = "shallow" DEEP = "deep" LIST = "list" DICT = "dict" EMPTY = "empty"
# python object programming, regular method, static method and class method class Employee: numOfEmployee = 0 raiseRate = 0.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@email.com' Employee.numOfEmployee += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def printInfo(self): print("{}'s email address is: {}, and {}'s pay is: {}.".format(self.fullname(), self.email, self.fullname(), self.pay)) def applyRaise(self): # In order to get access to the raiseRate, get it through instance or classes, if the # instance do not have the attribute, it would try to find the attribute from the class # which it inheritate from. self.raiseRate could be changed to Employee.raiseRate. But if # you assign a value to the instance, example: instance.raiseRate = 1.05, then raiseRate for # this instance will refer to this value instead of searching for the class. self.pay = int(self.pay * (1 + self.raiseRate)) # Regular methods, static methods and class methods difference, regular methods automatically # take in self as the input parameter. Here we can see the difference between classmethods and # staticmethods. @classmethod def setRaiseRate(cls, rate): # So for class method, the first input of the member function is the class instead of self. cls.raiseRate = rate @classmethod def printNumEmployee(cls): print(cls.numOfEmployee) @classmethod def fromStr(cls, string): # This is a very important usage of the classmethod, to use it as an alternative constructor first, last, pay = string.split('-') # Here we have to return an instance, to pass into an object container return cls(first, last, pay) # For static method, there is no automatic input, it's like the regular function, we include # them inside the class because it has some logic connection with the class. @staticmethod def isWorkDay(day): # In python, .weekday return a number, where [0, 1, 2, 3, 4, 5, 6] indicate Monday to Sunday if day.weekday() not in [5, 6]: return True return False # test class implementation import datetime myDate = datetime.date(2016, 7, 11) print(Employee.isWorkDay(myDate)) # construct instances e1 = Employee.fromStr('Jack-Douson-7000') e2 = Employee.fromStr('Emily-Woodly-6000') e3 = Employee.fromStr('Will-Simon-10000') e1.printInfo() e2.printInfo() e3.printInfo() print(Employee.numOfEmployee) print() print(Employee.raiseRate) Employee.setRaiseRate(0.05) print(Employee.raiseRate)
import random import time import sys class Ability: ''' ability class ''' def __init__(self, name, attack_strength): self.name = name self.attack_strength = attack_strength def attack(self): min_attack = self.attack_strength // 2 max_attack = self.attack_strength return random.randint(min_attack, max_attack) def update_attack(self, attack_strength): self.attack_strength = attack_strength class Weapon(Ability): ''' weapon class ''' def attack(self): print("Using {} to attack".format(self.name)) return random.randint(0, self.attack_strength) class Armor: ''' armor class ''' def __init__(self, name, defense): self.name = name self.defense = defense def defend(self): return random.randint(0, self.defense) class Hero: ''' hero class ''' def __init__(self, name, health=100): self.abilities = list() self.name = name self.armors = list() self.start_health = health self.health = health self.deaths = 0 self.kills = 0 def defend(self): ''' hero defends self ''' armor = 0 for item in self.armors: armor += item.defense print("hero is defending") return armor def take_damage(self, damage_amt): ''' hero receives damage from enemy ''' self.health -= damage_amt print("{} damage amount:{} ".format(self.name, damage_amt)) if self.health <= 0: print("{} is down".format(self.name)) self.deaths += 1 print(self.deaths) print("Hero took {} damage".format(damage_amt)) def add_kill(self, kill): ''' modify hero kill count +1 ''' self.kills += kill print("Hero increased Kill Count") def attack(self): ttldmg = 0 for ability in self.abilities: print("{} was used by {}".format(ability.name, self.name)) ttldmg += ability.attack() print("{} damage was done by {}".format(ttldmg, self.name)) print("Hero attacked") return ttldmg def add_ability(self, ability_name, power): print("{} ability added".format(ability_name)) ability = Ability(ability_name, power) self.abilities.append(ability) def add_armor(self, armor): self.armors.append(armor) class Team: ''' team class made of heroes ''' def __init__(self, team_name): self.name = team_name self.heroes = list() def add_hero(self, hero): self.heroes.append(hero) print(" {} added to {}".format(self.heroes[-1].name, self.name)) def remove_hero(self, name): print("attempting to remove hero:", name) if self.heroes == []: print("Error: there are no heroes in this list") return 0 for hero in self.heroes: if hero.name == name: print("\nfound hero to remove:", hero.name) self.heroes.remove(hero) else: print("hero not found") return 0 def defend(self, damage): print("defending against {}".format(damage)) dmgpts = damage / len(self.heroes) deaths = 0 for hero in self.heroes: hero.health -= (dmgpts - hero.defend()) if hero.health <= 0: deaths += 1 return deaths def attack(self, enemyteam): print("attacking {}".format(enemyteam.name)) if len(enemyteam.heroes) == 0: print("There is no one on {}".format(enemyteam.name)) return 0 ttldmg = 0 for hero in self.heroes: print(hero.name) ttldmg += hero.attack() dmgpts = ttldmg / len(enemyteam.heroes) dmgpts = 1000 our_kills = 0 for hero in enemyteam.heroes: hero.take_damage(dmgpts) if hero.deaths > 0: our_kills += 1 for hero in self.heroes: hero.kills += our_kills return ttldmg def revive_heroes(self): print("Healing {}".format(self.name)) for hero in self.heroes: hero.health = 60 def find_hero(self, name): if self.heroes == []: print("there are no heroes in this list") return 0 for hero in self.heroes: if hero.name == name: print("{} found".format(name)) return hero else: print("hero not found") return 0 def view_all_heroes(self): for hero in self.heroes: print(hero.name) class Arena: def __init__(self): self.team_one = Team("Red Team") self.team_two = Team("Blue Team") self.running = True def l00p(self): while self.running == True: self.team_battle() else: print("Shutting down loop in 3 seconds") time.sleep(3) sys.exit(0) def build_team_one(self): hero1 = Hero(input("Name a hero > ")) hero1.add_ability(input("Name an ability > "), random.randint(1, 5) * 10) hero1.add_ability(input("Name another ability > "), random.randint(1, 5) * 10) hero2 = Hero(input("Name a hero > ")) hero2.add_ability(input("Name an ability > "), random.randint(1, 5) * 10) hero2.add_ability(input("Name another ability > "), random.randint(1, 5) * 10) self.team_one = Team(input("Name this new team > ")) self.team_one.add_hero(hero1) self.team_one.add_hero(hero2) def build_team_two(self): hero1 = Hero(input("Name a hero > ")) hero1.add_ability(input("Name an ability > "), random.randint(1, 5) * 10) hero1.add_ability(input("Name another ability > "), random.randint(1, 5) * 10) hero2 = Hero(input("Name a hero > ")) hero2.add_ability(input("Name an ability > "), random.randint(1, 5) * 10) hero2.add_ability(input("Name another ability > "), random.randint(1, 5) * 10) self.team_two = Team(input("Name this new team > ")) self.team_two.add_hero(hero1) self.team_two.add_hero(hero2) def team_battle(self): self.team_one.attack(self.team_two) self.team_two.attack(self.team_one) if __name__ == "__main__": arena = Arena() arena.build_team_one() arena.build_team_two() arena.l00p() time.sleep(5) arena.running = False
#!/usr/bin/env python ############################################################################# # Filename : Thermometer.py # Description : A DIY Thermometer # Author : Jerry Lee and Justin Le # modification: 06/01/2018 ######################################################################## import RPi.GPIO as GPIO import smbus import time import math address = 0x48 bus=smbus.SMBus(1) cmd=0x40 def analogRead(chn): #used for reading value, input is pin from PCF8591 value = bus.read_byte_data(address,cmd+chn) return value #def analogWrite(value): # bus.write_byte_data(address,cmd,value) def setupTemp(): #setup GPIO GPIO.setmode(GPIO.BOARD) def calculateTemp(value): voltage = value / 255.0 * 3.3 #calculate voltage Rt = 10 * voltage / (3.3 - voltage) #calculate resistance value of thermistor tempK = 1/(1/(273.15 + 25) + math.log(Rt/10)/3950.0) #calculate temperature (Kelvin) tempC = tempK -273.15 #calculate temperature (Celsius) return tempC def loop(): while True: value = analogRead(0) #read A0 pin print 'Temperature : %.2f'%(calculateTemp(value)) time.sleep(0.01) def destroy(): GPIO.cleanup() if __name__ == '__main__': print 'Program is starting ... ' setupTemp() try: loop() except KeyboardInterrupt: destroy()
# Problem: https://leetcode.com/problems/merge-intervals/ """ Note: sorting is important. Sorting ensures we only have to update previous interval's end as start will be always lower. """ from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: out = [] for interval in sorted(intervals, key=lambda i: i[0]): # if interval's start is less than or equal to previous interval's end i.e. it lies within bound of previous interval # e.g. interval = [2,6] and out[-1] = [1,3] # we update previous interval's end to the max one if out and interval[0] <= out[-1][1]: out[-1][1] = max(out[-1][1], interval[1]) else: out += interval, # out = out + [interval] # comma is important in currently used form return out print(Solution().merge([[1,3],[2,6],[8,10],[15,18]]))
''' 1. Capture smallest string and longest string 2. Iterate over smallest string: 2.a. return the sub-string till there is a match with longest string 3. By default smallest string is longest common prefix so return that ''' def longestCommonPrefix(strs) -> str: if not strs: return '' # since list of string will be sorted and retrieved min max by alphebetic order s1 = min(strs) # e.g. 'b' v/s 'abc' => 'abc' s2 = max(strs) """ Alternatively we could (to make it faster) use sort which is O(nlog(n)) time complexity strs.sort() s1, s2= strs[0], strs[-1] """ for i, c in enumerate(s1): print(f'[i]: {i}, [c]: {c}') if c != s2[i]: print(f'c => {c} != s2[i] => {s2[i]}') return s1[:i] # stop until hit the split index i.e. s1[0]...s[i-1] return s1 print(longestCommonPrefix(["flower","flow","flight"])) ''' [i]: 0, [c]: f [i]: 1, [c]: l [i]: 2, [c]: i c => i != s2[i] => o fl '''
# Problem: https://leetcode.com/problems/sqrtx/ """ - since 1 <= x <= x^2 for all x > 0 - we are going to search for a number that which sqaure is just right a bit larger than x e.g. 8 1 2 3 4 5 6 7 8 ^ ^ 1 2 3 4 5 6 7 8 ^ ^ 1 2 3 4 5 6 7 8 ^ ^ 1 2 3 4 5 6 7 8 ^ 3^2 = 9 is larger than 8, therefore answer should be 3-1=2 Time O(logn) Space O(1) """ class BinarySearchSolution(): def mySqrt(self, x): if x == x*x: return x left = 1 right = x while left < right: mid = (left + right)/2 if x >= mid*mid: left = mid + 1 else: right = mid return left-1 class Solution: def mySqrt(self, x: int) -> int: r = x + 1 # avoid dividing 0 while r*r > x: r = int(r - (r*r - x)/(2*r)) # newton's method return r print(Solution().mySqrt(8))
# Problem: https://leetcode.com/problems/largest-rectangle-in-histogram/ # CHECK ALSO maximal_rectangle_stack class Solution: def largestRectangleArea(self, height): height.append(0) # appending 0 at the end of height list for our convenience stack = [-1] # initialize stack with -1 so it picks up 0 height from height array ans = 0 # ans stores the max area so far for i in range(len(height)): print(f"i {i}") while height[i] < height[stack[-1]]: # When we are at a height that breaks the ascending height in stack h = height[stack.pop()] # get height of index at top of stack and simultaneously remove that index from stack print(f"h {h} from index {i-1} and top index now {stack[-1]}") w = i - stack[-1] - 1 # width is lower height index (stack[-1]) subtracted from index to the left of i which will be the index that was at the top of stack ans = max(ans, h * w) print(f"Rectangle: {stack[-1]}<->{i-1} [A]: {ans} and stack {stack}") stack.append(i) # store index onto stack as it has higher height than the current index at top of stack height.pop() # cleaning up the 0 we put return ans print(Solution().largestRectangleArea([1, 2, 3, 2, 1, 0, 2, 1, 1, 0])) #0 1 2 3 4 5 6 7 8 9 """ Rectangles considered: 1<->2 i.e. heights 2 <-> 3 [A]: 3 stack [-1, 0, 1] 1<->3 i.e. heights 2 <-> 2 [A]: 4 and stack [-1, 0, 1] 0<->3 i.e. heights 1 <-> 2 [A]: 6 and stack [-1, 0] 0<->4 i.e. heights 1 <-> 1 [A]: 6 and stack [-1, 0] -1<->4 i.e. heights 0 <-> 1 [A]: 6 and stack [-1] 5<->6 i.e. heights 0 <-> 2 [A]: 6 and stack [-1, 5] 7<->8 i.e. heights 1 <-> 1 [A]: 6 and stack [-1, 5, 7] 5<->8 i.e. heights 0 <-> 1 [A]: 6 and stack [-1, 5] """
x=int( input("Indique su peso en kg: ") ) y=float( input("Indique su altura en metros: ") ) print("Su imc es", x/y)
import math def hello(): print ('Варіант 27, програма для обчислення y в залежності від значення х') print('Чумак С.І., група КМ-12') def read_x(): x=float(input('Введіть значення х=')) return x def calculate_y(x): if x<-1.5 : y=math.pi*math.sin(x) else : if x>=2.5 : y=math.pi*x else : y=x*math.sin(x) return y if __name__ == "__main__": # execute only if run as a script hello() while True: try: x=read_x() y=calculate_y(x) print ("При значенні х = %f y = %f." % (x,y)) break except Exception as e: print (e)
"""Check HTTPS connection""" from urllib.parse import urlparse import requests from clint.textui import indent, colored, puts from helpers import get_domain def check(urls): """Check the urls for access through https""" for url in set(map(get_domain, urls)): puts(colored.white('Checking https for: ', bold=True) + colored.yellow(url)) with indent(2): if check_connection(url): check_redirect(url) def check_connection(url): """Check connection to the url using an head request over https""" puts('Connection ', newline=False) try: requests.head('https://' + url) except requests.exceptions.RequestException as err: print(colored.red('failed')) print(str(err)) return False else: print(colored.green('success')) return True def check_redirect(url): """Check if the url is redirecting http to https""" puts('Redirect ', newline=False) r = requests.head('http://' + url) if (r.status_code in [301, 302] and _check_redirect_location(url, r.headers['location'])): if r.status_code == 301: print(colored.green('yes')) else: print(colored.yellow( 'yes but using a 302 redirect, consider using 301')) else: print(colored.red('no')) def _check_redirect_location(url, location): parsed_location = urlparse(location) return (parsed_location.scheme == 'https' and parsed_location.netloc == url)
def evaluar(nom, ape): if int(len(nom))<10 and int(len(ape))<10: print ("Nombre y apellido correctos") else: print("Nombre y/olargoooooo apellido muy largos") nombre="" apellido="" nombre = str(input("Por favor introduzca nombre=")) apellido= str(input("Por favor introduzca apellido=")) evaluar(nombre,apellido)
lista = [1, 2, 3, 5, 6, 7, 8] pares = [] impares = [] for i in lista: if i % 2 == 0: pares.append(i) else: impares.append(i) print("los pares " + str(pares)) print("los impares " + str(impares))
what = input('Что делаем?? (+, -, %, /, *)\n') number = int(input('Первое число ')) number1 = int(input('Второе число ')) if what == '+': res = number + number1 elif what == '-': res = number - number1 elif what == '*': res = number * number1 elif what == '%': res = number % number1 elif what == '/': res = number / number1 print('Результат: ' + str(res))
""" Chloe Harrison """ MIN_LENGTH = 5 password = input("Enter password: ") while len(password) < MIN_LENGTH: print("Needs 5 characters") password = input("Enter password: ") print("*" * len(password))
#Created by Shikha Singh import cv2 #Creating a function to generate live sketch of the object detected by webcam def sketch(img): #The 'if' statement is used to check that frames are passed correctly if img is not None: print("image is present") print(len(img.shape)) #converting the image to grayscale color space to apply thresholding img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #using blurring operation(Gaussian Blur) to smoothen & clean up any noise in the image img_gray_blur=cv2.GaussianBlur(img_gray,(3,3),0) #for edge detection, using 'Canny' method canny_edges=cv2.Canny(img_gray_blur,10,70) #the threshold operation returns 2 functions: #'ret' is a boolean variable returning True or False if the image is detected or not respectively #'mask' is our final sketch after applying all image manipulation functions ret,mask=cv2.threshold(canny_edges,70,255,cv2.THRESH_TOZERO) return mask #Creating a cap variable which pulls image from the webcam cap=cv2.VideoCapture(1) #running a loop, else the cap variable will capture image of a particular instant while True: #'frame' refers to the actual image captured from the webcam ret,frame=cap.read() #applying an 'if' condition to check if captured image is detected in the program if frame is not None: print("frame present") #the 'imshow' function is used for displaying the openCV window with the desired output cv2.imshow('live sketcher',sketch(frame)) #waitKey() function allows to input an information when a window is open #applying condition for detection of enter key #thus, the program terminates when user presses Enter key if cv2.waitKey(1)==13: break #cap.release() is used to release the camera. If it is not applied, leads to either abnormal termination or #hanging & locking up of the kernel. cap.release() #the below command is used to close all open windows of openCV cv2.destroyAllWindows()
#7 columns of 6 rows, #starts in bottom left corner. #not successultt stopping the other player when they have a column of 3 and you have col of 2 """ chunking makes moves for any player maybe do by dictionary with board val and number of, then length to see how many tyoes there are if len 2 and one is -1, add the move add way to sort moves by num_full, and then by player for specifc player when have priority list, check for validity, and if not go on. check if board with new value would make the other player win add to list of dont move there if nothing, go random as long as not on no put list """ #check by chunking from logic import board_won class Move(object): def __init__(self, direction, player, num_filled, start_col, start_row, end_col, end_row): self.direction=direction self.player=player self.num_full=num_filled self.start_row=start_row self.start_col=start_col self.end_row=end_row self.end_col=end_col def sets_up_other(board, col, row, player, num_players): new_board=[] for i in range(7): new_board.append([]) for j in range(6): new_board[i].append(board[i][j]) new_board[col][row]=player if board_won(new_board, num_players): return False if stop_other_three(new_board, player, num_players)!=-1: return True return False def process_move(board, move, num_players): #see if itll go where you want #make sure it doesn't set up anyone else player=move.player col=move.start_col row=move.start_row if board[col][row]==-1 and col_right_height(board, col, row)and not sets_up_other(board, col, row, player, num_players): return col if move.direction=='row': for i in range(1,4): if board[col+i][row]==-1 and col_right_height(board, col+i, row) and not sets_up_other(board, col+i, row, player, num_players): return col+i if move.direction=='col': for i in range(1,4): if board[col][row+i]==-1 and col_right_height(board, col, row+i) and not sets_up_other(board, col, row+i, player, num_players): return col if move.direction=='diag1': for i in range(1,4): if board[col+i][row+i]==-1 and col_right_height(board, col+i, row+i) and not sets_up_other(board, col+i, row+i, player, num_players): return col+i if move.direction=='diag2': for i in range(1,4): if board[col+i][row-i]==-1 and col_right_height(board, col+i, row-i) and not sets_up_other(board, col+i, row-i, player, num_players): return col+i return -1 #returns if can't fill in any of the spots def check_others(board, num_players, moves_list): for i in range(5): moves=moves_list[i] for move in moves: if process_move(board, move, num_players)!=1: return process_move(board,move, num_players) return -1 def pop_top_move(board, moves, player, num_players): #get col at the end from this player_3=other_3=player_2=other_2=player_1=other_1=[] for move in moves: if move.player==player and move.num_full==3: if process_move(board, move, num_players)!=1: return process_move(board, move, num_players) elif move.player==player and move.num_full==2: player_2.append(move) elif move.player==player and move.num_full==1: player_1.append(move) elif move.num_full==3: other_3.append(move) elif move.num_full==2: other_2.append(move) else: other_1.append(move) return check_others(board, num_players, [other_3, player_2, other_2, player_1, other_1]) def rows(board, moves): for j in range(6): for i in range(4): chunk={} for k in range(4): if board[i+k][j] not in chunk: chunk[board[i+k][j]]=1 else: chunk[board[i+k][j]]+=1 if len(chunk)==2 and (-1 in chunk): for player_key in chunk: if player_key!=-1: moves.append(Move('row', player_key, chunk[player_key], i, j, i+3, j)) return moves def cols(board, moves): for i in range(7): for j in range(3): chunk={} for k in range(4): if board[i][j+k] not in chunk: chunk[board[i][j+k]]=1 else: chunk[board[i][j+k]]+=1 if len(chunk)==2 and (-1 in chunk): for player_key in chunk: if player_key!=-1: moves.append(Move('col', player_key, chunk[player_key], i, j, i, j+3)) return moves def diag_up_right(board, moves): #diagonal going from bottom left to top right for col in range(4): for row in range(3): chunk={} for i in range(4): if board[col+i][row+i] not in chunk: chunk[board[col+i][row+i]]=1 else: chunk[board[col+i][row+i]]+=1 if len(chunk)==2 and (-1 in chunk): for player_key in chunk: if player_key!=-1: moves.append(Move('diag1', player_key, chunk[player_key], col, row, col+3, row+3)) return moves def diag_up_left(board, moves): #go from upper left to bottom right for col in range(4): for row in range(3): #will be 6 minus this chunk={} for i in range(4): if board[col+i][5-row-i] not in chunk: chunk[board[col+i][5-row-i]]=1 else: chunk[board[col+i][5-row-i]]+=1 if len(chunk)==2 and (-1 in chunk): for player_key in chunk: if player_key!=-1: moves.append(Move('diag2', player_key, chunk[player_key], col, 5-row, col+3, 2-row)) return moves def find_moves(board,player): #return a list of Move objects #check for every row chunk, then cols, then diag and other diag #when putting in, check if will set up other for winning (modify board and winning move funtion) #check if can be placed there(full under it)-- col right height function moves=[] moves=rows(board, moves) moves=cols(board, moves) moves=diag_up_right(board, moves) moves=diag_up_left(board, moves) return moves def get_ai_move(board, player, num_players): moves=find_moves(board, player) move=pop_top_move(board, moves, player, num_players) if move!=-1: return move return get_column(board) if __name__ == "__main__": board=[ \ [-1,-1,-1,-1,-1,-1], \ [-1,-1,-1,-1,-1,-1], \ [-1,-1,-1,-1,-1,-1], \ [-1,-1,-1,-1,-1,-1], \ [-1,-1,-1,-1,-1,-1], \ [-1,-1,-1,-1,-1,-1], \ [-1,-1,-1,-1,-1,-1] \ ]
# returns index of number just lesser/equal than num def binarySearchCeilIndex(arr, start, end, num): print(start, end) if end == start: if arr[start] >= num: return start elif arr[start] < num: return min(start + 1, len(arr) - 1) else: mid = (start + end)//2 if(arr[mid] == num): return mid elif arr[mid] < num: return binarySearch(arr, mid + 1, end, num) else: return binarySearch(arr, start, mid, num) arr = [2, 3, 5, 7, 9, 10, 18, 101] arr1 = [10, 11] print(binarySearch(arr1, 0, len(arr1) - 1, 12))
def quick_select(arr, k): if(len(arr)<=1): return arr[0] pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] l = len(left) m = len(middle) r = len(right) if(l>=k): return quick_select(left, k) elif (l+m)>=k: return middle[k-l-1] else: return quick_select(right, k-l-m) class Node: def __init__(self): self.char = '' self.childNodes = {} class Trie: def __init__(self): self.root = Node() def insertChar(self, word): current_node = self.root currentChar = 0 wordlen = len(word) while word[currentChar] in current_node.childNodes and currentChar<wordlen: current_node = current_node.childNodes[word[currentChar]] currentChar+=1 if currentChar<wordlen: while currentChar<wordlen: nextNode = Node() current_node.childNodes[word[currentChar]] = nextNode current_node = nextNode currentChar+=1 def printit(self, node): for child in node.childNodes.keys(): print child self.printit(node.childNodes[child]) trie = Trie() trie.insertChar("apple") trie.printit(trie.root)
from PIL import Image, ImageFilter # basic pillow img processing img = Image.open("./pokedex/bulbasaur.jpg") # filtered = img.filter(ImageFilter.BLUR) # BLUR, SHARPEN, SMOOTH etc more in docs. # filtered = img.convert("L") # converted into a grayscale - "L" mode here, mode avaible - in docs. # filtered.save("./pokedex/_bulba.png") # img.show() # opens an image in a explorer # img.resize((width, height) <- tuple) , img.rotate(degrees 90/180/270 etc) other methods avaible in docs # box = [100, 100, 400, 400] # img.crop(box) # cropes the img for position in the box # for resize we can use .thumbnail method to try to keep an aspect ratio of the img
print("enter 5 numbers") numbers = [input('number 1:'),input('number 2:'),input('number 3:'),input('number 4:'),input('number 5:')] print("the smallest number is {}".format(min(numbers))) print("the largest number is {}".format(max(numbers))) print("the first number is {}".format(numbers[0])) print("the last number is {}".format(numbers[len(numbers)-1]))
""" CP1404/CP5632 Practical File renaming and os examples """ import os, shutil __author__ = 'Lindsay Ward' print("Current directory is", os.getcwd()) # change to desired directory os.chdir('Lyrics/Christmas') # print a list of all files (test) # print(os.listdir('.')) # make a new directory os.mkdir('temp') # loop through each file in the (original) directory for filename in os.listdir('.'): # ignore directories, just process files if not os.path.isdir(filename): if filename.replace(' ', '') != filename: new_name = filename.replace(' ', '_') else: i = 1 # first character is neglected length = len(filename) new_name = False while i < length-4: if not new_name: if filename[i].upper() == filename[i]: new_name = filename[0:i] + '_' + filename[i:length] length = len(new_name) i += 1 else: if new_name[i].upper() == new_name[i]: new_name = new_name[0:i] + '_' + new_name[i:length] length = len(new_name) i += 1 i += 1 if new_name: new_name = new_name.replace('.TXT', '.txt') print(new_name) # Option 1: rename file to new name - in place # os.rename(filename, new_name) # Option 2: move file to new place, with new name shutil.move(filename, 'temp/' + new_name) # Processing subdirectories using os.walk() # os.chdir('..') # for dir_name, subdir_list, file_list in os.walk('.'): # print("In", dir_name) # print("\tcontains subdirectories:", subdir_list) # print("\tand files:", file_list)
for i in range(1, 13): print("No. {0} squared is {1} and cubed is {2}" .format(i, i ** 2, i ** 3)) print() for i in range(1, 15): print("No. {0:2} squared is {1:3} and cubed is {2:3}" .format(i, i ** 2, i ** 3)) print() for i in range(1, 13): print("No, {0:2} squared is {1:<3} and cubed {2:<4}" .format(i, i ** 2, i ** 3)) print() for i in range(1, 13): print("No. {0:2} squared is {1:>3} and cubed {2:^5}" .format(i, i ** 2, i ** 3)) print() print("Pi is approximately {0:12}".format(22/7)) print("Pi is approximately {0:12f}".format(22/7)) print("Pi is approximately {0:12.50f}".format(22/7)) print("Pi is approximately {0:52.50f}".format(22/7)) print("Pi is approximately {0:62.50f}".format(22/7)) print("Pi is approximately {0:<72.50f}".format(22/7)) print("Pi is approximately {0:<72.54f}".format(22/7)) print() for i in range(1, 13): print("No. {} squared is {} and cubed {:4}" .format(i, i ** 2, i ** 3)) print() print() print("This is the calculation for 33/7: {0}".format(33/7)) print("This is the calculation for 33/7: {0:3f}".format(33/7)) print("This is the calculation for 33/7: {0:6f}".format(33/7)) print("This is the calculation for 33/7: {0:12.50f}".format(33/7)) print("This is the calculation for 33/7: {0:6.5f}".format(33/7)) print("This is the calculation for 33/7: {0:6.2f}".format(33/7)) print("This is the calculation for 33/7: {0:8.50f}".format(33/7))
import random class Guesser(): def __init__(self): self.list_word =["house", "table", "rock", "guesser"] self.word = random.choice(self.list_word) self.display = "" self.first_hint = "" self.fails = 0 def get_hint(self): self.display = '_' * len(self.word) self.first_hint = self.display #print(self.word) return self.first_hint def do_guess(self,letter): # replace underscore with the letter found in the word i = 0 if letter in self.word: while self.word.find(letter, i) != -1: i = self.word.find(letter, i) self.display = self.display[:i] + letter + self.display[i + 1:] i += 1 else: self.fails += 1 return self.display #returns fails from do_guess def get_back_fails(self): return self.fails #returns word from do_guess def get_back_word(self): return self.word
# 交换变量简易的方法 a, b = 1, 2 print(f"a:{a}b:{b}") a, b = b, a print(f"a:{a}b:{b}") # 引用 在python中,值都是靠引用来传递来的,引用可以当做实参传递 # id()返回变量在内存中的十进制的地址 用于判断两个变量是同一个值的引用 a = 1 b = a print("%d\n%d" % (id(a), id(b))) """ 可变类型:列表 字典 集合 不可变类型:整形 浮点型 字符串 元组 """
# lambda[匿名函数]表达式:如果一个函数有一个返回值,并且只有一句代码,可以使用lambda简化 """ 语法: lambda 参数列表 : 表达式 lambda表达式的参数可有可无,函数的参数在表达式中完全适用 lambda表达式能接受任何形式的参数,但是只能返回一个值 """ def fn1(): return 200 fn2 = lambda: 100 print(fn2) # 直接打印表达式,返回内存地址 print(fn2()) # lambda 参数:返回值兼表达式 fn3 = lambda a, b: a + b print(fn3(2, 114)) # lambda 参数可以使用默认参数 可变参数[*args]和[**kwargs] fn4 = lambda a, b, c=100: a + b + c print(fn4(10, 20)) fn5 = lambda *args: args print(fn5('xiaoming', 'xiaoli')) fn5 = lambda **kwargs: kwargs print(fn5(name='xiaoli', age=12)) # 带判断的lambda fn6 = lambda a, b: a if a > b else b # 三元表达式 print(fn6(500, 100)) # 列表数据按字典key的值排序 students = [ {'name': 'TOM', 'age': 12}, {'name': 'ROSE', 'age': 19}, {'name': 'Jack', 'age': 22} ] students.sort(key=lambda x: x['name'], reverse=True) print(students)
# 递归 # 需求N以内的数字累加和1+2+3...+N def user_add(num): if num == 1: return 1 return num + user_add(num - 1) print(user_add(3))
import random """ 列表一个列表存储最好是相同类型 """ list1 = ["replace", "split", "join", "strip", "just"] str1 = "replace split join strip just" """ len(名)返回长度[公共操作] index和count用法基本一致 """ print(len(list1)) """ 判断指定数据是否在某个列表序列中[公共操作] in not in print("split" in list1) print("split" in str1) str = input("请输入要查找的字符串") if str in list1: print(f"找到了!{str}在数组中底数为{list1.index(str)}") else: print(f"找不到{str}") """ """ 添加内容 append列表增加到结尾 append追加数据的时候如果数据是一个序列,就会追加整个序列 extend列表追加 追加如果是应该序列,会拆开依次追加 insert(位置,数据) 指定位置追加 其他效果同 append """ list1.append("juele") print(list1) list1.append(["juele","liangle"]) list1.extend(["ljust","rjust"]) list1.insert(4, ["ljust","rjust"]) print(list1) """ 删除内容 del 可以指定一个数据也可以指定下标删除 pop 指定下标或者删除最后一个数据,返回被删除的数据 remove 删除名字 clear 清空列表 """ str2 = [1, 2, 3, 4, 5, 6] # del str2[1] print(str2) """ reverse 逆序 sort(reverse=布尔) 排序 """ str2.reverse() print(str2) """ copy 列表复制 """ str3 = str2.copy() print(str3) list2 = [] class1 = [] class2 = [] class3 = [] effices = [[], [], []] i = 0 while i < 8: strc1 = "cla"+str(i) list2.append(strc1) i += 1 print(list2) for k in list2: num = random.randint(0, (len(effices)-1)) effices[num].append(k) list2.clear() print(f"办公室{list2}") print(effices) for effice in effices: print(f"{effices.index(effice)}号办公室有{len(effice)}个人,他们分别是", end=" ") for cls in effice: print(f"{cls}", end=" ") print("") # end=p127
import random """ 循环 """ i = 0 while i < 5: print("好吧(╯▽╰)", end="") i += 1 print("结束") i = 1 Sum = 0 while i <= 100: if i % 2 == 0: Sum += i print(i, end=" ") i += 1 print(f"\n{Sum}") # 满足一定条件退出循环 # break--直接退出循环 continue--退出本次循环,执行下一次循环 i = 1 while i < 100: if i == random.randint(1, 10): print(f"\n你吃到虫子了,所以第{i}个苹果扔了") i += 1 continue elif i >= 10: print("你吃饱了") break else: print(f"你吃到第{i}个苹果", end=" ") i += 1 i = 0 while i < 9: k = 0 i += 1 while k < i: k += 1 print(f" {i}x{k}={i*k}", end="\t") print("") """ for 临时变量 in 序列: 代码 """ Str = "hello world!" for i in Str: if i == "r": continue print(f"{i}", end="") """ while...else 此处的else需要循环正常结束之后才能执行 for...else 同理 """ i = 0 while i <= 5: print(f"这是第{i}次", end=" ") i += 1 if i == 5: print("跳出") continue else: print("执行了吗?") """ 如果循环体遇到break跳出循环,则不会执行else里面的语句 而遇到continue则依然会执行else里面的语句 """ """ a = 0 b = 0 while not((a == 3) or (b == 3)): Player = int(input("请出拳,0--石头,1--剪刀,2--布 :>")) computer = random.randint(0, 2) if ((Player == 0) and (computer == 1)) or \ ((Player == 1) and (computer == 2)) \ or ((Player == 2) and (computer == 0)): print("玩家获胜") a += 1 elif Player == computer: print("平局") else: print("电脑获胜") b += 1 if a == 3: print("游戏结束,玩家胜利") else: print("游戏结束,电脑胜利") """
print "programa para guardar el menu del restaurante" seguir = True menu = {} while seguir: plato = raw_input("Escribe aqui el nombre del plato: ") precio = raw_input("Escribe aqui el precio del plato: ") menu [plato] = precio nuevo_plato = raw_input("desea escribir otro plato, responda con ( s o n ): ") if nuevo_plato == "s" : seguir = True else: seguir = False print "Fin del menu Hasta la proxima." respuesta = raw_input ("responde (s o n) para imprimir el menu: ") if respuesta == "s" : print menu with open("menu.txt", "w+") as menu_file: # open the file for writing and overwrite the previous file (w+) for dish in menu: menu_file.write( "%s, %s EUR\n" % (dish, menu[dish])) # write this text into the file and add a new line at the end (\n) else: print "No se imprime el menu, Hasta la proxima."
#import the csv file and read it import os import csv import math csvpath = os.path.join('PyBank','Resources','Python_PyBank_Resources_budget_data.csv') total_months = 0 total_p_l = 0 change_list = [] previous_row = 0 change = 0 month_money_list = [] with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') #define and print headers csv_header = next(csvreader) print(f"CSV Header: {csv_header}") #total count of column 0 to get total # of months in the set #store as variable "total_months" for row in csvreader: total_months += 1 #sum of column 2 to get the net total profits/losses #store as variable "total_p_l" total_p_l += int(row[1]) change = int(row[1]) - previous_row previous_row = int(row[1]) change_list.append(change) month_money_list.append(row[0]) #get the initial value out change_list.pop(0) month_money_list.pop(0) #net_monthly_avg = sum(change_list) / (total_months - 1) #calculate average change over time net_monthly_avg = round(sum(change_list) / len(change_list), 2) #print(net_monthly_avg) #print(total_months) #print(total_p_l) #print(net_monthly_avg) #calculate greatest increase month #store as a variable #find a way to associate greatest inc with month included min_loss = min(change_list) find_the_min_loc = change_list.index(min_loss) last_min = month_money_list[find_the_min_loc] #calculate greatest losses month #store as a variable #find a way to associate greatest loss with month included max_gains = max(change_list) find_the_max_loc = change_list.index(max_gains) last_max = month_money_list[find_the_max_loc] #run report print("Total Months: " + str(total_months)) print("Total: " + str(total_p_l)) print("Average Change: $" + str(net_monthly_avg)) print("Greatest Increase in Profits: $" + str(max_gains) + " during " + str(last_max)) print("Greatest Decrease in Profits: $" + str(min_loss) + " during " + str(last_min)) #export report as txt file output_path = os.path.join('PyBank', 'analysis', 'analysis.txt') with open(output_path, "w") as output_file: output_str = ( f"Total Months: {total_months}\n" f"Total: {total_p_l}\n" f"Average Change: ${net_monthly_avg}\n" f"Greatest Increase in Profits: ${max_gains} {last_max}\n" f"Greatest Decrease in Profits: ${min_loss} during {last_min}\n" ) output_file.write(output_str)
from tkinter import * root = Tk() root.geometry("500x50") root.title("Testing Entry") def printMessage(event): global e i = e.get() print(i) e.delete(0,END) frame = Frame(root) Label(frame,text="Enter Value: ").pack(side="left") e = Entry(frame) e.pack(side="left") printButton = Button(frame,text="PRINT") printButton.bind("<Button>", printMessage) printButton.pack(side="left") frame.pack() root.mainloop()
banks = [] for i in range(3): bank = [] for j in range(10): bank.append([j,0,0]) banks.append(bank) def deposit(bank,accno,v): bank = banks[bank] acc = bank[accno] if v > 0: acc[1] += v acc[2] = v def withdraw(bank,accno,v): bank = banks[bank] acc = bank[accno] if v > 0 and v <= acc[1]: acc[1] -= v acc[2] = -v def statement(bank,accno): bank = banks[bank] acc = bank[accno] print("Account: ",acc[0]) print("Balance: ",acc[1]) print("Last Transaction: ",acc[2]) def transfer(sender,sbank,receiver,rbank,v): withdraw(sbank,sender,v) deposit(rbank,receiver,v) def printBank(bank): size = len(banks[bank]) for i in range(size): statement(bank,i) for i in range(3): printBank(i) print("---------------------Testing Operations---------------------") deposit(2,0,100) statement(2,0) deposit(0,7,190) withdraw(0,7,50) statement(0,7) print("---------------------Testing Transfer---------------------") transfer(7,0,0,2,35) statement(0,7) statement(2,0)
from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['POST', 'GET']) def hello(): if request.method == "GET": return ''' <form action="/" method="POST"> <label>Message: </label> <input type="text" name="msg"> <br> <br> <label>Times: </label> <input type="number" name="times"> <br> <br> <input type="submit" value="Submit"> </form> ''' else: msg = request.form.get('msg') #Object has changed. now it is "form" obj, not "args" times = request.form.get('times') if msg == None or msg == '': msg = "Hello World" if times == None or times == '': times = 10 else: times = int(times) str = "" for i in range(0,times): str += '<h1> {} </h1>'.format(msg) return str app.run()
print("Welcome") print("Enter value for i") ##string input i = input() print("The Value entered is",i) print("Enter value for j") j = input() print("The Value entered is",j) z = i + j print("The Sum is",z) a = int(input("Enter value of a")) ##integer input print('The value entered for a is',a) b = int(input("Enter value of b")) print('The value entered for b is',b) z = a + b print("The Sum is",z) z = int(i) - int(j) ##Type casting print("The Difference is",z) z = (int(i) + int(j)) / 2 print("The Average is",z)
#Learning if statements. #if-else flag = False print("Entering Program1") if flag : #<--- if expression: print("Inside If") else: #<---clause print("Inside Else") #<---suite print("Leaving program1") #if-elif-else i = 20 print("Entering Program2") if i == 1 : print("Value of i is 1") elif i == 2 : print("Value of i is 2") elif i == 3 : print("value of i is 3") else: print("Value of i is other than 1,2 or 3") print("Leaving program2") #nested if i = 3 j = 4 print("Entering Program3") if i < 5: #venus print("###") if j == 4: #mars print("%%%") else: #belongs to venus print("$$$") print("Leaving program3")
# Stage 2 print("Welcome to Closure") # Container / Environment def f1(a,b): print("Entering f1") print("a = ",a) print("b = ",b) # f2 is not visible outside def f2(c,d): #nested/local functn print("Entering f2") print("c = ",c) print("d = ",d) print("Leaving f2") f2(3,4) #Can be called inside f1 only print("Leaving f1") f1(10,20) f1(1,2) # after f1 is over Activation rec of f1 will die # AR of f1 has a,b,f2(ref var f2) # which means f2 will be deleted # since nothing is pointing to f2 # f2 obj will get garbage collected # how many ever times f1 is called, f2 is created and destroyed
i=3 j=6 if i>=3 and j<13 : print('&&&') j=31 if j <25: print('@@@') elif j >20 : if i <=3: print('^^^') else : print('###') else : print('$$$')