blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
9ef3e7f62f753112d3a52053fa58ac8bb8a2d13d
dchandrie/Python
/inheritance.py
634
3.875
4
class pet: def __init__(self, name, age): self.name=name self.age=age def show(self): print("I am "+ str(self.name)+" and I am "+str(self.age)+" years old!") def speak(self): print("Hi!") class cat(pet): def __init__(self, name, age, color): super().__init__(name, age) self.color=color def speak(self): print("Meow") class Dog(pet): def speak(self): print("Bark") class Fish(pet): pass p=pet("Tim", 19) p.show() p.speak() c=cat("Bill", 34, "blue") c.show() c.speak() d=Dog("Jill", 25) d.show() d.speak() f=Fish("Mean", 1) f.show() f.speak()
fc1ba6d87024fa57eb85b0bd1601eb1fe1507132
IvTema/Python-Programming
/lesson1.12_step6.py
458
3.90625
4
# https://stepik.org/lesson/5047/step/6?unit=1086 a = int(input()) t=("программист") ta=("программиста") tov=("программистов") if 11<=a<=14 or (a-11)%100==0 or (a-12)%100==0 or (a-13)%100==0 or (a-14)%100==0: print(a, tov) elif (a-1)%10==0 or a==1: print(a, t) elif (a-2)%10==0 or a==2: print(a, ta) elif (a-3)%10==0 or a==3: print(a, ta) elif (a-4)%10==0 or a==4: print(a, ta) else: print(a, tov)
9df8f31fab565fbccea395cff93136e545c40c41
vmms16/MonitoriaIP
/Dicionarios/lista_dicionarios_02.py
526
4.03125
4
linhas=int(input("Numero de linhas: ")) colunas=int(input("Numero de colunas: ")) matriz={} for i in range(1,linhas+1,1): for j in range(1, colunas+1,1): matriz[i,j]=input("Insira um valor: ") matriz_transposta={} for i in range(1,linhas+1,1): for j in range(1, colunas+1,1): matriz_transposta[j,i]=matriz[i,j] for i in range(1,colunas+1,1): str_matriz="" for j in range(1,linhas+1,1): str_matriz+=matriz_transposta[i,j]+" " print(str_matriz)
a68e315033e7231eee39411763c7d5f2f94b21d6
JonesCD/P-E-Problems
/pe011.py
2,045
3.546875
4
""" What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20x20 grid? """ import time start = time.clock() import winsound Freq = 200 # Set Frequency To 2500 Hertz Dur = 250 # Set Duration To 1000 ms == 1 second ############################ import csv filename = 'pe011-grid.txt' grid = [] with open(filename, 'rb') as file: k = 0 for row in file: nums = [int(n) for n in row.split()] grid.append(nums) k += 1 rows = k columns = len(grid[0]) #print grid nums = [0, 0, 0, 0] maxnum = 0 maxseq = [] # going to multiply 4 numbers and check if product is biggest def prod(vals): global maxnum, maxseq # maxnum = 0 # maxseq = [0, 0, 0, 0] prodnum = 1 for n in range(4): prodnum *= vals[n] #print prodnum, #print vals if prodnum > maxnum: maxnum = prodnum maxseq = vals return maxnum, maxseq # check side to side for r in range(rows): for c in range(columns - 3): nums = grid[r][c : c + 4] prod(nums) print maxnum, 'side to side: ', maxseq # check top to bottom maxnum = 0 maxseq = [] nums = [0, 0, 0, 0] for c in range(columns): for r in range(rows - 3): nums = [grid[r][c], grid[r + 1][c], grid[r + 2][c], grid[r + 3][c]] # for p in range(4): # nums[p] = grid[r + p][c] prod(nums) # print maxnum, maxseq print maxnum, 'top to bottom: ', maxseq # check diagonals top left to bottom right maxnum = 0 maxseq = [] nums = [0, 0, 0, 0] for r in range(rows - 3): for c in range(columns - 3): nums = [grid[r][c], grid[r + 1][c + 1], grid[r + 2][c + 2], grid[r + 3][c + 3]] prod(nums) print maxnum, 'top left diagonal: ', maxseq # check diagonals bottom left to top right maxnum = 0 maxseq = [] nums = [0, 0, 0, 0] for r in range(3, rows): for c in range(columns - 3): nums = [grid[r][c], grid[r - 1][c + 1], grid[r - 2][c + 2], grid[r - 3][c + 3]] prod(nums) print maxnum, 'bottom left diagonal: ', maxseq ############################ end = time.clock() print 'elapsed time:',end - start winsound.Beep(Freq,Dur)
5ac44d446284a88b7382a166fcdea58c6db67b16
richnakasato/interviews
/reverse_ll_with_k.0.py
1,501
3.75
4
class Node(object): def __init__(self, data, next_=None): self.data = data self.next = next_ def reverse_ll(head): curr = head prev = None while curr: temp = curr.next curr.next = prev prev = curr curr = temp return prev def reverse_ll_with_k(head, k): curr = head prev = None new_head = None count = 0 stack = list() while curr: if count < k: stack.append(curr) curr = curr.next count += 1 else: while len(stack): if not prev: prev = stack.pop() if not new_head: new_head = prev else: prev.next = stack.pop() prev = prev.next return new_head def main(): head = curr = None n = 9 for num in range(1, n): if not head: head = Node(num) curr = head else: curr.next = Node(num) curr = curr.next curr = head while curr: print(curr.data) curr = curr.next ''' print("reversed") rev_head = reverse_ll(head) curr = rev_head while curr: print(curr.data) curr = curr.next ''' print("reversed k") rev_head = reverse_ll_with_k(head, 2) curr = rev_head while curr: print(curr.data) curr = curr.next if __name__ == "__main__": main()
a890dc9d5cb9a3344fabd3f6bcef8d49d129df02
BinXiaoEr/Target_to-Offer
/64.求1+2+n.py
324
3.53125
4
# -*- coding:utf-8 -*- class Solution: def Sum_Solution(self, n): # write code here return sum(list(range(1,n+1))) class Solution: def Sum_Solution(self, n): # write code here result=n temp=n>0 and self.Sum_Solution(n-1) result+=temp return result
7f19bff1d0ca20cf98b6081e70d8dfb523a20845
keisuke-isobe/Magic8Ball
/isquestion.py
630
4.15625
4
""" Function which returns if the input text is a question or not. This is determined by checking first if the sentence ends with a question mark. If it does, it is assumed that the statement is a question. If it doesn't end with a question mark, the function then checks if the statement contains any of the words that are associated with a question, if it does, it is considered a question. """ import string def isQuestion(text, question_words): text = text.translate(string.punctuation) text = text.lower() if text[-1] == '?': return True else: return not set(text).isdisjoint(question_words)
0d27c8874549c8930eec5588f37da379bd67ab8a
sdetcoding/Python_Basics
/basic/datatype/setbasic.py
872
3.921875
4
# --------- Lets Play with Set ------------------------------------- st = {1, 2, 3} print(st) # empty set est = {} print(est) # adding value to set st.add(4) st.add(40) st.add(64) st.add(42) print(st) # removing value from set st.pop() st.remove(42) st.discard(42) # will not throw error if element is not present print(st) # creating set by se constructor b = set([2, 3, 4, 88, 44, 22, 77]) # length of set print(len(b)) # finding all the method associate with set print(dir(b)) # union of set print(st | b) print(st.union(b)) # difference print(st - b) print(st.difference(b)) # frozen the value of set s = frozenset(b) print(s) # trying to add value to frozenset try: s.add(99) except Exception as e: print(e) finally: print("you cant add value to frozen set") # ------------------------------- Ending up the set --------------------------------
a148c63e4631c16a5575f6258162b835496aaf44
Akanksha-Verma31/Python-Practice-Problems
/Problem14.py
220
4.09375
4
# print the square of first 10 numbers i = 1 while (i<=10): print(f"Square of {i} is :" ,i**2) i+=1 # print the square of first 10 numbers x = 1 while (x<=10): print(f"Square of {x} is :" ,x*x) x+=1
b9f77525940724fdc33c559573a487fec20c4d10
Vickybilla/PRACTICA-PHYTON
/EjerciciosPython/ejercicio2-1.py
908
4.34375
4
"""Ejercicio 1: Pedir al usuario que ingrese un mensaje cualquiera, si el mensaje tiene más de 100 caracteres imprimirlo por pantalla, si tiene entre 50 y 100 caracteres imprimirlo al revés, si no se cumple ninguna de las opciones anteriores, por pantalla devolver un mensaje que diga "su mensaje es demasiado corto".""" mensaje_de_usuario = input("Ingrese un mensaje cualquiera ") # mensaje_de_usuario.count(len(mensaje_de_usuario)) """if len(mensaje_de_usuario) > 100: print(mensaje_de_usuario) elif 50 < len(mensaje_de_usuario) < 100: print(mensaje_de_usuario[::-1]) else: 0 < len(mensaje_de_usuario) <50 print("el mensaje es demasiado corto ")""" #solucion if len(mensaje_de_usuario) < 50: print("el mensaje es demasiado corto ") elif 50 < len(mensaje_de_usuario) < 100: print(mensaje_de_usuario[::-1]) else: len(mensaje_de_usuario) > 100 print(mensaje_de_usuario)
23a58c2a73fefb1e66a57faa02e44603a4c18626
capnhawkbill/simple-game
/randomfunctions.py
1,636
3.8125
4
import os def valid_input(): """Gets valid input from user""" while "true": output = int(input("> ")) if output > 10 or output < 1: print("input needs to be between 1 and 10") else: break return output def y_or_n(): """gets y or n from user""" while "true": output = input("> ") if output == "y": return 1 break elif output == "n": return 0 break else: print("Type y or n") def cls(): #placeholder = os.system("clear") #placeholder = os.system("cls") print("\033c") def player_input(): """get a valic player action""" while "true": cls() print("What do you want to do?") print("\t -Attack (a)") print("\t -Defend (d)") print("\t -Inventory (i)") print("\t -Switch Weapon (sw)") print("\t -Switch Armour (sa)") print("\t -View Quick Reference (r)") print("\t -Quit (q)") print("-" * 30) action = input("> ") if action == "a": player_action.attack() break elif action == "d": player_action.defend() break elif action == "i": player_inventory.list() break elif action == "sw": cls() print("With what weapon do you want to switch?") print("-" * 30) weapon = input("> ") player_inventory.equip_weapon(weapon) break elif action == "sa": cls() print("With what armour do you want to switch?") print("-" * 30) armour = input("> ") player_inventory.equip_armour(armour) break elif action == "r": print("Work in progress") break elif action == "q": print("are you sure? [Y,n]") sure = input("> ") if sure == "Y": sys.exit() else: print("That option is not recognised")
0a9dc0e80a2c71609520cafc6774127100e100f7
manufactured/Youtube_Scraper_mod1
/src/get_api_key.py
1,687
3.5
4
from googleapiclient.discovery import build from googleapiclient.errors import HttpError from httplib2 import ServerNotFoundError from google.auth.exceptions import DefaultCredentialsError ''' Get the API key and save it in a text file named, key.txt in parent folder. The method to get a youtube API key is well illustrated in the Youtube Video in the README page. ''' class api_key(): def __init__(self): self.youtube = None def get_api_key(self): try: with open('key.txt') as key_file: api_key = key_file.read() youtube = build('youtube','v3',developerKey=api_key) self.youtube = youtube except HttpError: print("\nAPI Key is wrong") print("Please recheck the API key or generate a new key.\nThen modify the 'key.txt' file with new Key\n") except ServerNotFoundError: print("\nUnable to connect to internet...") print("Please Check Your Internet Connection.\n") except DefaultCredentialsError: print("\n'key.txt' is Blank.") print("Please save your API key there and then continue.\n") except FileNotFoundError: print("\nNo such file: 'key.txt'") print("Please create a file named 'key.txt' and place your Youtube API key in it.\n") except Exception as e: print(e) print("Oops!", e.__class__, "occurred.") def get_youtube(self): return self.youtube if __name__ == "__main__": youtube_instance = api_key() youtube_instance.get_api_key() youtube = youtube_instance.get_youtube() print(youtube)
1891ca42f5cdb9f4f7f73119fed178d0a71fffe4
lbedoyas/Python
/Clase 1/if_else.py
307
3.875
4
sueldo1=int(input("Introduce el sueldo 1: ")) sueldo2=int(input("Introduce el sueldo 2: ")) #condicional if / else if sueldo1>sueldo2: print("El sueldo 1: " + str(sueldo1) + " Es mayor que sueldo2 " + str(sueldo2)) else: print("El sueldo 1: " + str(sueldo1) + " Es menor que sueldo2 " + str(sueldo2))
4aa92163cb1bd33f09aec4de69259308cebf6296
WenboTien/python_assignment_test
/firewall.py
2,455
3.5
4
import csv from IPy import IP """ input: the string of the port range output: The list consists of all qualified port number """ def port_range(port_str): if port_str.find('-') < 0: return [int(port_str)] port_list = port_str.split('-') return [i for i in range(int(port_list[0]), int(port_list[1]) + 1)] pass """ input: the string of the IP address range output: The list consists of all qualified Ip address in Decimal """ def ip_range(ip_str): if ip_str.find('-') < 0: return [int(IP(ip_str).strDec())] ip_list = ip_str.split('-') return [i for i in range(int(IP(ip_list[0]).strDec()), int(IP(ip_list[1]).strDec()) + 1)] pass class Firewall: """ This is the Firewall constructor, I build a map to store the input: eg: {'inbound_tcp' : {80 : set('192.168.1.2', '192.168.1.3')}} {'outbound_udp' : {1000 : set('192.168.1.2', '192.168.1.3')}} """ def __init__(self, csvPath): self.map = {} try: with open(csvPath, 'r') as csvFile: reader = csv.reader(csvFile) for row in reader: direct_protocol = row[0] + '_' + row[1] if direct_protocol not in self.map: self.map[direct_protocol] = {} for port in port_range(row[2]): if port not in self.map[direct_protocol]: self.map[direct_protocol][port] = set() for ip in ip_range(row[3]): self.map[direct_protocol][port].add(ip) except Exception as detail: print "This is the error ==> ", detail """ This is the search function: (1)we check if the direction and protocol exists in the map, (2)than we check if the port number exists (3)after that, we check the ip_address information The Time Complexity : O(1) """ def accept_packet(self, direction, protocol, port, ip_address): try: direct_protocol = direction + '_' + protocol if direct_protocol not in self.map: return False if port not in self.map[direct_protocol]: return False if int(IP(ip_address).strDec()) not in self.map[direct_protocol][port]: return False return True except Exception as detail: print "This is the error ==> ", detail
c7406591b4511b69e6c8b28e6c096497e89d34f0
gustavo-zsilva/exercicios-python-cev
/PythonExercicios/ex054.py
873
3.921875
4
from datetime import date data = date.today().year maiores = 0 menores = 0 for c in range(1,8): ano = int(input('Digite o ano que a {}ª pessoa nasceu: '.format(c))) if data - ano >= 18: maiores += 1 else: menores += 1 if ano >= data: print('\033[31mValor Inválido.\033[m') print('Ano de nascimento será igual ao seu ano atual menos um.') ano = data - 1 else: if maiores == 0: valor = 'Não temos maiores de idade, então temos 7 menores.' elif menores == 0: valor = 'Não temos menores de idade, então temos 7 maiores.' elif maiores == 1: valor = 'Temos 1 maior de idade e 6 menores.' elif menores == 1: valor = 'Temos 1 menor de idade e 6 maiores.' else: valor = 'Temos {} maiores e {} menores de idade.'.format(maiores, menores) print(valor)
58baef245b36eb2e74e6e10e63accd38ce724d78
trew13690/CSC101Code
/Work/Exam/app.py
3,763
3.5
4
""" App.py ~ This App build Meh Faces !!! 0.0 -_- by Alex Trew ~ 03/21/19 """ from graphics import * import math class App(): """ App - Contains all high level objects """ def __init__(self, faceR=50,eyeR=10, facecolor='blue', eyeColor='red', noseColor='green', noseWidth=10): self.window = GraphWin("Meh Face", width=600, height=600) self.window.setCoords(-100,-100,100,100) self.window.bind("<Motion>", self.getCoordinates) self.face = Face(self.window,faceR=int(faceR),eyeR=int(eyeR),facecolor=facecolor,noseColor=noseColor, noseWidth=noseWidth,eyeColor=eyeColor) def getCoordinates(self, event): print(event) points = self.window.toWorld(event.x, event.y) points = [round(p,2) for p in points] print(str(points)) def run(self): print('Running ...') self.window.getMouse() self.window.close() class Face(): """ Face ~ Represents the whole of a face """ def __init__(self, window, facecolor, eyeColor,noseColor ,noseWidth, faceR, eyeR): print('Creating a face!') self.head = Head(window, faceR, facecolor) self.eyes = Eye(window,faceR,eyeR,eyeColor) self.nose = Nose(window,noseWidth,noseColor) self.smile = Smile(window,faceR) class Head(): """ The Face component """ def __init__(self,window, radius,facecolor, center=Point(0,0), ): self.radius = radius self.window = window self.head = Circle(center, radius) self.draw() self.head.setFill(facecolor) def draw(self): print('Making a head first !') self.head.draw(self.window) class Eye(): """ Draws two eye Components """ def __init__(self, window,faceR, radius, eyeColor): self.window = window self.radius = radius self.eyeCenterR = Eye.calculateEyeDistance(faceR, 'right') self.eyeCenterL = Eye.calculateEyeDistance(faceR, 'left') self.eyel = Circle(self.eyeCenterR,self.radius) self.eyel.draw(self.window) self.eyer = Circle(self.eyeCenterL, self.radius) self.eyer.draw(self.window) self.eyer.setFill(eyeColor) self.eyel.setFill(eyeColor) def calculateEyeDistance(faceR, side): if (side == 'right'): angle = 45 x = (faceR/2)*math.cos(angle) y = (faceR/2)*math.sin(angle) return Point(x,y) else: angle = 45 x = (faceR/2)*math.cos(angle) x = -x y = (faceR/2)*math.sin(angle) return Point(x,y) class Nose(): def __init__(self, window,noseWidth,noseColor): self.nose = Rectangle(Point( -noseWidth/2 ,noseWidth),Point(noseWidth/2,-noseWidth)) self.nose.draw(window) self.nose.setFill(noseColor) class Smile(): def __init__(self, window, radius): self.window = window self.radius = radius self.smile = Line(Point(-radius/3,-radius/3),Point( radius/3,-radius/3)) self.smile.draw(self.window) print('Welcome to the meh creator!') print('Please enter the information as asked!') radius = input('\nWhat is the desired radius of the head?') eyeRadius = input('What is your desired eye radius?') noseWidth = input('what is the nose width?') colorPick = input('What is the desired color for the head?') eyeColorPick = input('What eye color do you wish? ') noseColorPick = input('what color of nose do you wish?') # Create check here to convert empty string allow defaults in App() SmileApp = App(radius,eyeRadius, facecolor=colorPick,noseWidth=int(noseWidth), noseColor=noseColorPick, eyeColor=eyeColorPick) SmileApp.run()
2541b58048a273a757541d64790f30504eeaa9a6
devdo-eu/zombreak
/logic/city_card.py
464
3.703125
4
from enums.zombie import ZombieType class CityCard: def __init__(self, zombie: ZombieType = ZombieType.ZOMBIE): if zombie == ZombieType.SURVIVOR: raise Exception('Card cannot be init with survivor on top!') self.active = True self.top = ZombieType.SURVIVOR self.bottom = zombie def flip(self) -> None: """Method used to flip card up side down.""" self.top, self.bottom = self.bottom, self.top
462f98f9352fea25e34ed30e0f5832781f848948
anthonywww/CSIS-9
/lockers.py
1,692
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Program Name: lockers.py # Anthony Waldsmith # 7/6/2016 # Python Version 3.4 # Description: Show how many lockers are open/close after a alternating loop run for each value instance 1000 times. # Optional import for versions of python <= 2 from __future__ import print_function step = 0 totalLockers = 1000 locker = [] openLockerCount = 0 closeLockerCount = 0 for i in range(0, totalLockers): locker.append(False); for i in range(totalLockers): # Incerement the step step += 1 for j in range(0, totalLockers, step): # Set the current locker to the current mode locker[j] = not locker[j]; # Taking into consideration locker[0] should always be open locker[0] = True for i in range(totalLockers): if(locker[i] == True): openLockerCount += 1 print("Locker %i is open" %(i)) else: closeLockerCount += 1 #print("Locker %i is closed" %(i)) print ("There are a total of %i lockers open, and a total of %i lockers closed" %(openLockerCount, closeLockerCount)) """ Locker 0 is open Locker 1 is open Locker 4 is open Locker 9 is open Locker 16 is open Locker 25 is open Locker 36 is open Locker 49 is open Locker 64 is open Locker 81 is open Locker 100 is open Locker 121 is open Locker 144 is open Locker 169 is open Locker 196 is open Locker 225 is open Locker 256 is open Locker 289 is open Locker 324 is open Locker 361 is open Locker 400 is open Locker 441 is open Locker 484 is open Locker 529 is open Locker 576 is open Locker 625 is open Locker 676 is open Locker 729 is open Locker 784 is open Locker 841 is open Locker 900 is open Locker 961 is open There are a total of 32 lockers open, and a total of 968 lockers closed """
bced22f69c020ef81941798b781f50c20dd89805
kavitshah8/PythonSandBox
/tutoring/hello1.py
232
3.984375
4
def con(): grade = int(input("Enter your final grade")) if grade >= 90 : print ("A") elif grade >=80: print ("B") elif grade >= 70: print ("C") else : print ("Avg")
6c6c7643baaaf284e739ee3f0bd6a2964b2c0474
mahoep/ME-499
/Lab5/complex.py
4,569
3.875
4
#!usr/bin/env python3 ''' @author Matthew Hoeper ''' import math class Complex: def __init__(self, re=0, im=0): if isinstance(re, int) or isinstance(re, float): self.re = re else: raise TypeError('Real part must be an integer or float') if isinstance(im, int) or isinstance(im, float): self.im = im else: raise TypeError('Imaginary part must be an integer or float') def __repr__(self): return self.__str__() def __str__(self, re=0, im=0): if self.im < 0: r = '({} - {}i)'.format(self.re, abs(self.im)) else: r = '({} + {}i)'.format(self.re, self.im) return r def __add__(self, other): try: re = self.re + other.re im = self.im + other.im except: re = self.re + other im = self.im return Complex(re, im) def __radd__(self, other): return self.__add__(other) def __sub__(self, other): try: re = self.re - other.re im = self.im - other.im except: re = self.re - other im = self.im return Complex(re, im) def __rsub__(self, other): try: re = other.re - self.re im = other.im - self.im except: re = other - self.re im = -self.im return Complex(re, im) def __mul__(self, other): try: re = self.re * other.re - (self.im * other.im) im = self.im * other.re + self.re * other.im except: re = self.re * other im = self.im * other return Complex(re, im) def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): try: re = (self.re * other.re + self.im * other.im) / (other.re**2 + other.im**2) im = (self.im * other.re - self.re * other.im) / (other.re**2 + other.im**2) except: re = self.re/other im = self.im/other return Complex(re, im) def __rtruediv__(self, other): if isinstance(other, int) or isinstance(other, float): re = (other * self.re) / (self.re**2 + self.im**2) im = (-other * self.im) / (self.re**2 + self.im**2) return Complex(re, im) else: return self.__truediv__(other) def __neg__(self): re = self.re * -1 im = self.im * -1 return Complex(re, im) def __invert__(self): re = self.re im = self.im * -1 return Complex(re, im) def __pow__(self, power): r = sqrt(self.re**2 + self.im**2) theta = math.atan2(self.im, self.re) real = r ** power * math.cos(power * theta) imaginary = r ** power * math.sin(power * theta) return Complex(real, imaginary) def sqrt(num): if isinstance(num, int) or isinstance(num, float): if num >= 0: return num ** (1/2) else: imaginary_ans = abs(num) ** (1/2) return Complex(0, imaginary_ans) # return imaginary_ans elif isinstance(num, Complex) and num.im == 0 and num.re >= 0: try: return Complex(sqrt(abs(num.re)), num.im) except: return num elif isinstance(num, Complex) and num.re < 0 and num.im == 0: return Complex(0, sqrt(abs(num.re))) elif isinstance(num, Complex) and num.re == 0: re = num.re im = num.im real_ans = (1 / sqrt(2)) * abs(sqrt(sqrt(re ** 2 + im ** 2) + re)) if im < 0: sign = -1 elif im == 0: sign = 0 else: sign = 1 imaginary_ans = (sign / sqrt(2)) * abs(sqrt(sqrt(re ** 2 + im ** 2) - re)) return Complex(real_ans, imaginary_ans) elif isinstance(num, Complex) and num.im != 0 and num.re != 0: re = num.re im = num.im real_ans = (1/sqrt(2)) * abs(sqrt(sqrt(re**2 + im**2) + re)) if im < 0: sign = -1 elif im == 0: sign = 0 else: sign = 1 imaginary_ans = (sign/sqrt(2)) * abs(sqrt(sqrt(re**2 + im**2) - re)) return Complex(real_ans, imaginary_ans) else: raise TypeError('Input must be a int, float, or complex') if __name__ == '__main__': a = Complex(1, 2) print (-a,'(-1 - 2i)') print (~a,'(1 - 2i)') a = 1.23 c = Complex(1.23, 3.45) print(sqrt(a), sqrt(c))
a01da818cdc80f09e1fd08ce587ba28b0ec5795b
makennamartin97/python-algorithms
/loweruppermap.py
424
4.25
4
# Write a function that creates a dictionary with each (key, value) pair # being the (lower case, upper case) versions of a letter, respectively. # mapping(["p", "s"]) ➞ { "p": "P", "s": "S" } # mapping(["a", "b", "c"]) ➞ { "a": "A", "b": "B", "c": "C" } # mapping(["a", "v", "y", "z"]) ➞ { "a": "A", "v": "V", "y": "Y", "z": "Z" def mapping(letters): map = {} for l in letters: map[l] = l.upper() return map
73a1f13ddb50eb74c88fa151bf7ff7ebceb5299f
Eunjuni/Indoor-Tracking
/Server/localization.py
7,971
3.515625
4
import math import re import sys import csv import localizationTrilateration ''' BSSID: Basic Service Set Identifier SS: signal strength RSSI: Received signal strength indicator AP location: access point location The basic service set (BSS) provides the basic building block of an 802.11 wireless LAN. Each BSS is uniquely identified by a BSSID. ''' ''' Input to this function is the location string. This function parses the string using str.split() function, with the delimiter as "::::" This function also finds the BSSID that has the greatest Signal Strength ''' def Parsing(location, BSSID_APinfo): BSSID_SignalStrength = {} MsgArray = location.split("::::") PhoneMAC = MsgArray[0] APCount = MsgArray[1] APData = MsgArray[2] TimeStamp = MsgArray[-1] start_tags = [m.end() for m in re.finditer("<", APData)] end_tags = [m.start() for m in re.finditer(">", APData)] max_SS = -sys.maxint - 1 for index in range(len(start_tags)): BSSID_SS = APData[start_tags[index]:end_tags[index]] BSSID = BSSID_SS[:BSSID_SS.find('-')] SS = int(BSSID_SS[BSSID_SS.find('-'):]) # find the greatest Signal Strength if BSSID in BSSID_APinfo and SS > max_SS: max_SS = SS max_BSSID = BSSID BSSID_SignalStrength[BSSID] = SS return (BSSID_SignalStrength, PhoneMAC, TimeStamp, max_BSSID) ''' Get_SSIDLocation() is a sub function that takes the dictionaries BSSID_SignalStrength, BSSID_APinfo as inputs, and return the dictionary BSSID_APinfo. Using this function, we can tell the X, Y, Z coordinates of a single BSSID captured. An additional feature of this function is to report BSSID not found in BSSID_APinfo. This happens because only the access points in Phillips Hall are considered into our calculation, however, in some of the measurement points, BSSID relating to access points in Upson Hall or Duffield Hall might be captured as well. ''' def Get_BSSIDlocation(BSSID_SignalStrength,BSSID_APinfo, APlocation): BSSIDlocation = dict() keys = BSSID_SignalStrength.keys() for i in range(len(keys)): if keys[i] in BSSID_APinfo: temp = BSSID_APinfo[keys[i]][0] if temp in APlocation: BSSIDlocation[keys[i]] = APlocation.get(temp,"unknown") else: print "AP location not found " + keys[i] + " " + str(BSSID_SignalStrength[keys[i]]) return BSSIDlocation ''' WeightedCentroid() is a sub function that takes the dictionaries BSSID_SignalStrength and BSSIDlocation as inputs, and returns a list called predicted_location which contains the predicted X, Y and Z coordinates values for the current occupant. This algorithm is used in three dimensions in this project. ''' def WeightedCentroid(BSSID_SignalStrength,BSSIDlocation, SignalStrength_RSSI, FloorNum): '''BSSID_SignalStrength is a dictionary where the key is the BSSID detected, the correponding #value is the related signal strength. BSSIDlocation is the location of the #"BSSID", only the APlocation has physical address, but we are using mapping # to find the APlocation the BSSID belongs to. #BSSIDlocation = {'00:0b:86:5c:f9:02': [1,2,3], '00:0b:86:5c:f9:03': [4,5,6]} #BSSID_SignalStrength = {'00:0b:86:5c:f9:02': -65, '00:0b:86:5c:f9:03': -65};''' floorNum_z = { 1 : 199.05, 2 : 650.65, 3 : 1139.85, 4 : 1466.35 } data = {} g = 1.3 sumweight = 0 X = 0.00 Y = 0.00 Z = 0.00 for SSID in BSSID_SignalStrength: if (SSID in BSSIDlocation) and (BSSIDlocation[SSID][2] == floorNum_z[FloorNum]): signalStrength = BSSID_SignalStrength[SSID] Rssi0 = SignalStrength_RSSI[signalStrength] signalpower = math.pow(10,Rssi0/20.0) weight = math.pow(signalpower,g) #print SSID, "weight: ", weight, BSSID_APinfo[SSID] data[SSID] = weight sumweight = sumweight + weight for SSID in data.keys(): if (SSID in BSSIDlocation) and (BSSIDlocation[SSID][2] == floorNum_z[FloorNum]): position= BSSIDlocation[SSID] x = position[0] y = position[1] z = position[2] weight = data[SSID] X = X + x * weight / sumweight Y = Y + y * weight / sumweight Z = Z + z * weight / sumweight predicted_location = [X,Y,Z] if predicted_location[0]==0: predicted_location[0]=-1 if predicted_location[1]==0: predicted_location[1]=-1 if predicted_location[2]==0: predicted_location[2]=-1 return predicted_location ##''' ##Location_AP() is a sub function that returns the access point locations ##detected at each measurement point. The inputs to this function are BSSID_SignalStrength, ##BSSID_APinfo. The num as an input to this file can be used as an iterator, to calculate ##average for multiple measurements. If a single trial then num=0 ##''' ##def Location_AP(num,BSSID_SignalStrength,BSSID_APinfo): ## Seen_APs = [] ## location_APseen = {} ## keys = BSSID_SignalStrength.keys() ## for i in range(len(keys)): ## if keys[i] in BSSID_APinfo: ## if BSSID_APinfo[keys[i]] in Seen_APs: ## continue; ## else: ## Seen_APs.append(BSSID_APinfo[keys[i]]) ## location_APseen[num] = Seen_APs ## ## return location_APseen ''' Give the BSSID that has the greatest signal strength Find the corresponding APID and read its z coordinate, which indicates which floor this AP is on. Use this floor number as the user's floor number ''' def getFloorNumber(max_BSSID, BSSID_APinfo, APlocation): z_floorNum = { 199.05 : 1, 650.65 : 2, 1139.85 : 3, 1466.35 : 4 , } if max_BSSID in BSSID_APinfo: APID = BSSID_APinfo[max_BSSID][0] return z_floorNum[APlocation[APID][2]] else: print "BSSID %s is not in BSSID_APinfo" % (max_BSSID) return -1 ''' Input is some constant data: BSSID_APinfo, SignalStrength_RSSI, APlocation Start to calculate use's position ''' def start(location, BSSID_APinfo, SignalStrength_RSSI, APlocation): (BSSID_SignalStrength, PhoneMAC, TimeStamp, max_BSSID) = Parsing(location, BSSID_APinfo) BSSIDlocation = Get_BSSIDlocation(BSSID_SignalStrength, BSSID_APinfo, APlocation) # Get floor number FloorNum = getFloorNumber(max_BSSID, BSSID_APinfo, APlocation) if FloorNum == -1: raise '''For running trilateration on the samples''' # make ap with multipe signals not double count BSSID_FixedSignalStrength = localizationTrilateration.fixRssi(BSSID_SignalStrength, BSSIDlocation) predicted_location = WeightedCentroid(BSSID_FixedSignalStrength, BSSIDlocation, SignalStrength_RSSI, FloorNum) possiblePts = [] # check points around weighted centroid predicted location (but not in z axis) for i in range(-200,210,10): for j in range(-200,210,10) : possiblePts.append([predicted_location[0] + i, predicted_location[1] + j, predicted_location[2]]) max = 0 ptPredicted = [] for pt in possiblePts: prob = localizationTrilateration.probabilityPt(pt, BSSID_FixedSignalStrength, BSSIDlocation, FloorNum) if prob > max: ptPredicted = pt max = prob #The following block is to store output result output_file = open("documentation.csv",'a') data = csv.writer(output_file,dialect = 'excel') if max > 0: data.writerow([PhoneMAC,TimeStamp,ptPredicted, FloorNum]) output_file.close() return (ptPredicted, PhoneMAC, FloorNum) else: data.writerow([PhoneMAC,TimeStamp,predicted_location, FloorNum]) output_file.close() return (predicted_location, PhoneMAC, FloorNum)
3e69933b6a38d3ac73f36cfab2769c32f95a5077
rkandekar/python
/DurgaSir/ob_input_eval.py
347
4.4375
4
#automatically it will evaluate, eval() takes string and evaluate print(eval("1+2+3")) expression=input("Enter some expression:") result=eval(expression) print(result) #eval is smart will determine the variable type x=eval(input("Enter one variable int or float or sting or any type:")) print(type(x)) print(x) for a in x: print(a)
38cc1e8ff475ce4a1ad0ece56aca429ed3c372c2
panditprogrammer/python3
/python97.py
338
4.25
4
# isupper and is lower function in python print("This is isupper function") x="This is paragraph." print(x.isupper()) print(x.islower()) print(x.istitle()) print("This is uppercase") n=x.upper() print(n.isupper()) print("This is lowercase.") m=x.lower() print(m) print("This is checking title is lower or uppercase.") o=x.title() print(o)
48d48b33f00df1a5cb7e1e06c8637e99a09481d0
rahulmitra-kgp/cnn_build_stepwise
/cnn_build_stepwise.py
7,858
3.515625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import cv2 import matplotlib.pyplot as plt # we will visualize the below mentioned image later on # change the path and provide the path from your file system img = cv2.imread('C:\\Users\\rmitra\\Desktop\\photograph\\fruits\\fruits-360\\Training\\Mango\\13_100.jpg') # In[2]: import numpy as np from sklearn.datasets import load_files # change the path and provide the path from your file system training_folder = 'C:\\Users\\rmitra\\Desktop\\photograph\\fruits\\fruits-360\\Training' test_folder = 'C:\\Users\\rmitra\\Desktop\\photograph\\fruits\\fruits-360\\Test' # ## Preprocessing starts here # ### loading dataset # In[3]: def load_mydata(folder_path): dataset = load_files(folder_path) output_labels = np.array(dataset['target_names']) file_names = np.array(dataset['filenames']) output_class = np.array(dataset['target']) return file_names,output_class,output_labels # Loading training and test dataset x_training, y_training, output_labels = load_mydata(training_folder) x_test, y_test,_ = load_mydata(test_folder) #Loading finished print('Training image datset size : ' , x_training.shape[0]) print('Test image dataset size : ', x_test.shape[0]) # In[4]: count_output_classes = len(np.unique(y_training)) print("Number of ouput classes : ",count_output_classes) # ### output classes are converted to one-hot vector # In[5]: from keras.utils import np_utils y_training = np_utils.to_categorical(y_training,count_output_classes) y_test = np_utils.to_categorical(y_test,count_output_classes) # ### testset splitted into validation and test dataset # Generally for creating validaion set we should use some standard technique # like k-way cross validation on training set. # In competitions where you don't know the output label of testset, # there anyway you don't have a way to create validation set from testset. # For the sake of simplicity ,during demo I created validation set from testset, since # for my case I know the output label for testset. # But genarally, you should try to create validation set from training set. # In[6]: x_test,x_validation = x_test[8000:],x_test[:8000] y_test,y_vaildation = y_test[8000:],y_test[:8000] print('Vaildation set size : ',x_validation.shape) print('Test set size : ',x_test.shape) # ### all the images are converted to arrays # In[7]: from keras.preprocessing.image import load_img,img_to_array def image_to_array_conversion(filenames): img_array=[] for f in filenames: # Image to array conversion img_array.append(img_to_array(load_img(f))) return img_array x_training = np.array(image_to_array_conversion(x_training)) x_validation = np.array(image_to_array_conversion(x_validation)) x_test = np.array(image_to_array_conversion(x_test)) # ### normalization of training,validation and testset # In[8]: x_training = x_training.astype('float32')/255 x_validation = x_validation.astype('float32')/255 x_test = x_test.astype('float32')/255 # ## Preprocessing ends here # ## CNN building starts here # # #### Recommendation is to use GPU system for larger Dataset # #### For GPU you need to use GPU version of tensorflow and keras. # In[13]: from keras.models import Sequential from keras.layers import Conv2D,MaxPooling2D from keras.layers import Activation, Dense, Flatten, Dropout model = Sequential() #Addition of Convolution layer model.add(Conv2D(filters = 8, kernel_size = 2,activation= 'relu',input_shape=(100,100,3))) model.add(MaxPooling2D(pool_size=2)) # In[14]: # function for printing the original image of a mango def print_image(model1,img1) : img_batch = np.expand_dims(img1,axis=0) print(img_batch.shape) img_conv = model1.predict(img_batch) print(img_conv.shape) #img2 = np.squeeze(img_conv,axis=0) #print(img2.shape) plt.imshow(img2) # function for visualizing the image after pooling operation. # In the last line of this function the 7th activation map has been printed. # You can check other activation maps by just changing the value of last index. def print_pooled_image(model1,img1): img_batch = np.expand_dims(img1,axis=0) print(img_batch.shape) img_conv = model1.predict(img_batch,verbose=1) print(img_conv.shape) plt.matshow(img_conv[0, :, :, 6], cmap='viridis') # ## Print image of a Mango # In[15]: plt.imshow(img) # ## Print the same image after applying Convolution and pooling operation # In[16]: print_pooled_image(model,img) # ## Adding other layers of CNN # In[17]: #Addition of Pooing layer #model.add(MaxPooling2D(pool_size=2)) #Addition of Convolution Layer and Pooling Layer for 3 more times model.add(Conv2D(filters = 16,kernel_size = 2,activation= 'relu')) model.add(MaxPooling2D(pool_size=2)) model.add(Conv2D(filters = 32,kernel_size = 2,activation= 'relu')) model.add(MaxPooling2D(pool_size=2)) model.add(Conv2D(filters = 64,kernel_size = 2,activation= 'relu')) model.add(MaxPooling2D(pool_size=2)) #Flattening the pooled images model.add(Flatten()) #Adding hidden layer to Neural Network model.add(Dense(200)) model.add(Activation('relu')) model.add(Dropout(0.4)) #Adding output Layer model.add(Dense(95,activation = 'softmax')) #model.summary() # ## CNN building ends here # ## Model evaluation # In[18]: #compiling the model model.compile(metrics=['accuracy'], loss='categorical_crossentropy', optimizer='adam' ) # In[19]: batch_size = 20 # ### Training # In[20]: history = model.fit(x_training,y_training, epochs=30, batch_size = 20, validation_data=(x_validation, y_vaildation), verbose=2, shuffle=True) # In[21]: # evaluate and print test accuracy score = model.evaluate(x_test, y_test, verbose=0) print('\n', 'Test accuracy:', score[1]) ## Plotting accuracy and loss import matplotlib.pyplot as plt # plot for accuracy plt.subplot(211) plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('Accuracy', fontsize='large') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend(['training', 'validation'], loc='upper left') plt.show() # plot for loss plt.subplot(212) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Loss', fontsize='large') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend(['training', 'validation'], loc='upper left') plt.show() # ## Predicting the the fruit classes # Here randomly 8 images have been printed. Among that 4 have been classified correctly # and 4 have been wrongly classified. # In[22]: y_pred = model.predict(x_test) fig = plt.figure(figsize=(16, 5)) r_count = 0 for i, idx in enumerate(np.random.choice(x_test.shape[0], size=8000, replace=False)): pred_idx = np.argmax(y_pred[idx]) true_idx = np.argmax(y_test[idx]) if pred_idx == true_idx : r_count += 1 ax = fig.add_subplot(1, 4, r_count, xticks=[], yticks=[]) ax.imshow(np.squeeze(x_test[idx])) ax.set_title("Predicted: {} \n Actual: {}".format(output_labels[pred_idx], output_labels[true_idx]), color=("green")) if r_count == 4 : break fig1 = plt.figure(figsize=(16, 5)) w_count = 0 for i, idx in enumerate(np.random.choice(x_test.shape[0], size=8000, replace=False)): pred_idx = np.argmax(y_pred[idx]) true_idx = np.argmax(y_test[idx]) if pred_idx != true_idx : w_count += 1 ax1 = fig1.add_subplot(1, 4, w_count, xticks=[], yticks=[]) ax1.imshow(np.squeeze(x_test[idx])) ax1.set_title("Predicted: {} \n Actual: {}".format(output_labels[pred_idx], output_labels[true_idx]), color=("red")) if w_count == 4 : break # In[ ]:
50ecd379d52625e8e3824acda131a82a833ad78e
KevinDeNotariis/self-replicating-virus
/03-recursive-encryption/recursively_encrypt_decryption.py
929
4.0625
4
import encrypt_decryption number_of_encryption = 1 original_filename = "" def level_of_encryption(): global number_of_encryption print("Number of encryption: ") number_of_encryption = input() def ask_for_filename(): global original_filename encrypt_decryption.ask_for_filename() original_filename = encrypt_decryption.file_name[:-3] def encrypt_loop(): encrypted_filename = original_filename + "_e1" for i in range(1, int(number_of_encryption)+1): print(i) encrypt_decryption.compute_payloads() encrypt_decryption.write_virus(encrypted_filename + ".py") encrypt_decryption.file_name = encrypted_filename + ".py" encrypted_filename = original_filename + "_e" + str(i+1) encrypt_decryption.payload.clear() encrypt_decryption.encode.clear() encrypt_decryption.previous_payload.clear() if __name__ == '__main__': level_of_encryption() ask_for_filename() encrypt_loop()
c9a12c8e0ec7c37df0309bea55df7bf7c0a6dedd
jagrvargen/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/8-simple_delete.py
206
3.71875
4
#!/usr/bin/python3 def simple_delete(my_dict, key=""): if my_dict: newDict = my_dict if key in newDict.keys(): del newDict[key] return newDict return my_dict
e3151a93661c2f8a805c94a7ddf93139f766a396
rafaelperazzo/programacao-web
/moodledata/vpl_data/359/usersdata/287/109647/submittedfiles/lecker.py
411
3.703125
4
# -*- coding: utf-8 -*- q1=int(input('digite os elementos da primeira lista: ')) q2=int(input('digite os elementos da segunda lista: ')) lista1=[] lista2=[] for i in range (0,q1): lista1.append(int(input('digite o valor'))) for i in range (0,q2): lista2.append(int(input('digite os valores da lista 2'))) print(lista1) print(lista2) def lecker(x): cont=0 for i in range(0,x):
428737aad901bf7ff52c5563e57a7387f5313f95
Mumulhy/LeetCode
/954-二倍数对数组/CanReorderDoubled.py
671
3.546875
4
# -*- coding: utf-8 -*- # LeetCode 954-二倍数对数组 """ Created on Fri Apr 1 10:30 2022 @author: _Mumu Environment: py38 """ from collections import Counter from typing import List class Solution: def canReorderDoubled(self, arr: List[int]) -> bool: cnt = Counter(arr) for num in sorted(cnt.keys(), key=lambda x: abs(x)): if cnt[num] == 0: continue if num * 2 in cnt and cnt[num * 2] >= cnt[num]: cnt[num * 2] -= cnt[num] else: return False return True if __name__ == '__main__': s = Solution() print(s.canReorderDoubled([4, -2, 2, -4]))
e93ec3e522c93b2042f5ec120f85bdedabc74569
hwangboksil/algorithm
/programmers/python_ex/level-1/divisibleArrayNums.py
1,050
3.59375
4
# 나누어 떨어지는 숫자 배열 # array의 각 element 중 divisor로 나누어 떨어지는 값을 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요. # divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하세요. def solution(arr, divisor): return sorted([i for i in arr if i % divisor == 0]) or [-1] print(solution([2, 36, 1, 3], 10)) # 1. if문을 사용하지 않고 or를 사용하면 값이 없는 경우 [-1]을 반환한다. # ========================================================= # def solution(arr, divisor): # answer = sorted([i for i in arr if i % divisor == 0]) # if sum(answer) == 0: # answer.append(-1) # return answer # 1. list comprehension을 사용해 배열 arr의 값을 하나씩 divisor로 나눠 나머지 값이 0인 경우 배수이므로 리스트에 담고 sorted() 함수로 오름차순으로 정렬하여 반환. # 2. 만약 배열 answer에 값이 없는 경우 -1을 append하여 반환한다.
cd888ce6401f27cfee3e998b2f00633efba831a7
ltadeu6/python-numeric-optimization
/pynumoptimizer/point.py
704
3.6875
4
#! /usr/bin/env python3 import numpy as np class Point(object): def __init__(self, dim): self.p = np.zeros(dim) self.v = 0 def __str__(self): return "Params: {}, ObjValue: {}".format(", ".join(["{:>10.5f}".format(p) for p in self.p]), self.v) def __eq__(self, rhs): return self.v == rhs.v def __lt__(self, rhs): return self.v < rhs.v def __le__(self, rhs): return self.v <= rhs.v def __gt__(self, rhs): return self.v > rhs.v def __ge__(self, rhs): return self.v >= rhs.v def main(): p = Point(3) print(p) if __name__ == "__main__": main()
e3d4a5a907375143172a21dd8ddf27f2e3c1d126
wffeige/algorithm015
/Week_02/350_两个数组的交集.py
523
3.671875
4
#!coding:utf-8 class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ # 存放共同元素 lst_set = list() for i in nums1: if not nums2: break if i in nums2: lst_set.append(i) # 删除nums2中下标最小的 index = nums2.index(i) nums2.pop(index) return lst_set
66a053938230fd90cc957e6ce973849ed476c96d
liyinging/leetcode
/Python/Binary_Tree_Inorder_Traversal.py
862
3.671875
4
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def inorderTraversalRecursion(self, root: TreeNode) -> List[int]: ans = [] def traverse(node): nonlocal ans if node: traverse(node.left) ans.append(node.val) traverse(node.right) traverse(root) return ans def inorderTraversalIteration(self, root: TreeNode) -> List[int]: stack, ans = [], [] while True: while root: stack.append(root) root = root.left if not stack: return ans node = stack.pop() ans.append(node.val) root = node.right
46e0585bcfab64ac677ad3576c28f2b3cc798f7e
JGuymont/ift2015
/3_tree/Tree.py
3,536
3.5625
4
from ListQueue import ListQueue #ADT Tree (Classe de base) class Tree: #inner class Position class Position: def element( self ): pass def __eq__( self, other ): pass def __ne__( self, other): return not( self == other ) # retourne la racine def root( self ): pass def _validate(self, p): if not isinstance(p, self.Position): raise TypeError('p must be proper Position type') if p._container is not self: raise ValueError('p does not belong to this container') if p._node._parent is p._node: raise ValueError('p is no longer valid') return p._node def _make_position(self, node): return self.Position(self, node) if node is not None else None # retourne le parent d'une Position def parent( self, p ): pass # retourne le nombre d'enfants d'une Position def num_children( self, p ): pass # retourne les enfants d'une Position def children( self, p ): pass # retourne le nombre de noeuds def __len__( self ): pass # demande si une Position est la racine def is_root( self, p ): return self.root() == p # demande si une Position est une feuille def is_leaf( self, p ): return self.num_children( p ) == 0 # demande si un arbre est vide def is_empty( self ): return len( self ) == 0 # retourne la profondeur d'une Position def depth( self, p ): # retourne le nombre d'ancêtres d'une Position if self.is_root( p ): return 0 else: return 1 + self.depth(self.parent()) # retourne la hauteur d'une Position avec depth (non efficace) def height1( self, p ): # retourne la profondeur maximum des feuilles sous une Position # positions n'est pas implanté et se fait en O(n) return max( self.depth( p ) for p in self.positions() if self.is_leaf( p )) # retourne la hauteur d'une Position en descendant l'arbre (efficace) def height( self, p ): # retourne la hauteur d'un sous-arbre à une Position if self.is_leaf( p ): return 0 else: return 1 + max( self.height( c ) for c in self.children( p ) ) # imprime le sous-arbre dont la racine est la Position p # utilise un parcours préfixé def preorder_print( self, p, indent = "" ): # on traite le noeud courant print( indent + str( p ) ) # et par la suite les enfants, récursivement for c in self.children( p ): self.preorder_print( c, indent + " " ) # imprime le sous-arbre dont la racine est la Position p # utilise un parcours postfixé def postorder_print( self, p ): # on traite les enfants for c in self.children( p ): self.postorder_print( c ) # et par la suite le parent print( p ) # imprime le sous-arbre dont la racine est la Position p # utilise un parcours en largeur, utilisant une File def breadth_first_print( self, p ): Q = ListQueue() # on enqueue la Position p Q.enqueue( p ) # tant qu'il y a des noeuds dans la File while not Q.is_empty(): # prendre le suivant et le traiter q = Q.dequeue() print( q ) # enqueuer les enfants du noeud traité for c in self.children( q ): Q.enqueue( c )
a64b6576f6e2bf1abe0ffd5b9f1e31ced2656050
anuragsingh7700/FITC_anurag_singh
/q1.py
62
3.546875
4
t=int(input()) for i in range(t): print(input().count('5'))
954ed1406bb3308d6bc1eafbcff31a43a0201d3f
IamJenver/mytasksPython
/asimptotic.py
336
3.78125
4
# На вход программе подается натуральное число n. Напишите программу, # которая вычисляет значение выражения n = int(input()) counter = 0 from math import log for i in range(1, n + 1): counter = counter + 1 / i counter -= log(n) print(counter)
1bf95b285168d5e332de9f082227a89833161fde
Ernestbengula/python
/kim/Payroll.py
448
3.859375
4
# create a payroll #Gross_Pay salary =float(input("Enter salary")) wa =float(input("Enter wa")) ha=float(input("Enter ha")) ta =float(input("Enter ta")) Gross_Pay =(salary+wa+ha+ta) print("Gross Pay ", Gross_Pay) #Deduction NSSF =float(input("Enter NSSF")) Tax =float(input("Enter Tax")) Deductions=(NSSF+Tax) print("Deductions: ", Deductions) #formula Net_Pay =Gross_Pay-Deduction Net_pay =Gross_Pay-Deductions print("Your net_pay",Net_pay)
9e2c874da0bfd4df1e818ee9d333f75c304b4a8d
mintheon/Practice-Algorithm
/Minseo-Kim/leetcode/5_Longest_palindromic_substring.py
769
3.671875
4
# two pointer solution O(n^2) # Middle can be any index from 0 to (n-1) in the loop. # Two pointers depart from middle point and expand to left and right. class Solution: def expand(self, left: int, right: int, s: str) -> str: result = "" while 0 <= left and right <= len(s) - 1: if s[left] != s[right]: return result result = s[left: right + 1] left -= 1 right += 1 return result def longestPalindrome(self, s: str) -> str: if len(s) == 1 or s == s[::-1]: return s result = "" for i, char in enumerate(s): result = max(result, self.expand(i, i, s), self.expand(i, i + 1, s), key=lambda x: len(x)) return result
79da11b8d911fc21de9d192f398aa2c076dc0e72
wujjpp/tensorflow-starter
/py/l2.py
2,213
3.84375
4
# 关键字参数 def person(name, age, **kw): if 'city' in kw: # 有city参数 pass if 'job' in kw: # 有job参数 pass print('name:', name, 'age:', age, 'other:', kw) person('Jane', 20) person('Jack', 20, city='Suzhou', job='Test') extra = {'city': 'Beijing', 'job': 'Engineer'} person('Jack', 24, city=extra['city'], job=extra['job']) person('Jack', 24, **extra) # 关键字参数 def person2(name, age, *, city, job): print('name:', name, 'age:', age, 'city:', city, 'job:', job) person2('Jack', 24, city='SuZhou', job='Test') # 关键字参数调用必须命名,下面代码将抛出异常 # person2('Jack', 24, 'Suzhou', 'Job') # 如果函数定义中已经有了一个可变参数(*args),后面跟着的命名关键字参数就不再需要一个特殊分隔符*了 def person3(name, age, *args, city, job): print(name, age, args, city, job) person3('Jack', 24, 'test1', 'test2', city='suzhou', job='test') # 组合使用 def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) f1(1, 2) # a = 1 b = 2 c = 0 args = () kw = {} f1(1, 2, c=3) # a = 1 b = 2 c = 3 args = () kw = {} f1(1, 2, 3, 'a', 'b') # a = 1 b = 2 c = 3 args = ('a', 'b') kw = {} f1(1, 2, 3, 'a', 'b', x=99) # a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99} f2(1, 2, d=99, ext=None) # a = 1 b = 2 c = 0 d = 99 kw = {'ext': None} # 递归函数 def fact(n): if n == 1: return 1 return n * fact(n - 1) print(fact(10)) # 尾递归 - Python不支持 def fact2(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product) print(fact(5)) # 汉诺塔: a:原始柱子, b:辅助柱子, c:目标柱子 def move(n, a, b, c): if n == 1: print(a, ' --> ', c) else: move(n - 1, a, c, b) # 把A柱上的n-1个珠子借助C, 移到B柱 move(1, a, b, c) # 把A柱上第n的珠子移到C柱 move(n - 1, b, a, c) # 把B柱上n-1个珠子借助A柱,移到C柱 move(3, 'A', 'B', 'C')
e02903be1a5a2039f3e8d5ff08d88599ff5e00c4
aimdarx/data-structures-and-algorithms
/solutions/Strings/validate_ip_address.py
3,167
4.09375
4
""" Validate IP Address Given a string IP, return "IPv4" if IP is a valid IPv4 address, "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type. A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and xi cannot contain leading zeros. For example, "192.168.1.1" and "192.168.1.0" are valid IPv4 addresses but "192.168.01.1", while "192.168.1.00" and "[email protected]" are invalid IPv4 addresses. A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8" where: 1 <= xi.length <= 4 xi is a hexadecimal string which may contain digits, lower-case English letter ('a' to 'f') and upper-case English letters ('A' to 'F'). Leading zeros are allowed in xi. For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334" and "2001:db8:85a3:0:0:8A2E:0370:7334" are valid IPv6 addresses, while "2001:0db8:85a3::8A2E:037j:7334" and "02001:0db8:85a3:0000:0000:8a2e:0370:7334" are invalid IPv6 addresses. Example 1: Input: IP = "172.16.254.1" Output: "IPv4" Explanation: This is a valid IPv4 address, return "IPv4". Example 2: Input: IP = "2001:0db8:85a3:0:0:8A2E:0370:7334" Output: "IPv6" Explanation: This is a valid IPv6 address, return "IPv6". Example 3: Input: IP = "256.256.256.256" Output: "Neither" Explanation: This is neither a IPv4 address nor a IPv6 address. Example 4: Input: IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:" Output: "Neither" Example 5: Input: IP = "1e1.4.5.6" Output: "Neither" Constraints: IP consists only of English letters, digits and the characters '.' and ':'. https://leetcode.com/problems/validate-ip-address/solution """ # O(n) time | O(1) space class Solution: def validIPAddress(self, IP: str): if ":" in IP: return self.validateIPv6(IP) return self.validateIPv4(IP) def validateIPv4(self, IP): if len(IP) > 15: return "Neither" if IP.count(".") != 3: return "Neither" for section in IP.split("."): if not section.isnumeric(): return "Neither" num = int(section) # cannot contain leading zeros if not len(section) == len(str(num)): return "Neither" # 0 <= xi <= 255 if num < 0 or num > 255: return "Neither" return "IPv4" def validateIPv6(self, IP): if len(IP) > 39: return "Neither" if IP.count(":") != 7: return "Neither" for section in IP.split(":"): if not section.isalnum(): return "Neither" # 1 <= xi.length <= 4 if len(section) < 1 or len(section) > 4: return "Neither" # digits, lower-case English letter ('a' to 'f') and upper-case ('A' to 'F'). for char in section: is_number = char.isnumeric() is_corr_char = ord(char.lower()) >= ord( "a") and ord(char.lower()) <= ord("f") if not (is_number or is_corr_char): return "Neither" return "IPv6"
748ce036df96aaac0e975c76a4b042799e92c1a0
princess0307/PythonExercises
/ex36.py
158
3.671875
4
class Add(object): def __init__(self,name,age): self.name=name self.age=age print self.name obj=Add("chanchal",20)
5e36933b188437cb16cfe741886e9fcc97d8abdd
fjaschneider/Course_Python
/Exercise/ex044.py
807
3.671875
4
print('{:=^50}'.format(' Schneider Store ')) p = float(input('Preço das compras: R$ ')) print('''Formas de pagamento: [ 1 ] à vista dinheiro/ cheque [ 2 ] à vista no cartão [ 3 ] 2x no cartão [ 4 ] 3x ou mais no cartão''') op = int(input('Qual é a opção? ')) if op == 1: print('O valor das compras ficou R$ {:.2f} com o desconto de 10%!' .format(p - (p*0.1))) elif op == 2: print('O valor das compras ficou R$ {:.2f} com o desconto de 5%!' .format(p - (p * 0.05))) elif op == 3: print('O valor das compras em duas vezes ficou de R$ {:.2f}!' .format(p / 2)) elif op == 4: par = int(input('Em quantas vezes você quer parcelar? ')) print('O valor de sua parcela será de R$ {:.2f}!'.format((p + (p * 0.2))/par)) else: print('Opção inválida!')
be0f88fea248bb9d8954b2e00396bbf164a94cac
fadymedhat/TMIXT
/HOCRParser/autocorrect/word.py
3,092
3.53125
4
# Python 3 Spelling Corrector # # Copyright 2014 Jonas McCallum. # Updated for Python 3, based on Peter Norvig's # 2007 version: http://norvig.com/spell-correct.html # # Open source, MIT license # http://www.opensource.org/licenses/mit-license.php """ Word based methods and functions Author: Jonas McCallum https://github.com/foobarmus/autocorrect """ from autocorrect.utils import concat from autocorrect.nlp_parser import NLP_WORDS from autocorrect.word_lists import LOWERCASE, MIXED_CASE from autocorrect.word_lists import LOWERED, CASE_MAPPED ALPHABET = 'abcdefghijklmnopqrstuvwxyz' KNOWN_WORDS = LOWERCASE | LOWERED | NLP_WORDS class Word(object): """container for word-based methods""" def __init__(self, word): """ Generate slices to assist with typo definitions. 'the' => (('', 'the'), ('t', 'he'), ('th', 'e'), ('the', '')) """ word_ = word.lower() slice_range = range(len(word_) + 1) self.slices = tuple((word_[:i], word_[i:]) for i in slice_range) self.word = word def _deletes(self): """th""" return {concat(a, b[1:]) for a, b in self.slices[:-1]} def _transposes(self): """teh""" return {concat(a, reversed(b[:2]), b[2:]) for a, b in self.slices[:-2]} def _replaces(self): """tge""" return {concat(a, c, b[1:]) for a, b in self.slices[:-1] for c in ALPHABET} def _inserts(self): """thwe""" return {concat(a, c, b) for a, b in self.slices for c in ALPHABET} def typos(self): """letter combinations one typo away from word""" return (self._deletes() | self._transposes() | self._replaces() | self._inserts()) def double_typos(self): """letter combinations two typos away from word""" return {e2 for e1 in self.typos() for e2 in Word(e1).typos()} def common(words): """{'the', 'teh'} => {'the'}""" return set(words) & NLP_WORDS def exact(words): """{'Snog', 'snog', 'Snoddy'} => {'Snoddy'}""" return set(words) & MIXED_CASE def known(words): """{'Gazpacho', 'gazzpacho'} => {'gazpacho'}""" return {w.lower() for w in words} & KNOWN_WORDS def known_as_lower(words): """{'Natasha', 'Bob'} => {'bob'}""" return {w.lower() for w in words} & LOWERCASE def get_case(word, correction): """ Best guess of intended case. manchester => manchester chilton => Chilton AAvTech => AAvTech THe => The imho => IMHO """ if word.istitle(): return correction.title() if word.isupper(): return correction.upper() if correction == word and not word.islower(): return word if len(word) > 2 and word[:2].isupper(): return correction.title() if not known_as_lower([correction]): #expensive try: return CASE_MAPPED[correction] except KeyError: pass return correction
94ce4dfb752d2056cab38cfc2f58f6bac71f29bb
gordol/CrossHair
/crosshair/examples/PEP316/bugs_detected/hash_consistent_with_equals.py
769
3.515625
4
class HasConsistentHash: """ A mixin to enforce that classes have hash methods that are consistent with their equality checks. """ def __eq__(self, other: object) -> bool: """ post: implies(__return__, hash(self) == hash(other)) """ raise NotImplementedError class Apples(HasConsistentHash): """ Uses HasConsistentHash to discover that the __eq__ method is missing a test for the `count` attribute. """ count: int kind: str def __hash__(self): return self.count + hash(self.kind) def __repr__(self): return f"Apples({self.count!r}, {self.kind!r})" def __eq__(self, other: object) -> bool: return isinstance(other, Apples) and self.kind == other.kind
b72a990b4a437c771b1993855d180178a1276a40
iankatzman/CS112-Spring2012
/hw08/math_funcs.py
404
3.984375
4
#!/usr/bin/env python import math def ptop((x1, y1), (x2, y2)): distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return distance x1 = int(raw_input("enter a number for x1: ")) y1 = int(raw_input("enter a number for y1: ")) x2 = int(raw_input("enter a number for x2: ")) y2 = int(raw_input("enter a number for y2: ")) print "the distance between those points is: ",ptop((x1, y1), (x2, y2))
5c15a640c5f20e1035e7927112631a69ae88c433
xaowoodenfish/Chapter2
/Chapter2_eig8.py
417
3.921875
4
# Time Oct.20 2015 # A simple input to judge whether prime number from math import * a = raw_input('Input an integer:') while True: if not a.isdigit(): print 'Error: try again.' a = raw_input('Input an integer:') else: print 'The integer is:%s'%a break b = int(a) N = int(sqrt(b)) i = 2 while i <= N: if b%i ==0: print 'The input can be divided by %d'%i i+=1
0083fd2066590e429270f2980662573d0c13a620
sungillee90/python-exercise
/FromJClass/MazeProject.py
1,630
3.921875
4
# Backtracking maze = [[".", ".", ".", "."], [".", "X", "X", "X"], [".", ".", ".", "X"], ["X", "X", ".", "."]] def print_maze(maze): for row in maze: row_print = "" for value in row: row_print += value + " " print(row_print) print(maze) print_maze(maze) def solve_maze(maze): if len(maze) < 1: return None if len(maze[0]) < 1: return None return print(solve_maze_helper(maze, [], 0, 0)) #solve_maze_helper(maze, [], 0, 0) def solve_maze_helper(maze, sol, pos_row, pos_col): # Get size of the maze num_row = len(maze) num_col = len(maze[0]) # Base Cases # Robot is already home # list starts 0, num of row 1 2 3 4 if pos_row == num_row - 1 and pos_col == num_col - 1: return sol # Out of bounds if pos_row >= num_row or pos_col >= num_col: return None # Is on an obstacle (X) if maze[pos_row][pos_col] == "X": return None # Recursive Case # Try going Right sol.append("r") sol_going_right = solve_maze_helper(maze, sol, pos_row, pos_col + 1) if sol_going_right is not None: return sol_going_right # Pretend going Right is not answer, BACKTRACK, trying going down sol.pop() sol.append("d") sol_going_down = solve_maze_helper(maze, sol, pos_row + 1, pos_col) if sol_going_down is not None: return sol_going_down # No soln, impossible, BACKTRACKING sol.pop() return None print(solve_maze_helper(maze, [], 0, 0)) print(solve_maze_helper(maze, [], 2, 0)) print(solve_maze(maza))
1e7e8fd1718883a228730b96cbdcaa664735d188
peterlaraia/DailyProgrammerChallenges
/e282/Instruction.py
291
3.609375
4
class Instruction: def __init__(self, base, value): self.base = base self.val = value def getBase(self): return self.base def getVal(self): return self.val def __str__(self): return "base: {}, value: {}".format(self.base, self.val)
33ef4ce59f3e15963c924b68fbc4d1d082bea34d
Austin-Bell/PCC-Exercises
/Chapter_2/famous_quotes.py
379
3.859375
4
#find a quote from a famous person. Print the quote adn the name of its author. famous_quote = ' once said, "A person who never made a mistake never tried anything new."' #print(famous_quote) #repeat exericies above, but this time store the famous person's name iin a variable called famous_person. famous_person = "Albert Einsten" message = famous_person + famous_quote print(message)
5c1a906241a975a7e113ad7d6ae73b679ad194cf
fenglihanxiao/Python
/Module01_CZ/day9_reference/04-代码/day9/151_引用(数值、布尔、字符串).py
440
3.78125
4
""" 演示引用(数值型、布尔型、字符串型) """ # a = 1 # b = 1 # print(id(1)) # print(id(a)) # print(id(b)) # print((id(2))) # a = 2 # print("-------") # print(id(a)) # flag1 = True # flag2 = False # print(id(flag1)) # print(id(flag2)) # flag1 = False # print("-------------") # print(id(flag1)) # print(id(flag2)) str1 = "a" str2 = "a" print(id(str1)) print(id(str2)) str1 = "b" print(id(str1)) print(id(str2))
2c87771069c9fe8c8c74793ba31fd14fba114a1f
sy850811/Python_DSA
/Kth_largest_element.py
461
3.671875
4
import heapq def kthLargest(lst, k): ###################### #PLEASE ADD CODE HERE# ###################### heap=lst[:k] heapq.heapify(heap) n1=len(lst) for i in range(k,n1): if lst[i]>heap[0]: heapq.heappop(heap) heapq.heappush(heap,lst[i]) return heap[0] # Main n=int(input()) lst=list(int(i) for i in input().strip().split(' ')) k=int(input()) ans=kthLargest(lst, k) print(ans)
ca96d354feb59f7757802609165696583e4c7ab2
abdularifb/Pythonprograms
/SimpleInterest.py
180
3.859375
4
P = input("Enter the Principle Amount:") R = input("Rate of Interest:") N = input("No Of Years:") si = float(P * N * R)/100 print "Simple Interest is {}".format(si)
524c5da8f7997bd7c67b19a84a105a712991d083
ikhvastun/deepLearning
/randomizer/shuffle.py
658
4.03125
4
""" Tools for shuffling arrays """ import numpy as np def randomIndices( length ): random_indices = np.arange( length ) np.random.shuffle( random_indices ) return random_indices #shuffle several arrays consistencly def shuffleSimulataneously( *arrays ): #check that all input arrays have the same length array_size = len( arrays[0] ) if not( all( len(array) == array_size for array in arrays ) ): raise ValueError('All arrays must have the same length to be simultaneously shuffled.') #shuffle arrays random_indices = randomIndices( array_size ) for array in arrays: array = array[ random_indices ]
e4e1e1ec13126d4766104aa8d40825bcaf1abc5b
CharlyWelch/data-structures
/dll.py
3,252
4.15625
4
class Node(object): """ Class object for instantiating nodes to add to the doubly-linked list """ _value = None _next = None _prev = None def __init__(self, value): self._value = value def value(self): return self._value def next(self, next): self._next = next def prev(self, prev): self._prev = prev class DoubleLinkedList(object): """ class object for creating a linked-list data structure """ head = None tail = None curr = None size = 0 def __init__(self): pass def append(self, node): """ add a node to end of list """ if self.head is None: self.head = node self.tail = node else: self.tail._next = node self.tail = node self.size += 1 def push(self, node): """ add to front - reassign head value to current node """ if self.head is None: self.head = node self.tail = node else: self.head._prev = node node._next = self.head self.head = node self.size += 1 def pop(self): """ remove and return head value - reassign head to current head.next""" if self.head is None: return "No value to return" elif self.head._next == None: return self.head else: node = self.head self.head = self.head._next self.size -= 1 return node def shift(self): """ remove and return tail value - reassign tail to prev""" if self.tail is None: return "No value to return" elif self.tail._prev == None: return self.tail else: node = self.tail self.tail = self.tail._prev self.size -= 1 return node def remove(self, value): """ search by value, remove that node - reassign bookending head and next """ _prev = None curr = self.head try: while curr is not None: if curr._value == value: if _prev is not None: _prev._next = curr._next if curr._next is not None: curr._next._prev = _prev if self.head == curr: self.head = curr._next if self.tail == curr: self.tail = curr._prev break else: _prev = curr curr = curr._next except (RuntimeError): return "Node does not exist!" def __len__(self): """ return the length of the list """ return self.size """ Andy's comments: 1. You use the _ underscore naming in Node as to mean private, but in some places in DoubleLinkList you directly access the attribute. 2. All classes and methods should have a docstring 3. pop() should return None when empty, not an object which is a string => return "No value to return" 4. Pop() has bug fir case of a single node in list 5. Shift() has similar problems as pop() I see you have lots of diverse tests :) """
8a50f197003450d2661257d387cd15ed25a3679f
ParkChangJin-coder/pythonProject
/random_tutorial.py
1,311
3.78125
4
import random #randint : 시작 숫자부터 끝 숫자 사이에 임의 숫자 print(random.randint(1,100)) #random : 0 ~ 1 사이의 임의 플롯 print("random.random() : ", random.random()) #uniform(시작 소숫점, 끝 소숫점) : 시작 소숫점 ~ 끝 소숫점 사이의 임의 플롯 print("random.uniform() : ", random.uniform(0.1,0.02)) #randrange(정수) : 0부터 정수 미만의 수 사이에서 임의수 #randrange(시작숫자, 끝숫자) print("random.randrange() : ", random.randrange(10)) print("random.randrange() : ", random.randrange(5,8)) #randrange(시작, 끝, 숫자간격) : 시작 부터 끝 미만 사이에서 숫자 간격만큼 #떨어진 수 들 중 임의 수를 뽑아준다 print("random.randrange() : ", random.randrange(1,101,2)) #1부터 2씩 증가한 수 중에 랜덤 #choice(list) : list, tuple, dictionary, set 등등 데이터 구조에서 랜덤으로 하나 가져옴 list = [1,2,3,4,5,6,7,8,9,10] print("choice() : ", random.choice(list)) #sample : list, tuple, dictionary, set 등등 데이터 구조에서 랜덤으로 특정 개수만큼 들고옴 print("sample() : ", random.sample(list, 3)) #shuffle : list, tuple, dictionary, set 등등 데이터 구조에서 랜덤으로 섞음 random.shuffle(list) print("shuffle() : ", list)
dc9be2de5f8367600809aa2ce8ba8608cf1119c7
yunjung-lee/class_python_data
/test1.py
225
3.6875
4
###CSV 안에 comma를 포함한 문자열이 있을 때 문자열은 상관없이 분리하는 방법 import csv a='1234,John Smith,100-0014,"$1,350.00",3/4/14' for a in csv.reader([a],skipinitialspace=True): print(a)
a4e3fb8f436a801576f0a4d15c0b5ebd6d733606
DeepLearningSky/qandabot
/utils/generate_txt_from_csv.py
406
3.765625
4
import sys def generate_txt_from_csv(filename, q = True, a = False): for l in open(filename): sentences = l.strip().split('\t') if(len(sentences) >= 3): question = sentences[1] answer = sentences[2] if q and a: print question print answer elif a: print answer else: print question if __name__ == "__main__": generate_txt_from_csv(sys.argv[1], q = True, a=False)
25227aed6439091c15bb1a5fc6babd6fd29df103
abhijitdey/coding-practice
/trees_graphs/trie.py
1,147
4.03125
4
class Node: def __init__(self): # Each node can have a max of 26 children (if we consider only lower-case chars) # print('Initializing Node') self.children = [None]*26 self.is_word = False class Trie: def __init__(self): # print('Initializing Trie') self.root = Node() def _char_to_index(self, char): # A helper function to return the index of a char (0-25) return ord(char) - ord('a') def insert(self, word): # Insert new word to the Trie current = self.root for char in word: index = self._char_to_index(char) if current.children[index] is None: current.children[index] = Node() current = current.children[index] current.is_word = True def search(self, word): # Search if a word or a substring is present in the Trie current = self.root for char in word: index = self._char_to_index(char) if current.children[index] is None: return False current = current.children[index] return True
11c3aba4ec50bd58f01459251036a325bce5dddf
MarineChap/Machine_Learning
/Classification/Section 15 - K-Nearest Neighbors (K-NN)/K_NN_algorithme.py
2,745
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Part 3 : K-Nearest Neighbors in following the course "Machine learning A-Z" at Udemy The dataset can be found here https://www.superdatascience.com/machine-learning/ Objective : Predict the likelihood for a person to buy an SUV in function of his age and his estimated salary Step 1 : Choose K nearest neighbors (usually 5) Step 2 : Take the k-NN of the new data point, according to the Euclidian distance Step 3 : Count the number of NN in each category Conclusion : The new data point is in the category the most represented in his neighborhood. Created on Sun Feb 25 18:05:12 2018 @author: marinechap """ # Import libraries import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import precision_score, confusion_matrix import matplotlib.pyplot as plt import Display_graph as dg # Parameters name_file = 'Social_Network_Ads.csv' nb_indep_var = 4 # Import dataset dataset = pd.read_csv(name_file) indep_var = dataset.iloc[:,2:-1].values dep_var = dataset.iloc[:,nb_indep_var].values # Split the dataset indep_train, indep_test, dep_train, dep_test = train_test_split(indep_var, dep_var, test_size = 0.25, random_state = 0) # Feature scalling stdScal = StandardScaler() indep_train = stdScal.fit_transform(indep_train) indep_test = stdScal.transform(indep_test) """ K-NN Algorithm n_neighbors = 5 means it is the number 5 of neighbors which is chosen p = 2, metric = 'minkowski' means we are using the Euclidian distance. if p =1, we are using the Manhattan distance """ classifier = KNeighborsClassifier(n_neighbors = 5, p = 2, metric = 'minkowski') classifier.fit(indep_train, dep_train) dep_pred = classifier.predict(indep_test) # Print the confusion matrix and the precision score print(confusion_matrix(dep_test, dep_pred)) precision = precision_score (dep_test, dep_pred) # Visualising the Training set results plt.subplot(1,2,1) plt = dg.display_classifier(plt, classifier, indep_train, dep_train) plt.title('Training set') plt.xlabel('Age') plt.ylabel('Estimated Salary') # Visualising the Test set results plt.subplot(1,2,2) plt = dg.display_classifier(plt, classifier, indep_test, dep_test) plt.title('Test set') plt.xlabel('Age \n precision = %s'%(precision)) plt.suptitle('K_NN algorithm', size = 'x-large') plt.savefig('K_NN_algo.pdf', bbox_inches='tight') plt.show()
8514278a72cd0ae0b04dd2013be27ce4275a39d1
jadhaddad01/SudokuSolver
/solver.py
3,694
3.859375
4
## Author: Jad Haddad import puzzleAPI import time """ #manually entered puzzle puzzle = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7] ] """ # Main variables easy = 4 medium = 5 hard = 6 # printPuzzle prints a 2D array puzzle in a neat format def printPuzzle(puz): for i in range(len(puz)): # seperating boxes horizontally if(i % 3 == 0 and i != 0): print((len(puz[i]) * 2 + 3) * "-") for j in range(len(puz[i])): # seperating boxes vertically if((j % 3 == 0) and j != 0): print("| " + str(puz[i][j]), end=" ") elif(j != (len(puz[i]) - 1)): print(puz[i][j], end=" ") # last number in row else: print(puz[i][j]) # Find next empty block def emptyBlock(puz): for i in range(len(puz)): # return first empty block we find for j in range(len(puz[i])): if(puz[i][j] == 0): return (i, j) # no blocks are empty return None # Check if number in certain index is valid as to respect the rules of sudoku # No same num in same row Or column Or box def numValid(puz, num, index): # Check row for duplicate for i in range(len(puz[0])): if(puz[index[0]][i] == num and index[1] != i): return False # Check column for duplicate for j in range(len(puz)): if(puz[j][index[1]] == num and index[0] != j): return False # Check box for duplicate for k in range((index[0] // 3) * 3, (index[1] // 3) * 3 + 3): for l in range((index[1] // 3) * 3, (index[0] // 3) * 3 + 3): if(puz[k][l] == num and (k, l) != index): return False # Number is valid return True # Solve puzzle def solvePuzzle(puz): # Base Case finding the next empty block, and if no empty block is found we return true nextEmpty = emptyBlock(puz) if not nextEmpty: # puzzle loved return True else: # we start with the next empty block row, column = nextEmpty # try nums 1 to 9 and place first valid num for num in range(1, 10): # Add numb in block if valid if(numValid(puz, num, (row, column))): puz[row][column] = num # recursive call to solve this block if(solvePuzzle(puz)): return True # we reset the block to 0 if no num worked puz[row][column] = 0 # if this block finished counting to 9 and nothing is valid # we reset to 0 and the previous block continues to 9 return False (puzzle, solvedPuzzle) = puzzleAPI.getPuzzle(hard) print("\nAPI Generated Puzzle:") printPuzzle(puzzle) print("\nAPI Solved Puzzle:") printPuzzle(solvedPuzzle) print("\nAlgorithmicaly Solved Puzzle:") # start time start_time = time.time() solvePuzzle(puzzle) print("--- solved in %s seconds ---" % (time.time() - start_time)) printPuzzle(puzzle) (puzzle1, solvedPuzzle1) = puzzleAPI.getPuzzle(hard) print("\nAPI Generated Puzzle:") printPuzzle(puzzle1) print("\nAPI Solved Puzzle:") printPuzzle(solvedPuzzle1) print("\nAlgorithmicaly Solved Puzzle:") # start time start_time1 = time.time() solvePuzzle(puzzle1) print("--- solved in %s seconds ---" % (time.time() - start_time1)) printPuzzle(puzzle1)
22ee0a4db1572243ab763a560ce389120f3aa7f7
routdh2/100daysofcodingchallenge
/Day5/find_distance_value.py
428
3.65625
4
#Problem Statement: https://leetcode.com/problems/find-the-distance-value-between-two-arrays class Solution: def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: count=0 for i in arr1: flag=False for j in arr2: if abs(i-j)<=d: flag=True if flag==False: count+=1 return count
35acc68784cc7c656abbd7315b4d14b3d1ffdb27
kadirkoyici/pythonkursu
/karalamalar_src_idi/sayial.py
391
3.5625
4
# -*- coding: utf-8 -*- sayi = input("Bir Sayi Giriniz:") if sayi==5: print "Girdiginiz sayi 5 tir" else: print "girdiginiz ssayi 5 degildir %s dir " %sayi kelime = raw_input("Bir kelime giriniz") if kelime=="kadir": print "girdiginiz kelime kadirdir" print "dogru kelime bu" else: print "girdginiz kelime kadir degillldir %s dir" %kelime print "yanlis kelime bu"
f2c748bc52b971e1d29e377a87985b2082864338
b01lers/b01lers-library
/2019tuctf/Crypto/Something in Common [405 pts]/solve.py
1,700
3.5625
4
''' Explanation The given information shows two ciphertext, two public keys, and a single common modulus. With this information we can apply bezout's identity using the extended euclidean algorithm. Which states that there are two coefficients, which we can call a and b, such that a * e1 + b * e2 = gcd(e1,e2). We also know that the gcd of our public keys, 13 and 15, is 1 since they are coprime. ''' from fractions import gcd n = 5196832088920565976847626600109930685983685377698793940303688567224093844213838345196177721067370218315332090523532228920532139397652718602647376176214689 e1 = 15 e2 = 13 c1 = 2042084937526293083328581576825435106672034183860987592520636048680382212041801675344422421233222921527377650749831658168085014081281116990629250092000069 c2 = 199621218068987060560259773620211396108271911964032609729865342591708524675430090445150449567825472793342358513366241310112450278540477486174011171344408 def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise ValueError('Modular inverse does not exist.') else: return x % m def attack(c1, c2, e1, e2, N): if gcd(e1, e2) != 1: raise ValueError("Exponents e1 and e2 must be coprime") s1 = modinv(e1,e2) s2 = (gcd(e1,e2) - e1 * s1) / e2 temp = modinv(c2, N) m1 = pow(c1,s1,N) m2 = pow(temp,-s2,N) return (m1 * m2) % N def main(): try: message = attack(c1, c2, e1, e2, n) print '\nPlaintext message:\n%s' % format(message, 'x').decode('hex') except Exception as e: print e.message main()
aa47a251564828ce69662bd835cbc68c32cbcfc3
nicholasrokosz/python-crash-course
/Ch. 6/favorite_places.py
284
3.734375
4
favorite_places = { 'nick': ['tucson', 'milwaukee'], 'nicole': ['bend', 'sedona'], 'al': ['madrid', 'barcelona', 'rome'], } for person, places in favorite_places.items(): print(f"{person.title()}'s favorite places are:") for place in places: print(place.title()) print("\n")
c265190d0c1775a52dc143c8f4fa6bde09ce5784
maCucyrt07/Birthday-quiz
/birthday.py
1,935
4.75
5
""" birthday.py Author: MaCucyrt07 Credit: Ella, Kyle Assignment: Birthday Quiz Your program will ask the user the following questions, in this order: 1. Their name. 2. The name of the month they were born in (e.g. "September"). 3. The year they were born in (e.g. "1962"). 4. The day they were born on (e.g. "11"). If the user's birthday fell on October 31, then respond with: You were born on Halloween! If the user's birthday fell on today's date, then respond with: Happy birthday! Otherwise respond with a statement like this: Peter, you are a winter baby of the nineties. Example Session Hello, what is your name? Eric Hi Eric, what was the name of the month you were born in? September And what year were you born in, Eric? 1972 And the day? 11 Eric, you are a fall baby of the stone age. """ from datetime import datetime from calendar import month_name todaymonth = datetime.today().month todaydate = datetime.today().day month = month_name[todaymonth] name = input("Hello, what is your name? ") print("Hi",name+", what was the name of the month you were born in?") b = birthmonth = input() print("And what year were you born in,",name+"?") a = birthyear = float(input()) print("And the day?") c = birthday = float(input()) if b == 'October' and c == 31: print ("You were born on Halloween!") elif b == month and c == todaydate: print ("Happy birthday!") else: if b in ['March','April','May']: season = 'spring' elif b in ['December','January','February']: season = 'winter' elif b in ['June', 'July', 'August']: season = 'summer' elif b in ['September','October','November']: season = 'fall' if a<=1979: age = 'Stone Age.' elif a<=1989: age = 'eighties.' elif a<=1999: age = 'nineties.' elif a<=2020: age = 'two thousands.' print (name+', you are a',season,'baby of the',age)
efed965bb69f8a371ef7da6960aa9bf7f870b2c7
emrahselli/python_challenge
/PyBank/main_csv.py
1,629
3.515625
4
import os import csv csvpath = os.path.join('Resources', 'budget_data.csv') with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') next(csvreader, None) row = next(csvreader, None) max_m = row[0] min_m = row[0] profit = float(row[1]) row_counter = 1 total = float(row[1]) change_total = 0 max_p = 0 min_p = 0 prev_profit = profit for row in csvreader: row_counter = row_counter + 1 total = total + float(row[1]) profit = float(row[1]) change = profit - prev_profit change_total = change_total + change if change > max_p: max_m = row[0] max_p = change if change < min_p: min_m = row[0] min_p = change prev_profit = profit average = round(change_total / (row_counter - 1)) print("Financial Analysis") print("-------------------------") print(f'Total months: {row_counter}') print(f'Total: {total}') print(f'Average Change: $-{average}') print(f'Greatest increase in profits: {max_m} (${max_p})') print(f'Greatest increase in profits: {min_m} (${min_p})') file = open("pybank_output.txt", "w") file.write("Financial Analysis \n-------------------------\n") file.write(f'Total months: {row_counter}\n') file.write(f'Total: {total}\n') file.write(f'Average Change: $-{average}\n') file.write(f'Greatest increase in profit: {max_m} ({max_p})\n') file.write(f'Greatest decrease in profit: {min_m} ({min_p})\n') file.close()
f039b8695207daa2fea92fdd2528f268d5420475
BazzalSeed/LeetCoding
/counting_bits/counting_bits.py
702
3.6875
4
""" Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Atacched pic to see the core concept """ class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ special = 1 steps = 1 res = [] res.append(0) for i in xrange(1, num + 1): if(i == special): res.append(1) special = special << 1 steps = 1 else: res.append(res[steps] + 1) steps += 1 return res
32ed9e077843e51d9fc514d6cc7b13af66226566
rm-hull/luma.examples
/examples/game_of_life.py
2,319
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2023 Richard Hull and contributors # See LICENSE.rst for details. # PYTHON_ARGCOMPLETE_OK """ Conway's game of life. Adapted from: http://codereview.stackexchange.com/a/108121 """ import time from random import randint from demo_opts import get_device from luma.core.render import canvas def neighbors(cell): x, y = cell yield x - 1, y - 1 yield x, y - 1 yield x + 1, y - 1 yield x - 1, y yield x + 1, y yield x - 1, y + 1 yield x, y + 1 yield x + 1, y + 1 def iterate(board): new_board = set([]) candidates = board.union(set(n for cell in board for n in neighbors(cell))) for cell in candidates: count = sum((n in board) for n in neighbors(cell)) if count == 3 or (count == 2 and cell in board): new_board.add(cell) return new_board def main(): text = "Game of Life" scale = 3 cols = device.width // scale rows = device.height // scale initial_population = int(cols * rows * 0.33) while True: board = set((randint(0, cols), randint(0, rows)) for _ in range(initial_population)) for i in range(500): with canvas(device, dither=True) as draw: for x, y in board: left = x * scale top = y * scale if scale == 1: draw.point((left, top), fill="white") else: right = left + scale bottom = top + scale draw.rectangle((left, top, right, bottom), fill="white", outline="black") if i == 0: left, top, right, bottom = draw.textbbox((0, 0), text) w, h = right - left, bottom - top left = (device.width - w) // 2 top = (device.height - h) // 2 draw.rectangle((left - 1, top, left + w + 1, top + h), fill="black", outline="white") draw.text((left + 1, top), text=text, fill="white") if i == 0: time.sleep(3) board = iterate(board) if __name__ == "__main__": try: device = get_device() main() except KeyboardInterrupt: pass
eaf31902187cdd442bb3619fce76f1186917a004
FionaT/Digital-Image-Processing_Proj
/proj_2/0201/proj_02-01-a.py
1,969
3.890625
4
# Write a halftoning computer program for printing gray-scale images # based on the dot patterns just discussed. Your program must be able # to scale the size of an input image so that it does not exceed the # area available in a sheet of size 8.5 x 11 inches (21.6 x 27.9 cm). # Your program must also scale the gray levels of the input image to # span the full halftoning range. from PIL import Image, ImageDraw # open an image and get its information im = Image.open('Fig0222(b)(cameraman).tif') data = im.load() width, height = im.size # new two blank images for halftoning halftoningImage = Image.new('L',(width * 3, height * 3), 'white') # the color array represnets nine patterns # corresponding to the question description color = [[] * 9 ] * 10 color[0] = [0,0,0,0,0,0,0,0,0] color[1] = [0,255,0,0,0,0,0,0,0] color[2] = [0,255,0,0,0,0,0,0,255] color[3] = [255,255,0,0,0,0,0,0,255] color[4] = [255,255,0,0,0,0,255,0,255] color[5] = [255,255,255,0,0,0,255,0,255] color[6] = [255,255,255,0,0,255,255,0,255] color[7] = [255,255,255,0,0,255,255,255,255] color[8] = [255,255,255,255,0,255,255,255,255] color[9] = [255,255,255,255,255,255,255,255,255] # divide the grey level interval into 9 parts # which suit for the nine replacement patterns d = 255/9 # draw the answer image draw = ImageDraw.Draw(halftoningImage) # for each pixel count its correspond pattern and # draw the pattern in the image with new size for i in range(width): for j in range(height): p = data[i, j]/d c = color[p] draw.point((i * 3, j * 3), c[0]) draw.point((i * 3 + 1, j * 3), c[1]) draw.point((i * 3 + 2, j * 3), c[2]) draw.point((i * 3, j * 3 + 1), c[3]) draw.point((i * 3 + 1, j * 3 + 1), c[4]) draw.point((i * 3 + 2, j * 3 + 1), c[5]) draw.point((i * 3, j * 3 + 2), c[6]) draw.point((i * 3 + 1, j * 3 + 2), c[7]) draw.point((i * 3 + 2, j * 3 + 2), c[8]) #save the output files halftoningImage.save('halftoningImage_a.bmp', format='BMP')
dce6b989352a096fbd97ad55adc7b17b07f93047
MartinMa28/Algorithms_review
/backtracking/knight_tour.py
1,768
3.75
4
class Solution(): def __init__(self, n): self.size = n self.board = [[-1 for _ in range(self.size)] for _ in range(self.size)] self.directions = ((2, 1), (-2, 1), (2, -1), (-2, -1), (1, 2), (-1, 2), (1, -2), (-1, -2)) def _is_safe(self, row, col): if row >= 0 and \ row < self.size and \ col >= 0 and \ col < self.size and \ self.board[row][col] == -1: return True else: return False def _print_solution(self): for i in range(self.size): for j in range(self.size): print(str(self.board[i][j]).zfill(2), end=' ') print() def solve_knight_tour(self) -> None: # start from (0, 0) self.board[0][0] = 0 # step counter for knight's position pos = 1 if not self._recursive_util(0, 0, self.directions, pos): print('Solution does not exist!') else: self._print_solution() def _recursive_util(self, row, col, directions, pos) -> bool: if pos == self.size ** 2: return True for row_offset, col_offset in directions: next_row = row + row_offset next_col = col + col_offset if self._is_safe(next_row, next_col): self.board[next_row][next_col] = pos if self._recursive_util(next_row, next_col, directions, pos + 1): return True else: # backtracking self.board[next_row][next_col] = -1 return False if __name__ == '__main__': solu = Solution(5) solu.solve_knight_tour()
534b93d7e10626cb00a52c95a75686569f0673f3
mario21ic/abstract-data-structures
/python/tree/Arbol.py
2,805
3.796875
4
class Node: def __init__(self, label, parent=None): self.label = label self.parent = parent def __str__(self): return self.label def __repr__(self): return self.label def have_parent(self): return self.parent == None class Tree: def __init__(self): self.root = None self.nodes = [] #def __str__(self): # return self.root.__str__() def position_node(self, label): #print("nodes:", self.nodes) position = 0 for node in self.nodes: #print("node:", node.label) if node.label == label: return position position += 1 return position def exists_node(self, label): #print("nodes:", self.nodes) for node in self.nodes: #print("node:", node.label) if node.label == label: return True return False def get_children(self, parent): children = [] for node in self.nodes: #print("node,parent:", node.parent) if node.parent == parent: children.append(node) return children def get_node(self, label): node_return = None for node in self.nodes: #print("node.label:", node.label) if node.label == label: node_return = node return node_return def get_full_path(self, label): full_path = [] node_obj = self.get_node(label) full_path.append(node_obj.label) #print("node_obj.parent:", node_obj.parent) is_done = False while is_done == False: for node in self.nodes: #print("node.label:", node.label) #print("node.parent:", node.parent) #print("node_obj.parent:", node_obj.parent) if node.label == node_obj.parent: full_path.append(node.label) node_obj = self.get_node(node.label) #print("new node_obj:", node_obj) if node.label == self.root: is_done = True full_path.reverse() return "".join(full_path) def insert(self, label, parent=None): node_new = Node(label, parent) if parent == None and self.root is None: self.root = label self.nodes.append(node_new) return True else: #print(self.exists_node(parent)) if self.exists_node(parent): self.nodes.append(node_new) return True print("No es posible agregar %s en %s" % (label, parent)) return False def move_node(self, label, new_parent): if self.exists_node(label): node = self.get_node(label) print("node.parent:", node.parent) node.parent = new_parent return True return False def delete(self, label): #print(self.exists_node(parent)) if self.exists_node(label): del self.nodes[self.position_node(label)] return True return False def empty(self): if len(self.nodes) == 0: return True return False
4206cb3d60e1bf4623268ead41d19d4a5080ab5a
hyuueee/Python-Crash-Course
/aliens.py
957
3.859375
4
#字典列表 alien_0={'color':'green','points':5} alien_1={'color':'yellow','points':10} alien_2={'color':'red','points':15} aliens=[alien_0,alien_1,alien_2] print(aliens) #使用range aliens=[] for alien_number in range(30):#创建30个外星人,range的作用是告诉python循环多少次 new_alien={'color':'green','point':5,'speed':'slow'} aliens.append(new_alien)#append用于在列表末尾添加新的对象 for alien in aliens[:5]:#使用切片打印前5个 print(alien) print('...') print('Total number of aliens: '+str(len(aliens)))#打印列表的长度 #修改 for alien in aliens[:3]: if alien['color']=='green':#两个等号是判断 alien['color']='yellow'#一个等号是赋值 alien['color']='mediem' alien['point']=10 elif alien['color']=='yellow': alien['color']='red' alien['speed']='fast' alien['points']=15 for alien in aliens[0:5]: print(alien) print('...')
629fabece847eb52995bf752bc4caed0b59fc171
PravinSelva5/LeetCode_Grind
/Linked_Lists/LinkedList.py
6,191
4.1875
4
''' - A linked list is a linear data strucutre where its elements are not stored in contiguous order in memory unlike an array. - Two types: - Singly Linked List - Doubly Linked List - Singly Linked List: - nodes only have a pointer to the NEXT ELEMENT - first node in the linked list is called the HEAD - last node in the linked lis is called the TAIL - Disadvantages: O(n) searching - Advantages: Insertion and deletion are cheaper ( compared to arrays ) ''' # ----------------------------------- # # ----------------------------------- # # Singly Linked List Implementation # # ----------------------------------- # # ----------------------------------- # class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): temp = self.head linked_list = "" while (temp): linked_list += (str(temp.data) + " ") temp = temp.next print(linked_list) # lists starts at 0 def insertNode(self, val, pos): target = Node(val) if (pos == 0): target.next = self.head self.head = target return def getPrev(pos): temp = self.head count = 1 while count < pos: temp = temp.next count += 1 return temp prev = getPrev(pos) nextNode = prev.next prev.next = target target.next = nextNode def deleteNode(self, key): temp = self.head if (temp is None): return if (temp.data == key): self.head = temp.next temp = None return while (temp.next.data != key): temp = temp.next target_node = temp.next temp.next = target_node.next target_node = None #----------------------------------------------------# #----------------------------------------------------# # DOUBLY LINKED LIST #----------------------------------------------------# #----------------------------------------------------# ''' - A doubly linked list node has pointers to both the previous and the next nodes - Insertion: 4 pointers need to be taken care of - Deletion: similar to insertion ''' class DoublyLinkedListNode: def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None def createList(self, arr): start = self.head l = len(arr) temp = start pointer = 0 while pointer < l: newNode = DoublyLinkedListNode(arr[pointer]) if pointer == 0: start = newNode temp = start else: temp.next = newNode newNode.prev = temp temp = temp.next pointer += 1 self.head = start return start def printList(self): temp = self.head linked_list = "" while temp: linked_list += (str(temp.data) + " ") temp = temp.next print(linked_list) def countList(self): temp = self.head count = 0 while ( temp is not None ): temp = temp.next count += 1 return count # consider the index starts at 1 def insertAtLocation(self, value, index): temp = self.head count = self.countList() if ( count + 1 < index ): return temp newNode = DoublyLinkedListNode(value) # Case when user wants to add a new node as the new head if ( index == 1 ): newNode.next = temp temp.prev = newNode self.head = newNode return self.head # If new node is going to be the last node in the linked list if ( index == count + 1): while (temp.next is not None): temp = temp.next temp.next = newNode newNode.prev = temp return self.head # General Case pointer = 1 while ( pointer < index - 1): temp = temp.next pointer += 1 nodeAtTarget = temp.next newNode.next = nodeAtTarget nodeAtTarget.prev = newNode temp.next = newNode newNode.prev = temp return self.head def deleteAtLocation(self, index): temp = self.head count = self.countList() if (count < index): return temp # Deleting the first node if index == 1: temp = temp.next self.head = temp # Deleting the last node if count == index: while temp.next is not None and temp.next.next is not None: temp = temp.next temp.next = None # deleted the last node return self.head pointer = 1 while pointer < index - 1: temp = temp.next pointer += 1 prevNode = temp nodeAtTarget = temp.next nextNode = nodeAtTarget.next # connect previous node with next node, to remove target node out of the linked list nextNode.prev = prevNode prevNode.next = nextNode return self.head # Node structure to be: 5 => 1 => 3 => 7 linked_list =LinkedList() linked_list.head = Node(5) second_node = Node(1) third_node = Node(3) fourth_node = Node(7) linked_list.head.next = second_node second_node.next = third_node third_node.next = fourth_node linked_list.insertNode(2,2) linked_list.deleteNode(3) linked_list.printList() # Doubly Linked List commands to check if class and methods work array = [1,2,3,4,5] Dlinkedlist = DoublyLinkedList() Dlinkedlist.createList(array) Dlinkedlist.printList() Dlinkedlist.insertAtLocation(6,6) Dlinkedlist.printList() Dlinkedlist.deleteAtLocation(2) Dlinkedlist.printList()
93aed7ebf886ad31f7b2b2c8d0fbdd9ec9705b80
yccdesign/Python-for-Everybody
/ex_7_2/ex_7_2_avgnum.py
449
3.515625
4
fname = input('Enter file name:') fileopen = open(fname) count = 0 totalnum = 0 for line in fileopen: if line.startswith('X-DSPAM-Confidence:'): locate = line.find(':') aftercolon = line[locate+1:] num = aftercolon.strip() floatnum = float(num) totalnum = totalnum + floatnum count = count + 1 else: continue avgfloatnum = totalnum/count print('Average spam confidence:', avgfloatnum)
a9a8c3ca0a588d4ac82576bea0af27c1e2b0b75a
magnuskonrad98/max_int
/FORRIT/timaverkefni/29.08.19/greatest_common_divisor.py
259
3.765625
4
m = int(input("Input the first integer: ")) # Do not change this line n = int(input("Input the second integer: ")) # Do not change this line gdc = 0 for i in range(1, m): if m % i == 0 and n % i == 0: if i > gdc: gdc = i print(gdc)
92664a01a546facdcbe63e2d77e85e91c4ee9d81
amberrevans/pythonclass
/chapter 4 and 5 programs/commissions.py
679
4.09375
4
#amber evans #9/15/20 #program 4-1 #This program calculates sales commissions. #create a variable to control the loop. keep_going= 'y' #Calculate a series of commissions. while keep_going=='y': #get a salespersons sales and commission rate. sales = float(input('Enter the amount of sales: ')) comm_rate= float (input('Enter the commission rate: ')) #Calculate the commisssion commission = sales * comm_rate #display the commission print (f'The commission is ${commission:,.2f}.') #see if the user wants to do another one. keep_going = input ('Do you want to calculate another ' + 'commission (Enter y for yes): ')
5cccfde3492de3a8f7b9ac59c1ea953d4b00aaff
jiatongw/notes
/code/queue_stack/reverse_polish_notation.py
1,028
3.9375
4
## LC 150 ## Input: ["2", "1", "+", "3", "*"] ## Output: 9 ## Explanation: ((2 + 1) * 3) = 9 def reverse_polish_notation(tokens): stack = [] for num in tokens: if num == "+": num2 = stack.pop() num1 = stack.pop() result = num1 + num2 stack.append(result) elif num == "-": num2 = stack.pop() num1 = stack.pop() result = num1 - num2 stack.append(result) elif num == "*": num2 = stack.pop() num1 = stack.pop() result = num1 * num2 stack.append(result) elif num == "/": sign = 1 num2 = stack.pop() num1 = stack.pop() if num1 * num2 < 0: ### 在python3里,3 // -5 = -1, 但是题目要求 3 // -5 = 0 sign = -1 result = sign * (abs(num1) // abs(num2)) stack.append(result) else: stack.append(int(num)) return stack[-1]
81edb0d2dde52930b1dfcf67d710c4c867daf2cc
MariaNazari/Introduction-to-Python-Class
/cs131ahw4Final.py
1,311
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ The purpose of this program is to calculate how many times bigger the Alaskan district is from an average Wisconsin district Background: Wisconsin has eight congressional districts covering its land area of 169,790 square kilometers, while Alaska has just one district for its 1,717,856 square kilometers. Write a program which determines how many times bigger than the average Wisconsin district that Alaskan district is. """ wisconsin_land_area = 169790 wisconsin_numberOf_districts = 8 alaska_average_district_size = 1717856 def find_average_district_size(land_area,numberOf_districts): global average_district_size #make variable global to exist outside of function average_district_size = land_area / numberOf_districts find_average_district_size(wisconsin_land_area,wisconsin_numberOf_districts) def compare_district_size_ratio(avg_district1_size, avg_district2_size): global numberOf_times_bigger numberOf_times_bigger = avg_district2_size / avg_district1_size compare_district_size_ratio (average_district_size, alaska_average_district_size) print("The Alaskan district is approximately",'{0:.2f}'.format(numberOf_times_bigger), 'times bigger than an average Wisconsin district.')
69557ae4b9f07fc95ebb551c39a8008e7949e6c2
q36762000/280201102
/lab7/example4.py
378
4.03125
4
password = input("enter a password:") valid = True if len(password) != 8: valid = False if password.lower() == password: valid = False if password.upper() == password: valid = False count = 0 for i in range(10): if str(i) in password: count += 1 if count == 0: valid = False if valid: print("Your password is valid.") else: print("Your password is not valid.")
8de00655ec55cdd75ef84b31f327c19bfd00509a
sky7sea/KDD_Daily_LeetCoding_Challenge
/0329-0404 (Week_1)/RobertHan/039.Length of a Linked List/solution.py
766
3.96875
4
#https://binarysearch.com/problems/Length-of-a-Linked-List ''' Given a singly linked list node, return its length. The linked list has fields next and val. Example - Input node = [5,4,3,] - Output 3 ''' # class LLNode: # def __init__(self, val, next=None): # self.val = val # self.next = next class Solution: def solve(self,node): c = 0 while node: c +=1 node = node.next return c ### Explanation ### ''' Traversing the linked list till next element is null. Traverse through the given linked list, keep count of number until the loop terminates. Time Complexity: O(n) (Because we travel N lenght of Linked list) Space Complexity: O(1) (Becuase we only take an extra int variable) '''
357b3df77357f9739d458ce94fdb0f3559621b32
xucaimao/python
/kid/e1201.py
263
4.09375
4
names=[] print("Enter 5 names:") for i in range(5): names.append(input()) print("The names are",end=" ") for na in names: print(na,end=" ") print() names.sort() print("After sorted,The names are",end=" ") for na in names: print(na,end=" ") print()
f97ea3cb395a68753b9797484d4bf88996f8d533
gonzaloquiroga/neptunescripts
/lation2.py
799
3.703125
4
#! /usr/bin/env python import re #It creates an object where the package of Regular expressions are in Python InFileName = 'Marrus_claudanielis.txt' InFile = open (InFileName, 'r') #opening the file to read it! LineNumber = 0 for Line in InFile: Line = Line.strip() if LineNumber > 0: #print (LineNumber) #print (Line) ElementList = Line.split( '\t' ) #print (ElementList) print ( 'Depth:{} Lat: {} Long: {}'.format (ElementList [4], ElementList [2], ElementList [3])) SearchString = '(\d+) ([\d\.]+) (\w)' Result = re.search( SearchString, ElementList[2] ) #in the regular epxpression library, search this re. print (Result.group ( 0 )) print (Result.group ( 1 )) print (Result.group ( 2 )) print (Result.group ( 3 )) LineNumber = LineNumber + 1 InFile.close()
54128716fa095b91e0a5dc4c95678332b47af24c
TrickFF/helloworld
/task3.2.py
974
3.859375
4
# 3: import random player = { 'name': '', 'health': 100, 'min_damage': 30, 'max_damage': 50, 'armor': 1.2 } enemy = { 'name': 'COVID-19', 'health': 100, 'min_damage': 10, 'max_damage': 50 } player['name'] = input('Введите свое имя - ') def attack(player, enemy): dmg_player = random.randint(player['min_damage'], player['max_damage']) dmg_enemy = random.randint(enemy['min_damage'], enemy['max_damage']) player['health'] -= int(dmg_enemy/player['armor']) enemy['health'] -= dmg_player return f"{enemy['name']} нанес {dmg_enemy} урона. Получено {int(dmg_enemy/player['armor'])} урона с учетом брони." \ f" Здоровье игрока после атаки - {player['health']}. \n" \ f"{player['name']} нанес {dmg_player} урона. Здоровье врага после атаки - {enemy['health']}." print(attack(player, enemy))
714bf09379b5017d6778bdd862e9758fec9a470e
sqw3Egl/TSTP
/TSTP_Scripts/chapt4_examples/def_variable_example2.py
210
4.34375
4
#save the result the function returns in a variable for use later in the program. def f(x): return x + 1 z = f(5) if z == 5: print("z is 5") else: print("z is not 5, its something else!")
a1452e7cfc087e81d2437e59c07315770b4d1dfa
sevenhe716/LeetCode
/Heap/q855_exam_room.py
16,782
3.53125
4
# Time: seat O(n) leave O(log(n)) # Space: O(n) # 解题思路: # 多次调用,需要维护当前座位信息的数据结构,当数据稀疏时,维护座位索引即可 # 对于相邻的座位i,j,离相邻学习的最大距离为d = (j-i)//2,新的位置为i+d,但需要保证i+1<j,或者说保证存在座位,则不会取到这种情况(我的计算方式太复杂) # 特殊情况:左右两端需要单独判断,d = seat_index[0], d = self.N-1-seat_index[-1],从左至右选择第一个满足条件的解 # O(n)并非效率最高的解法,用最大堆或者优先队列来维护下一个最优位置,可以把seat的时间复杂度降为O(log(n)),但是维护成本变高 import bisect import heapq from heapq import heappop, heappush class ExamRoom: @staticmethod def call(methods, params): room = None rets = [0] * len(methods) for i, method in enumerate(methods): if method == 'ExamRoom': room = ExamRoom(params[i][0]) rets[i] = None elif method == 'seat': rets[i] = room.seat() elif method == 'leave': room.leave(params[i][0]) rets[i] = None return rets def __init__(self, N): """ :type N: int """ self.seats = [0] * N self.dp = [i + 1 for i in range(N)] self.N = N # print(self.seats) # print(self.dp) # print() def seat(self): """ :rtype: int """ seat_pos = self.find_seat_pos1() self.seats[seat_pos] = 1 self.adjust_seat_seat(seat_pos) # print(self.seats) # print(self.dp) # print(seat_pos) # print() # if seat_pos >= 0: # self.seats[seat_pos] = 1 return seat_pos def leave(self, p): """ :type p: int :rtype: void """ self.seats[p] = 0 self.adjust_seat_leave(p) # print('leave') # print(self.seats) # print(self.dp) # print(p) # print() def adjust_seat_seat(self, p): self.dp[p] = 0 count = 1 for i in range(p + 1, self.N): if self.seats[i]: return else: self.dp[i] = count count += 1 begin = -1 for i in range(p)[::-1]: if self.seats[i]: begin = i break count = 1 for i in range(begin + 1, p): self.dp[i] = count count += 1 def adjust_seat_leave(self, p): begin = -1 for i in range(p)[::-1]: if self.seats[i]: begin = i break end = self.N for i in range(p + 1, self.N): if self.seats[i]: end = i break count = 1 for i in range(begin + 1, end): self.dp[i] = count count += 1 def find_seat_pos1(self): longest = 0 cur = -1 for i in range(self.N): # 单独讨论两端的情况 if i == self.N - 1: if self.dp[i] << 1 > longest and ((self.dp[i] << 1) - 1) >> 1 > (longest - 1) >> 1: longest = self.dp[i] << 1 cur = i elif i == self.dp[i] - 1: longest = self.dp[i] << 1 cur = i else: if self.dp[i] > longest and (self.dp[i] - 1) >> 1 > (longest - 1) >> 1: longest = self.dp[i] cur = i # print(cur) # print('l={}, c={}'.format(longest, cur)) # if cur == 7: # print('here') if longest >> 1 == self.N: return 0 elif cur == self.N - 1: return cur elif cur == (longest >> 1) - 1: return 0 cur_seat = cur - longest + 1 + ((longest - 1) >> 1) return cur_seat # def find_seat_pos(self): # longest = 0 # cur = 0 # cur_seat = -1 # # for i, seat in enumerate(self.seats): # if seat: # if i == cur: # 单独处理头部为0的情况 # if cur > longest >> 1: # longest = cur << 1 # cur_seat = 0 # else: # # if (cur + 1) >> 1 > longest >> 1 or (longest == 0 and (cur + 1) >> 1 >= longest >> 1): # if (cur + 1) >> 1 > longest >> 1 and (cur - 1) >> 1 > (longest - 1) >> 1: # longest = cur # cur_seat = i - cur + ((cur - 1) >> 1) # # cur = 0 # else: # cur += 1 # # if cur > 0: # 单独处理尾部为0的情况 # if cur << 1 > longest: # # if cur == len(self.seats): # cur_seat = 0 # else: # cur_seat = len(self.seats) - 1 # # return cur_seat # Your ExamRoom object will be instantiated and called as such: # obj = ExamRoom(N) # param_1 = obj.seat() # obj.leave(p) class ExamRoom1: @staticmethod def call(methods, params): room = None rets = [0] * len(methods) for i, method in enumerate(methods): if method == 'ExamRoom': room = ExamRoom1(params[i][0]) rets[i] = None elif method == 'seat': rets[i] = room.seat() elif method == 'leave': room.leave(params[i][0]) rets[i] = None return rets # 这个数据结构维护了区间,同时记录了区间的长度 # 还可以只维护1的索引,然后每次用1来减 def __init__(self, N): """ :type N: int """ self.N = N self.seat_index = [] def seat(self): """ :rtype: int """ seat_pos = self.find_seat_pos() self.adjust_seat_seat(seat_pos) return seat_pos def leave(self, p): """ :type p: int :rtype: void """ self.adjust_seat_leave(p) def adjust_seat_seat(self, p): import bisect bisect.insort(self.seat_index, p) def adjust_seat_leave(self, p): import bisect self.seat_index.pop(bisect.bisect_left(self.seat_index, p)) def find_seat_pos(self): longest = 0 cur = -1 if not self.seat_index: return 0 for i in range(len(self.seat_index) - 1): zero_count = self.seat_index[i + 1] - self.seat_index[i] - 1 if zero_count > longest and (zero_count - 1) >> 1 > (longest - 1) >> 1: longest = zero_count cur = i # 单独讨论两端的情况 zero_count = self.N - self.seat_index[-1] - 1 if self.seat_index[0] << 1 >= longest and self.seat_index[0] << 1 > 0 and self.seat_index[0] >= zero_count: return 0 if zero_count << 1 > longest and ((zero_count << 1) - 1) >> 1 > (longest - 1) >> 1: return self.N - 1 return self.seat_index[cur] + 1 + ((longest - 1) >> 1) class ExamRoom2: # 最大堆 interval value为离相邻位置的最大距离,还需要一个dict索引左边界 右边界对应的区间,保证可以O(1)时间找到对应区间 # 添加时,先pop出当前区间,然后将此区间分裂成两个区间即可,删除时,需要找到这个点对应的左右区间,并且删除,合并一个新的区间 # left+1=right的区间是否要添加 class Interval: def __init__(self, left, right, N): self.left = left self.right = right self.N = N self.available = True def __lt__(self, other): d1 = self.dist() d2 = other.dist() if d1 == d2: return self.left <= other.left # 相等时选择坐标小的那个 else: return d1 > d2 def dist(self): # 左右边界单独处理 if self.left == 0 or self.right == self.N: return self.right - self.left return (self.right - self.left + 1) // 2 def __str__(self): return '({}, {})'.format(self.left, self.right) def __init__(self, N): """ :type N: int """ self.N = N self.priority_intervals = [] self.left_interval_dict = {} self.right_interval_dict = {} self.add_interval(self.Interval(0, N, N)) def print_intervals(self): print('left ', end='') for k, v in self.left_interval_dict.items(): if v.available: print('{}:{} '.format(k, v), end='') print() print('right ', end='') for k, v in self.right_interval_dict.items(): if v.available: print('{}:{} '.format(k, v), end='') print() print() def add_interval(self, interval): heapq.heappush(self.priority_intervals, interval) self.left_interval_dict[interval.left] = interval self.right_interval_dict[interval.right] = interval def add_seat(self, p, interval): # if interval.left < p: # li = self.Interval(interval.left, p, self.N) # self.add_interval(li) # # if p + 1 < interval.right: # ri = self.Interval(p + 1, interval.right, self.N) # self.add_interval(ri) li = self.Interval(interval.left, p, self.N) self.add_interval(li) ri = self.Interval(p + 1, interval.right, self.N) self.add_interval(ri) def pop_seat(self): interval = heapq.heappop(self.priority_intervals) while not interval.available: interval = heapq.heappop(self.priority_intervals) self.left_interval_dict.pop(interval.left) self.right_interval_dict.pop(interval.right) return interval # 无法删除heapq中的指定元素,因此使用标记的方式 def remove_seat(self, p): # 暂时默认删除的元素必然存在 self.add_interval(self.Interval(self.right_interval_dict[p].left, self.left_interval_dict[p+1].right, self.N)) self.left_interval_dict.pop(p + 1).available = False self.right_interval_dict.pop(p).available = False def seat(self): """ :rtype: int """ interval = self.pop_seat() # 若是两端则取0, n-1,若是中段则(left+right)//2 if interval.left == 0: seat_pos = 0 elif interval.right == self.N: seat_pos = self.N - 1 else: seat_pos = (interval.left + interval.right - 1) // 2 # print('pos=', seat_pos) self.add_seat(seat_pos, interval) # self.print_intervals() return seat_pos def leave(self, p): """ :type p: int :rtype: void """ self.remove_seat(p) # self.print_intervals() @staticmethod def call(methods, params): room = None rets = [0] * len(methods) for i, method in enumerate(methods): if method == 'ExamRoom': room = ExamRoom2(params[i][0]) rets[i] = None elif method == 'seat': rets[i] = room.seat() elif method == 'leave': room.leave(params[i][0]) rets[i] = None return rets class ExamRoom3(object): @staticmethod def call(methods, params): room = None rets = [0] * len(methods) for i, method in enumerate(methods): if method == 'ExamRoom': room = ExamRoom3(params[i][0]) rets[i] = None elif method == 'seat': rets[i] = room.seat() elif method == 'leave': room.leave(params[i][0]) rets[i] = None return rets def __init__(self, N): self.N = N self.students = [] def seat(self): # Let's determine student, the position of the next # student to sit down. if not self.students: student = 0 else: # Tenatively, dist is the distance to the closest student, # which is achieved by sitting in the position 'student'. # We start by considering the left-most seat. dist, student = self.students[0], 0 for i, s in enumerate(self.students): if i: prev = self.students[i - 1] # For each pair of adjacent students in positions (prev, s), # d is the distance to the closest student; # achieved at position prev + d. d = (s - prev) // 2 if d > dist: dist, student = d, prev + d # Considering the right-most seat. d = self.N - 1 - self.students[-1] if d > dist: student = self.N - 1 # Add the student to our sorted list of positions. bisect.insort(self.students, student) return student def leave(self, p): self.students.pop(bisect.bisect(self.students, p)) class ExamRoom4: @staticmethod def call(methods, params): room = None rets = [0] * len(methods) for i, method in enumerate(methods): if method == 'ExamRoom': room = ExamRoom4(params[i][0]) rets[i] = None elif method == 'seat': rets[i] = room.seat() elif method == 'leave': room.leave(params[i][0]) rets[i] = None return rets def __init__(self, N): self.N, self.L = N, [] def seat(self): N, L = self.N, self.L if not L: L.append(0) return 0 d = max(L[0], N - 1 - L[-1]) for a, b in zip(L, L[1:]): d = max(d, (b - a) // 2) # 这么写很cool,zip并未生成拷贝,也是iter if L[0] == d: L.insert(0, 0) return 0 for i in range(len(L) - 1): if (L[i + 1] - L[i]) / 2 == d: L.insert(i + 1, (L[i + 1] + L[i]) // 2) return L[i + 1] L.append(N - 1) return N - 1 def leave(self, p): self.L.remove(p) # https://leetcode.com/problems/exam-room/discuss/139941/Python-O(log-n)-time-for-both-seat()-and-leave()-with-heapq-and-dicts-Detailed-explanation class ExamRoom5(object): def __init__(self, N): """ :type N: int """ self.N = N self.heap = [] self.avail_first = {} self.avail_last = {} self.put_segment(0, self.N - 1) def put_segment(self, first, last): if first == 0 or last == self.N - 1: priority = last - first else: priority = (last - first) // 2 segment = [-priority, first, last, True] # 未使用class,而是把排序值也放进了heap中 self.avail_first[first] = segment self.avail_last[last] = segment heappush(self.heap, segment) def seat(self): """ :rtype: int """ while True: _, first, last, is_valid = heappop(self.heap) if is_valid: del self.avail_first[first] del self.avail_last[last] break if first == 0: ret = 0 if first != last: self.put_segment(first + 1, last) elif last == self.N - 1: ret = last if first != last: self.put_segment(first, last - 1) else: ret = first + (last - first) // 2 if ret > first: self.put_segment(first, ret - 1) if ret < last: self.put_segment(ret + 1, last) return ret def leave(self, p): """ :type p: int :rtype: void """ first = p last = p left = p - 1 right = p + 1 if left >= 0 and left in self.avail_last: segment_left = self.avail_last.pop(left) segment_left[3] = False first = segment_left[1] if right < self.N and right in self.avail_first: segment_right = self.avail_first.pop(right) segment_right[3] = False last = segment_right[2] self.put_segment(first, last)
48361c4f4904145d397db0376b0773f79d43518a
bujars/csc113
/Chapter9prac.py
2,250
4.34375
4
class Dog(): #A simple attempt to model a dog. def __init__(self, name, age): #NOTE init function is constructor, def means define a function, #this is a "self" function because it accepts self, or an instance as a paramter # "Initialzie name and age attributes" self.name=name self.age = age def sit(self): #" Simulate a dog sititng response" print(self.name.title() + ' is sitting') def roll_over(self): print(self.name.title()+' rolled') #creating instances joe = Dog('joe', 5) pug = Dog('pug', 2) #call funcitons joe.sit() joe.roll_over() #accessing attributes joe.name #You cna modify the attributes of an instance directly, or write methods that update attributes in specific ways class Car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def increment_odometer(self, miles): self.odometer_reading += miles def read_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer() #Modifying the attriute my_new_car.odometer_reading = 23 my_new_car.read_odometer() #To make classes more interesting, we can have them have attribites that change overtime #def update_odometer(self, mileage): #added to class #"""Set the odometer reading to the given value.""" self.odometer_reading = mileage #Showing how you can't go backwards on an odometer my_new_car.update_odometer(20) my_new_car.read_odometer() #Showing an incremenet my_used_car = Car('subaru', 'outback', 2013) print(my_used_car.get_descriptive_name()) my_used_car.update_odometer(23500) my_used_car.read_odometer() my_used_car.increment_odometer(100) my_used_car.read_odometer()
1e81f1ad64af88917fd409183b061626ef141577
silvafj/BBK-MSCCS-2017-19
/POP1/mocks/practical-one/question1a.py
164
3.6875
4
def fib(n): terms = [0, 1, 1] for i in range(3, n): terms.append(terms[i-1] + terms[i-2]) return terms for v in fib(20): print(v, end=" ")
40f35423f3a6f923157756592a77993fbeaf94ef
KevenGe/LeetCode-Solutions
/books/《剑指offer》/剑指 Offer 41. 数据流中的中位数.py
875
3.59375
4
# 剑指 Offer 41. 数据流中的中位数 # https://leetcode-cn.com/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/ import heapq class MedianFinder: def __init__(self): """ initialize your data structure here. """ self.A = [] self.B = [] def addNum(self, num: int) -> None: if len(self.A) == len(self.B): heapq.heappush(self.A, -heapq.heappushpop(self.B, -num)) else: heapq.heappush(self.B, -heapq.heappushpop(self.A, num)) def findMedian(self) -> float: if len(self.A) == len(self.B): return (self.A[0] - self.B[0]) / 2 else: return self.A[0] # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian() if __name__ == "__main__": m = MedianFinder()
c87850a7d419ff0a10a2d24c5950b51baeced6a1
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/scrsha001/util.py
2,733
3.796875
4
# Shaaheen Sacoor SCRSHA001 #30 April 2014 # Programs that to be utilized for 2048 game #Creating grid def create_grid(grid): height =4 for i in range(4): grid.append([0]*4) return grid #Printing Grid def print_grid(grid): print("+--------------------+") for y in range(4): for x in range(4): lnth = len(str(grid[y][x])) #Works out how much space must be left ending = 5-lnth # between numbers. This is dependant on length if grid[y][x] ==0 : #of number grid[y][x] = " " #Changes 0 into space if x == 0: print("|",grid[y][x],end =" "*ending,sep="") #Format of grid elif x == 3: print(grid[y][x],"|",end ="",sep=" "*ending) else: print(grid[y][x],end=" "*ending) print() for y in range(4): for x in range(4): if grid[y][x] ==" " : #Changes space back into 0 grid[y][x] = 0 print("+--------------------+") #Checks if user has lost def check_lost(grid): x= "STOP" for j in range(4): if 0 in grid[j]: #Goes through each line of grid to see if there is a space x= "carry on" if x =="carry on": return False #if there isn't a space, user hasn't lost else: counter =0 counter2 = 0 for y in range(4): #Goes through each value on grid and looks for adjacent equal for x in range(3): #values if grid[y][0] == grid[y][1] or grid[y][1] == grid[y][2] or grid[y][2] == grid[y][3]: counter +=1 if grid[0][x] == grid[1][x] or grid[1][x] == grid[2][x] or grid[2][x] == grid[3][x]: counter2 +=1 if counter ==0 and counter2 ==0: return True else: return False #Checks if user won def check_won(grid): for y in range(4): for x in range(4): if grid[y][x] ==" " : grid[y][x] = 0 if grid[y][x]>=32: return True # if grid[y][x] ==0 : # grid[y][x] = " " else: return False #Makes a deepcopy of grid def copy_grid(grid): import copy global copygrid1 copygrid1 = copy.deepcopy(grid) return copygrid1 #Checks if grids are equal so as to not add a new random number if grid doesn't move def grid_equal(grid1,grid2): if grid1 == grid2: return True else : return False
e499cfcd27e72aeccc08228d3497b03d67b95b77
blackbogdan/interviewcake
/task1_stocks.py
5,473
4.34375
4
# coding=utf-8 # Suppose we could access yesterday's stock prices as a list, where: # # The indices are the time in minutes past trade opening time, which was 9:30am local time. # The values are the price in dollars of Apple stock at that time. # So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 500. # # Write an efficient function that takes stock_prices_yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday. # stock_prices_yesterday = [10, 7, 5, 8, 11, 9] # # get_max_profit(stock_prices_yesterday) # returns 6 (buying for $5 and selling for $11) # import time # stock_prices_yesterday = [10, 7, 5, 8, 11, 9] stock_prices_yesterday = [12, 11, 10, 9, 7, 4] def get_max_profit1(stock_prices_yesterday): "BRUTE FORCE APPROACH" ''' the point of this code is to find maximum porfit by comparing existing one in the beginning of the for loop to max_profit ''' max_profit = 0 # go through every time start_time = time.time() time.sleep(1) for outer_time in xrange(len(stock_prices_yesterday)): # for every time, go through every OTHER time for inner_time in xrange(len(stock_prices_yesterday)): # for each pair, find the earlier and later times earlier_time = min(outer_time, inner_time) later_time = max(outer_time, inner_time) # and use those to find the earlier and later prices earlier_price = stock_prices_yesterday[earlier_time] later_price = stock_prices_yesterday[later_time] # see what our profit would be if we bought at the # earlier price and sold at the later price potential_profit = later_price - earlier_price # update max_profit if we can do better max_profit = max(max_profit, potential_profit) print("--- %s seconds ---" % (time.time() - start_time)) return max_profit def get_max_profit2(stock_prices_yesterday): "STILL BRUTE FORCE, but better one" max_profit = 0 # go through every price (with its index as the time) for earlier_time, earlier_price in enumerate(stock_prices_yesterday): print earlier_time, earlier_price # and go through all the LATER prices for later_price in stock_prices_yesterday[earlier_time+1:]: print "===============" print stock_prices_yesterday[earlier_time+1:] # see what our profit would be if we bought at the # earlier price and sold at the later price potential_profit = later_price - earlier_price # update max_profit if we can do better max_profit = max(max_profit, potential_profit) return max_profit def get_max_profit3(stock_prices_yesterday): """A greedy algorithm iterates through the problem space taking the optimal solution "so far," until it reaches the end. The greedy approach is only optimal if the problem has "optimal substructure," which means stitching together optimal solutions to subproblems yields an optimal solution""" min_price = stock_prices_yesterday[0] max_profit = 0 for current_price in stock_prices_yesterday: # ensure min_price is the lowest price we've seen so far min_price = min(min_price, current_price) # see what our profit would be if we bought at the # min price and sold at the current price potential_profit = current_price - min_price # update max_profit if we can do better max_profit = max(max_profit, potential_profit) print max_profit """ Let’s think about some edge cases. What if the stock value stays the same? What if the stock value goes down all day? first scenario is good, what about second one""" # stock_prices_yesterday = [10, 7, 5, 8, 11, 9] stock_prices_yesterday = [12, 13, 10, 9, 7, 4] def get_max_profit3(stock_prices_yesterday): # make sure we have at least 2 prices if len(stock_prices_yesterday) < 2: raise IndexError('Getting a profit requires at least 2 prices') # we'll greedily update min_price and max_profit, so we initialize # them to the first price and the first possible profit min_price = stock_prices_yesterday[0] max_profit = stock_prices_yesterday[1] - stock_prices_yesterday[0] for index, current_price in enumerate(stock_prices_yesterday): # skip the first (0th) time # we can't sell at the first time, since we must buy first, # and we can't buy and sell at the same time! # if we took this out, we'd try to buy /and/ sell at time 0. # this would give a profit of 0, which is a problem if our # max_profit is supposed to be /negative/--we'd return 0! if index == 0: continue # see what our profit would be if we bought at the # min price and sold at the current price potential_profit = current_price - min_price # update max_profit if we can do better max_profit = max(max_profit, potential_profit) # update min_price so it's always # the lowest price we've seen so far min_price = min(min_price, current_price) print max_profit get_max_profit3(stock_prices_yesterday)
50a5f662940e4e9c9589abd4f87ff3e4d8444484
adebray/adebray.github.io
/python/mandelbrot.py
917
3.609375
4
#Draws a Mandelbrot set. from Tkinter import * def main(): master = Tk() w = Canvas(master,width=750,height=675) w.pack() a = -2.0 while a < 1.75: b = -1.25 #Unfortunately this skips over zero while b < 1.25: if in_set(a,b): create_point(give_x(a),give_y(b),w) b = b + 0.001 #This takes a long time! You may want to use 0.004 instead a = a + 0.001 #same thing def in_set(a,b): z = (a,b) for i in range(100): #Hopefully sufficient z = next_fn(z,a,b) (x,y) = z if x*x + y*y < 3: return True else: return False def next_fn(z,a,b): (x,y) = z x_next = x*x - y*y + a y_next = 2*x*y + b z_next = (x_next,y_next) return z_next def create_point(a,b,w): w.create_line(a,b,a+1,b) w.create_line(a+1,b,a+2,b,fill="white") def give_x(a): return 250*(a+2) def give_y(b): return 250*(1.25-b) if __name__ == '__main__': main()
6fb3874538b010fa6367cfd1ef6ed6fd392e91c3
TheJoeCollier/cpsc128
/code/python2/tmpcnvrt.py
1,242
4.5
4
########################################################### ## tmpcnvrt.py -- allows the user to convert a temperature ## in Fahrenheit to Celsius or vice versa. ## ## CPSC 128 Example program: a simple usage of 'if' statement ## ## S. Bulut Spring 2018-19 ## Tim Topper, Winter 2013 ########################################################### print "This program converts temperatures from Fahrenheit to Celsius," print "or from Celsius to Fahrenheit." print "Choose" print "1 to convert Fahrenheit to Celsius" print "2 to convert Celsius to Fahrenheit" choice = input( "Your choice? " ) if choice == 1: print "This program converts temperatures from Fahrenheit to Celsius." temp_in_f = input( "Enter a temperature in Fahrenheit (e.g. 10) and press Enter: " ) temp_in_c = (temp_in_f - 32) * 5 / 9 print temp_in_f, " degrees Fahrenheit = ", temp_in_c, " degrees Celsius." elif choice == 2: print "This program converts temperatures from Celsius to Fahrenheit ." temp_in_c= input( "Enter a temperature in Celsius (e.g. 10) and press Enter: " ) temp_in_f = temp_in_c * 9 / 5 + 32 print temp_in_c, " degrees Celsius = ", temp_in_f, " degrees Fahrenheit." else: print "Error: Your choice not recognized!"
9158a9d71afe231d29baa78e499900f78458650d
ZGingko/algorithm008-class02
/Week_08/242.valid-anagram.py
599
3.546875
4
class Solution: """ 242.有效的字母异位词 https://leetcode-cn.com/problems/valid-anagram/ """ def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False base = ord('a') counter = [0] * 26 for i in range(len(s)): counter[ord(s[i]) - base] += 1 counter[ord(t[i]) - base] -= 1 for c in counter: if c != 0: return False return True if __name__ == "__main__": sol = Solution() s = "anagram" t = "nagaram" print(sol.isAnagram(s, t))
f45619416d5d80444b45d288dc54089b4c577add
marleneargenton/Python-Ipea
/Interaction.py
2,798
3.78125
4
# Python4ABMIpea - Exercício 2 # # Professor: Bernardo Furtado # # Autora: Marlene Aparecida Argenton # # Outro módulo, import as classes e contém algumas funções: # Uma para criar os agentes e as lojas, a partir de um número n e controla o id específico i # Criam-se listas # Faz-se um loop utilizando n, i, append às listas, retorna # Outra função, acessa as contas dos agentes e deposita recursos, por exemplo: # a[i].account.deposit(random.randrange(10, 50)) # Por fim, talvez a função ao mais difícil, a interação entre agentes e lojas. # Por exemplo, para todos os agentes, escolhe-se uma loja aleatória: # random.choice(listalojas) # então, verifica-se a capacidade da loja, os recursos do agente, faz-se a visita, computa-se o gasto e adquire-se # satisfação! Por exemplo: # s1.account.deposit(a[i].account.pay(s1.cost)) # a[i].get fun(s1.fun) # Por fim, escreva uma função que tire a média da satisfação do agente, do custo das lojas e das contas. from Accounts import Agent, Shop import random def creation(f, n, d): # essa função pode ser utilizada por agentes e lojas pois o primeiro argumento é a classe x = list() for i in range(n): x.append(f(i, d)) i += 1 return x def salaries(a): # acessa a conta dos agentes e deposita recursos for i in range(len(a)): a[i].account.deposit(random.randrange(10, 50)) def interact(a, s): # verifica-se a capacidade da loja, os recursos do agente, faz-se a visita, computa-se o gasto e adquire-se # satisfação for i in range(len(a)): s1 = random.choice(s) if a[i].check_funds(s1) and s1.check_capacity(): s1.visit() s1.account.deposit(a[i].account.pay(s1.cost)) a[i].get_fun(s1.fun) def averaging(a, s): # essa função calcula a média da satisfação do agente, do custo das lojas e das contas das lojas e dos agentes. avg_fun = sum([i.fun for i in a]) / len(a) avg_cost = sum([i.cost for i in s]) / len(s) avg_shop = sum([i.account.balance for i in s]) / len(s) avg_agent = sum([i.account.balance for i in a]) / len(a) print('A média da satisfação é {:.2f}\nA média do custo das lojas é {:.2f}\nA média das contas das lojas e dos ' 'agentes são {:.2f} e {:.2f}\n'.format(avg_fun, avg_cost, avg_shop, avg_agent)) def main(a, s): # cria listas list_a = creation(Agent, a, 1) list_s = creation(Shop, a, s + 1) # mistura as listas random.shuffle(list_a) random.shuffle(list_s) salaries(list_a) interact(list_a, list_s) return list_a, list_s if __name__ == '__main__': ag = 10 sh = 10 agents, shops = main(ag, sh) print(averaging(agents, shops))
b295affe0a0ad0ce0754b4e57eb09b68e5c6df13
larikova/python-practice
/lacey-book/109.py
642
4.15625
4
print("1) Create a new file") print("2) Display the file") print("3) Add a new item to the file") selection = int(input("Make a selection 1, 2 or 3: ")) if selection == 1: file = open("Subjects.txt", "w") subject = input("Enter a school subject: ") file.write(subject + "\n") file.close() elif selection == 2: file = open("Subjects.txt", "r") print(file.read()) elif selection == 3: file = open("Subjects.txt", "a") subject = input("Enter a school subject: ") file.write(subject + "\n") file.close() file = open("Subjects.txt", "r") print(file.read()) file.close() else: print("Error")
9218271e4fb907b966c079fe1d0ec1a4f185e263
Yoyoshix/random
/tilde_expression.py
1,122
3.984375
4
def is_prime(number): if number == 1 or number%2 == 0: return 0 for i in range(3, int(number**0.5)+1, 2): if number%i == 0: return 0 return 1 def prime_factor(number): prime_list = [] while number % 2 == 0: prime_list.append(2) number = number // 2 div = 3 while div <= number: while number % div == 0: prime_list.append(div) number = number // div div += 2 return prime_list def generate(number): if abs(number) == 2: return "*~1" res = "" yes = is_prime(abs(number)) prime_list = prime_factor(abs(number) + yes) for prime in prime_list: res += generate(prime) return "*" + "~("*yes + res[1:] + "*~0"*((prime_list.count(2)+yes)%2) + ")"*yes def make_tilde_expression(number): if number == -1: return "~0" if number in [0,1]: return str(number) if number == 2: return "~1*~0" res = generate(number)[1:] + "*~0"*(number < 0) res = res.replace("*~0*~0", "") print(number) print(eval(res)) print(res)
a81799e19c04debcb218c689387e353ad2230390
Haris-Noori/algoassignment2
/i150013_Sabkat/q6.py
557
3.5
4
#q6 def count( S, m, n ): table=[[0 for x in range(m+1)] for x in range(n+1)] for i in range(1,m): table[0][i] = 1; for i in range(1,m): for j in range(1,n): if(S[i-1]>j): table[i][j]=table[i-1][j] else: table[i][j]=table[i-1][j]+table[i][j-(i-1)] for i in range(1,m): for j in range(1,n): print(table[i][j],end=" ") print("\n") return table[m-1][n-1] arr = [1, 2, 3] m = len(arr) N = 4 x = count(arr, m, N) print (x)
a6fb79df3858935d9307e87da861c3fb5acf2cdd
draganmoo/trypython
/pandas_notes/Song_Tian_Pandas/s1_Series.py
273
3.671875
4
import pandas as pd # 生成一个20行的series d = pd.Series(range(5)) print(d) """ 0 0 1 1 2 2 3 3 4 4 dtype: int64 """ """对d进行前n项累加""" print(d.cumsum()) """ 0 0 1 1 2 3 3 6 4 10 dtype: int64 """
8238b59030b1874ae2f2e532a2f07a6c2ffcbf50
PC-coding/Exercises
/data_structures/linked_lists/1_insert_start/solution/solution.py
329
3.734375
4
# Write your solution here class Node: def __init__(self, data): self.data = data self.next = None class linkedList: def __init__(self, head=None): self.head = head def insert_at_start(self, data): Node1 = Node(data) Node1.next = self.head self.head = Node1
4e1e17d8336917f19eb92ddb8d2d61c44ab9af75
SmischenkoB/campus_2018_python
/Oleksandr_Mykhailovskyi/2/MapFunctions.py
414
4.28125
4
import math def map_functions(arg, *functions): """ Given object arg and functions - subsequently use those functions on arg. Args: arg (obj): any object. *functions: functions which can take arg. Returns: arg. """ for func in functions: arg = func(arg) return arg num = float(input("Enter number\n")) print(map_functions(num, math.sin, math.cos))