blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
0497e4dca2c5e64b7cb1c737a15dc18fc3c1443e
FATIZ-CH/mundiapolis-ml
/0x01-classification/1-neuron.py
723
3.578125
4
#!/usr/bin/env python3 import numpy as np class Neuron: def __init__(self, nx): '''INTEGER & >1 CONDITION''' if type(nx) != int: raise TypeError('nx must be an integer') elif nx < 1: raise ValueError('nx must be a positive integer') else: self.__W = np.random.normal(size=(1, nx)) self.__b = 0 self.__A = 0 @property def W(self): """Returns: private instance weight""" return self.__W @property def b(self): """Returns: private instance bias""" return self.__b @property def A(self): """Returns: private instance output""" return self.__A
9d746d03cb9c99ab929176c5003194e1e2ff82ee
Viinky-Kevs/ClasesPython
/sesion7.py
1,679
3.859375
4
""" Mientras Que Como vimos anteriormente, en Python, el ciclo Mientras Que se maneja con "while". Por ejemplo: """ def ejemplo1(): i = 1 while i < 6: print(i) i += 1 #ejemplo1() def actividad1(): print("actividad1") # Continuemos integrando los conceptos que hemos visto hasta el momento. # Ahora vamos a elaborar un algoritmo que pida un número al usuario, e imprima todos los números pares desde 2 hasta el número. number = int(input("Ingrese un número")) i = 2 while i <= number: print(i) i += 2 # Para ejecutar cada actividad, debes quitar el comentario a la línea que llama el bloque de código #actividad1() def actividad2(): print("actividad2") #Escribe el código un ciclo para obtener el número de dígitos de un número ingresado por el usuario. num1 = int(input("Ingrese el numero: ")) digito = 1 while num1 > 0: num1 = num1//10 digito += 1 if num1 == 1: print(digito) actividad2() def actividad3(): import numpy as np print("actividad3") #Escribe el código que solicite números al usuario hasta que éste ingrese -1. #Cuando se ingrese -1, el programa debe imprimir el promedio de todos los números ingresados hasta ese momento (sin contar con el -1). numbers = None dicti = [] while numbers != -1: numbers = int(input("Ingrese números (para terminar digite -1): ")) if numbers != -1: dicti.append(numbers) media = np.mean(dicti) print(f"El promedio de {dicti} es {media}") #actividad3()
bfb4b2bc263d17db3e7ddac1f5023cf6fca39be0
FireAmpersand/231PythonProjects
/ex7.py
419
3.625
4
def flatten(list, newList): for i in range(len(list)): if type(list[i]) is type([]): newList = flatten(list[i], newList) else: newList.append(list[i]) return(newList) def testSuite(): print(flatten([2,9,[2,1,13,2],8,[2,6]], [])) print(flatten([[9,[7,1,13,2],8],[7,6]], [])) print(flatten([[9,[7,1,13,2],8],[2,6]], [])) print(flatten([['this',['a',['thing'],'a'],'is'],['a','easy']], [])) testSuite()
2456276e34d2435e631e142878b8d67d563bd6f7
FireAmpersand/231PythonProjects
/turtleMethods.py
211
3.5
4
import turtle wn = turtle.Screen() alex = turtle.Turtle() alex.write("Hello") #Alex writes Hello on the screen alex.penup() alex.goto(200,200) alex.begin_fill() alex.circle(20) alex.end_fill() wn.mainloop()
5212b4e60d7f376019fd415f4b912e162bd28c06
FireAmpersand/231PythonProjects
/ex8.py
422
3.625
4
def main(): strn = input("Enter text: ").lower() letterCount = {} for letter in strn: letterCount[letter] = letterCount.get(letter, 0) + 1 if letter == " ": del(letterCount[letter]) letterItems = list(letterCount.items()) letterItems.sort() print(letterItems) for i in range(len(letterItems)): tup = letterItems[i] valueOne = tup[0] valueTwo = tup[1] print(valueOne + " : " + str(valueTwo)) main()
c25d7652a815aeed4457282f41f638e2c7ec1520
FireAmpersand/231PythonProjects
/pytest.py
147
3.625
4
a = int(input("Enter A: ")) for x in range(1, 1000): for z in range (1,1000): y = a if x*x == y*y + z*z: if y < z < x: print(y,z,x)
894ddfec618f02fcda53b13ab5b3003b0565cd11
FireAmpersand/231PythonProjects
/ex6.py
406
3.9375
4
def replace(s , old , new): "Replaces the old letter with the new one" word = s.split(old) newWord = new.join(word) print(newWord + "\n") return(newWord) def testSuite(): print("Mississippi","i","I") replace("Mississippi","i","I") s = "I love spom! Spom is my favorite food. Spom, spom, yum!" print(s,"om", "am") s = replace(s, "om", "am") print(s, "o","a") replace(s,"o","a") testSuite()
4a009a684956c1d21060c660e04db79ba7b287d5
JasonJieJay/0211
/0219-01.字符串操作.py
519
3.671875
4
#coding=utf-8 a='hello big chui!' print(a[0]) print(a[-2]) #print(a[30]) #切片 print(a[0:4]) print(a[:4]) print(a[4:]) print(a[3:-1]) print('*****************') #字符串的拼接 m='simida' n='kangsang' print(n+m) print(n,m) #字符串的遍历 for i in m: print(i) #成员运算 if 'i' in m: print('i is here') #去空格 #strip() 取消所有空格 #lsrtip() 去掉左边空格 #rstrip() 去掉右边空格 a=' yo girl ,look at me! ' print(a.strip()) print(a.lstrip()) print(a.rstrip())
7c06ca915aaa4a0ed4a15a28ff17934f9b243f74
czunigamunoz/ahorcado_python
/juego.py
5,707
3.671875
4
from tkinter import * from tkinter import Canvas from random import randint from tkinter.messagebox import* letrasUsadas=[] vidas=6 letrasAcertadas=0 ''' Verifica si la letra que se ingreso en el entry pertenece a la palabra del archivo plano y cuantas veces esta ''' def probarletra(): global vidas global letrasAcertadas letrasUsadas.append(letraObtenida.get()) # Agrega a la lista letrasUsadas la letra que ingreso el usuario conjuntoLetras[ord(letraObtenida.get())-97].config(text="") # ord nos permite pasar de caracter a su parte entera - quita la letra que digito el usuario if letraObtenida.get() in palabra: if palabra.count(letraObtenida.get())>1: # Comprueba si la letra esta mas de una vez en la palabra letrasAcertadas+=palabra.count(letraObtenida.get()) # Cuantas veces esta la letra en la palabra y aumenta el contador de letras acertadas for i in range(len(palabra)): if palabra[i]==letraObtenida.get(): # Verifica la poisicion donde esta la letra obtenida guiones[i].config(text=""+letraObtenida.get()) # Anexa la letra obtenida else: # Si solo hay una letra en la palabra letrasAcertadas+=1 guiones[palabra.index(letraObtenida.get())].config(text=""+letraObtenida.get()) # Anexa la letra obtenida - index le da ubicacion de la letra en la palabra if letrasAcertadas==len(palabra): # Verifica si el numero de las letras acertadas es el mismo a la longitud de la palabra showwarning(title="Victoria", message= "Adivinaste la palabra!!!!") else: # Sino se baja una vida y se pinta una parte del cuerpo vidas-=1 dibujar_cuerpo() if vidas ==0: showwarning(title="Derrota",message= "se te han acabado las vidas") letra.delete(0, 'end') letra.focus() # funcion para acomodar las letras del abcedaria en el frame def colocarLetras(): x=50 y=150 contador=0 Label(juego,text="Letras sin usar", bg="darkred", fg="white", font=("Arial italic", 15)).place(x=50,y=80) for i in range(26): # contador+=1 conjuntoLetras[i].place(x=x,y=y) #Le da la posicion en X y Y a las letras del abcedario x+=30 if contador==5: # Cuando llega a 5 aumenta su eje Y y en X se reinicia y+=35 contador=0 x=50 def dibujar_cuerpo(): if vidas == 5: # Cabeza canvas.create_oval(200, 90, 270, 160, width=4, outline="black") elif vidas == 4: # Cuerpo canvas.create_rectangle(235, 160, 245, 350, fill="black") elif vidas == 3: # Brazo izquierdo canvas.create_line(200, 230, 235, 175, width=5, fill="black") elif vidas == 2: # Brazo derecho canvas.create_line(245, 175, 280, 230, width=5, fill="black") elif vidas == 1: # pierna izquierda canvas.create_line(200, 440, 235, 350, width=5, fill="black") elif vidas == 0: # pierna derecha canvas.create_line(245, 350, 280, 440, width=5, fill="black") # Crea la raiz donde se va a configurar el tkinter tablero = Tk() tablero.title("AHORCADO") tablero.iconbitmap("Anonyymous.ico") tablero.config(relief="groove", bd=10) tablero.resizable(False, False) # Lee el archivo plano donde estan las palabras a adivinar archivo=open("palabras.txt","r") conjuntopalabras=list(archivo.read().split("\n")) # Crea una lista de las palabras que encontro en el archivo plano palabra = conjuntopalabras[randint(0, len(conjuntopalabras)-1)].lower() # Toma una palabra aleatoriamente de la lista y las convierte a minuscula letraObtenida=StringVar() # almacena como variable la letra que digito el usuario # Cuadro izquierdo del juego juego = Frame(tablero) juego.config(width=550, height=600, relief="sunken", bd=15, bg="darkred") juego.grid_propagate(False) juego.pack(side=LEFT, anchor=W, fill=BOTH) letrero = Label(juego, text="Ingresar letra", font=("Verdana", 20), bg="darkred", fg="white") letrero.grid(row=0, column=0, padx=10, pady=10) letra = Entry(juego, width=2, font=("Vedana", 24), textvariable=letraObtenida) letra.grid(row=0, column=1, padx=10, pady=10) btn_probar = Button(juego, text="Probar", bg="darkgray", bd= 5, width=10, height=2, command=probarletra) btn_probar.grid(row=1, column=1, pady=10) btn_salir = Button(juego, text="Salir", bg="darkgray", bd=5, width=10, height=2, command=tablero.destroy).place(x=320, y=70) # Importa la imagen del ahorcado from tkinter import PhotoImage foto = PhotoImage(file="ahorcado.png") Label(juego, image=foto).place(x=250, y=150) # Crea el contenedor del canvas dibujo = Frame(tablero) # Tablero derecho dibujo.pack(side=RIGHT, anchor=E) # Lo ubica en el lado derecho en la direccion Este dibujo.config(relief="sunken", bd=15, bg="black") # Crea el linezo donde se va a dibujar canvas = Canvas(dibujo, width=500, height=600, bg="darkred") canvas.pack(expand=YES, fill=BOTH) guiones=[Label(juego,text="_", font=("Arial italic",25), bg="darkred") for _ in palabra ] cordenadaX=50 for i in range(len(palabra)): guiones[i].place(x=cordenadaX,y=450) #Dependiendo del numero de letras de la palabra, va colocando guiones cordenadaX+=50 conjuntoLetras=[Label(juego,text=chr(j+97),font=("Arial italic",20), bg="darkred", fg="white", padx=5) for j in range(26)] # Conjunto de letras del abcdario colocarLetras() # Tronco del conlagero canvas.create_rectangle(450, 50, 470, 550, fill="black") # Linea que va hacai la izquierda canvas.create_rectangle(230, 30, 470, 50, fill="black") # Linea que representa la soga canvas.create_rectangle(230, 50, 250, 90, fill="black") tablero.mainloop()
4aabc7df24869143d5018d3d0e757e0704b90061
jgbarreda/software-para-construccion
/objeto_hueco.py
1,111
3.9375
4
''' En este ejemplo he creado una clase hueco, con un atributo 'tipo' que puedes definir como un string y un constructor con la medidas del hueco. Los métodos alfeizar y carpintería te dan las medidas de estos elementos en un string''' class Hueco: tipo='' def __init__(self, a, b): self.ancho = a self.alto = b def __str__(self): return 'Hueco tipo ' + self.tipo + ' de medidas ' + str(self.ancho) + ' x ' + str(self.alto) def alfeizar(self): alfeizar=self.ancho return 'La piedra de alfeizar mide ' + str(alfeizar) + ' metros' def carpinteria(self): carpinteria=float('{0:.4f}'.format(self.ancho*self.alto)) return 'la carpinteria mide ' + str(carpinteria) + ' m2.' def mide_hueco(a,b): v1=Hueco(a,b) alf=v1.alfeizar() carp=v1.carpinteria() return alf + ' y ' + carp if __name__ == "__main__": print(mide_hueco(0.8, 1.4))
27d0745e6199185dc5b1fb8d9739b2d0226fd606
letaniaferreira/guessinggame
/game.py
1,554
4.1875
4
"""A number-guessing game.""" # greet player # get player name # choose random number between 1 and 100 # repeat forever: # get guess # if guess is incorrect: # give hint # increase number of guesses # else: # congratulate player import random name = raw_input("Welcome, what is your name? ") greeting = "Hello, %s, do you want to play a guessing game? " %(name) print greeting best_score = "" def number_game(): random_number = random.randint(1,100) user_guess = 0 count = 0 while user_guess != random_number: user_guess = raw_input("Guess a number from 1 to 100: ") try: user_guess = int(user_guess) #break except ValueError: print("Oops! That was an invalid number. Rounding number.") user_guess = int(float(user_guess)) print user_guess if user_guess > random_number: print "Your guess is too high!" count += 1 elif user_guess < random_number: print "Your guess is too low!" count += 1 elif user_guess < 1 or user_guess > 100: print "Please enter a number between 1 and 100." count += 1 else: print "Well done, %s, You found the number in %s trials!" %(name,count) return count number_game() # keep track of best score greeting = raw_input("Would you like to play another round: ") if greeting == 'yes': number_game() # if count < best_score: else: print "goodbye"
24200966c29778f717b014e37e55b0d0ba7576fb
psshankar64/PiGitFolderFDC
/Tutorial_Backup/Tutorial_4/justcode_bouncingblits.py
4,325
3.6875
4
''' This script loads an image, creates ball objects and then bounces them around the display surface ''' import sys import random import math import pygame import pygame.gfxdraw from pygame.locals import * pygame.init() ''' DISPLAY SETUP -------------------------------------------------------------------------------- DISPLAY SETUP ''' DISPLAY_WIDTH = 1240 DISPLAY_HEIGHT = 720 DW_HALF = DISPLAY_WIDTH / 2 DH_HALF = DISPLAY_HEIGHT / 2 DISPLAY_AREA = DISPLAY_WIDTH * DISPLAY_HEIGHT DS = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT)) ''' LOAD IMAGES ---------------------------------------------------------------------------------- LOAD IMAGES ''' # Load the image from a file # Supported formats are JPEG, PNG, GIF BALL = pygame.image.load('colorwheel_100.png') # Get the dimensions of the image by calling the Surface get_rect() function R = BALL.get_rect() ''' DATA TABLES ---------------------------------------------------------------------------------- DATA TABLE ''' # this list defines the direction vector for the ball to travel in. There are 360 possible directions D2R = (math.pi * 2) / 360 # this converts radians to degrees DIRECTION_VECTOR_LOOKUP = list([[math.cos(D2R * degrees), math.sin(D2R * degrees)] for degrees in xrange(360)]) ''' FUNCTIONS AND CLASSES ------------------------------------------------------------------------ FUNCTIONS AND CLASSES ''' # define the ball class class ball: x = 0.0 y = 0.0 def __init__(self, r = R): # because the script generations random positions for x, y it needs to know the x and y limits of those boundries global DISPLAY_WIDTH, DISPLAY_HEIGHT, DIRECTION_VECTOR_LOOKUP self.r = r # grab the image.get_rect() dimensions for use when drawing the image # randomly assign the x and y position to somewhere in the display surface self.x += random.randint(r.center[0], DISPLAY_WIDTH - r.center[0]) self.y += random.randint(r.center[1], DISPLAY_HEIGHT - r.center[1]) # define the direction vector based on 360 degrees self.dx, self.dy = DIRECTION_VECTOR_LOOKUP[random.randint(0, 359)] def draw(self, ds = DS, image = BALL): # this function draws the ball image centralised at its x, y coordinates # remember .center[0] = image.width / 2 and .center[1] = image.height / 2 ds.blit(image, (self.x - self.r.center[0], self.y - self.r.center[1])) def move(self): global DISPLAY_WIDTH, DISPLAY_HEIGHT # this function moves the ball by adding the direction vector to the x and y coords then checks to see # if the ball has hit the sides of the display surface. if it has then change the direction of the ball # add the direction vector to the x, y coordinates self.x += self.dx self.y += self.dy # check if either the left or right side of the display surface has been 'hit' # and if true then switch the horizontal direction of the ball if self.x <= self.r.center[0] or self.x >= DISPLAY_WIDTH - self.r.center[0]: self.dx = -self.dx # check if either the top or bottom of the display surface has been 'hit' # and if true then switch the vertical direction of the ball if self.y <= self.r.center[1] or self.y >= DISPLAY_HEIGHT - self.r.center[1]: self.dy = -self.dy def do(self): self.move() self.draw() def event_handler(): for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() ''' DEFINE BALLS --------------------------------------------------------------------------------- DEFINE BALLS ''' # define the number of balls nBALLS = 20 #create a list of balls BALLS = list([ball() for count in xrange(nBALLS)]) ''' MAIN LOOP ------------------------------------------------------------------------------------ MAIN LOOP ''' while True: event_handler() # iterate through the balls drawing and moving each in turn for b in BALLS: b.do() pygame.display.update() # it's important in the this script to clear the display surface after updating # overwise you'll see a trail of images as it moves from one side of the display # surface to the other. Try deleting the line below and running the script again! DS.fill([0,0,0])
033e0562f0ef0da6b48a768f2bff23238e5aeb52
psshankar64/PiGitFolderFDC
/Tutorial_Backup/Tutorial_3/justcode_random_rect.py
1,836
3.765625
4
# This script will randomly place rectangles on the display surface, each with a random color # WARNING: if you suffer from photo-sensitive epilepsy then I'd not recommend running this script! import sys import random import math import pygame import pygame.gfxdraw from pygame.locals import * #Define some standard colors FUCHSIA = (255, 0, 255) PURPLE = (128, 0, 128) TEAL = (0, 128, 128) LIME = (0, 255, 0) GREEN = (0, 128, 0) OLIVE = (128, 128, 0) YELLOW = (255, 255, 0) ORANGE = (255, 165, 0) RED = (255, 0, 0) MAROON = (128, 0, 0) SILVER = (192, 192, 192) GRAY = (128, 128, 128) BLUE = (0, 0, 255) NAVY = (0, 0, 128) AQUA = (0, 255, 255) WHITE = (255, 255, 255) BLACK = (0, 0, 0) pygame.init() DISPLAY_WIDTH = 1280 DISPLAY_HEIGHT = 720 DISPLAY_AREA = DISPLAY_WIDTH * DISPLAY_HEIGHT DS = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT)) # FUNCTIONS ------------------------------------------------------------------------------------------------ FUNCTIONS def event_handler(): for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() while True: event_handler() # create the random color (R, G, B), remember red, green and blue values are 0-255, 0 = DARKEST, 255 = BRIGHTEST rgb = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # create random coordinates and dimensions for the rectangles. w = random.randint(0, DISPLAY_WIDTH - 1) h = random.randint(0, DISPLAY_HEIGHT - 1) x = random.randint(0, DISPLAY_WIDTH - w) y = random.randint(0, DISPLAY_HEIGHT - h) # draw the rectangle on the display surface pygame.draw.rect(DS, rgb, (x, y, w, h), 0) # update the display surface so we can see the changes pygame.display.update()
24b374d64dfab5739802512709e3f299f5692199
juannumo/Momento2_NuevTecn
/momento2_2.py
521
3.84375
4
# 2. Escribir una función que cuente la cantidad de apariciones de cada carácter en una cadena de texto, y los devuelva en un diccionario. from collections import defaultdict texto2 = "esto es un ensayo para contar caracteres" contador = defaultdict(int) for c in texto2: if(c.isalpha()): contador[c] += 1 for c in sorted(contador, key=contador.get, reverse=True): if contador[c] > 2: # print(texto2.replace(' ','')) print('el caracter %s se repite %i' % (c, contador[c]))
395f4ef257a4edea0f608d00a21825391d5c9719
12qw1q2w/Solving-SE-with-DL
/01_random_fourier.py
466
3.640625
4
import numpy as np import matplotlib.pyplot as plt N = 100 def summation(f, n0, N): s = 0 for n in range(n0, N+1): s += f(n) return s def random_fourier(x, nmax): a = np.random.random(nmax+1)-0.5 b = np.random.random(nmax+1)-0.5 return summation(lambda n: a[n]*np.sin(n*np.pi*x) + b[n]*np.cos(n*np.pi*x), 0, nmax) x = np.linspace(0, 1, N+1) while True: plt.plot(x, random_fourier(x, np.random.randint(0, 32))) plt.show()
770f554dff3a6a44359af3b86c26a3f8d17188e9
lipengyuan1994/computer-science-station
/MITx-6.00.1x/problem set2/q2.py
889
4.03125
4
balance = 4773 annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12 monthlyPayment = 0 updatedBalance = balance counter = 0 # Will loop through everything until we find a rate that will reduce updatedBalance to 0. while updatedBalance > 0: # Was stated that payments needed to happen in increments of $10 monthlyPayment += 10 # To reset balance back to actual balance when loop inevitably fails. updatedBalance = balance month = 1 # For 12 months and while balance is not 0... while month <= 12 and updatedBalance > 0: # Subtract the ($10*n) amount updatedBalance -= monthlyPayment # Compound the interest AFTER making monthly payment interest = monthlyInterestRate * updatedBalance updatedBalance += interest # Increase month counter month += 1 counter += 1 print("Lowest Payment: ", monthlyPayment) #print("Number of iterations: ", counter)
05d6b70390bafc07721444c4d81a729fcacce719
Rapt0r399/HackerRank
/Python/Strings/Find a string.py
202
3.59375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT s1 = raw_input() s2 = raw_input() count =0 for i in range (0, len(s1)-2) : if(s1[i:i+len(s2)]==s2) : count = count+1 print count
734393a5223b988fda14b57c5d7d1595509744c6
puzzleVerma/numerical-methods
/regula_falsi.py
994
3.859375
4
def factorial(a): result = 1 for i in range(1, a+1): result = result * i return result def e(n): e = 0.0 for i in range(0, n + 1): e = e + (1/factorial(i)) # print("iteration -", i, " ", e) return e #print(e(10)) def f(x): # return (e(10)**x) - (5*(x)**2) # return(x**3 - 2*(x)**2 - 5) return (x**3 - x - 2) EPSILON1 = 0.00001; EPSILON2 = 0.000001; #a = 0 #b = 1 #a = 2 #b = 3 a = 1 b = 2 c = b - (f(b) * (b-a)/(f(b) - f(a))) count = 0 lebar = c #while count <= 21: while abs(a-b) >= EPSILON1: c = b - (f(b) * (b-a)/(f(b) - f(a))) if abs(f(c)) < EPSILON2: a = c b = c else: if f(a) * f(c) < 0: b = c else: a = c print(count, "{0:.6f}".format(a), "{0:.6f}".format(c), "{0:.6f}".format(b),"{0:.6f}".format(f(a)), "{0:.6f}".format(f(c)), "{0:.6f}".format(f(b)), "{0:.6f}".format(lebar)) lebar = abs(a - b) count = count + 1
fcb90c66edc8178db5934fdf86061120a16cff9a
borislavtotev/SoftUni-Python
/Exam/04_city_with_empty_data.py
1,401
3.78125
4
import csv import iso8601 from datetime import date try: file_name = 'city-temperature-data.csv' #input() cities = set() data = {} with open(file_name, encoding='utf-8') as f: for line in f: line = line.strip() if line: line_elements = line.split(',') date_string = str(line_elements[0]) date_elements = date_string.split('-') dt = date(int(date_elements[0]), int(date_elements[1]), int(date_elements[2])) city = line_elements[1] cities.add(city) temperature = float(line_elements[2]) if dt in data: data[dt].append(city) else: data[dt] = [city] found_empty_cities = False if not cities: raise ValueError() for date in sorted(data.keys()): missing_cities = [] current_cities = set(data[date]) # missing_cities = cities.difference(current_cities) missing_cities = [city for city in cities if city not in current_cities] if missing_cities: print("{},{}".format(date.isoformat(), ",".join(sorted(missing_cities)))) found_empty_cities = True if not found_empty_cities: print("ALL DATA AVAILABLE") except: print("INVALID INPUT")
0db51041a8cee9c2550908fd41b2c07ae0294e25
borislavtotev/SoftUni-Python
/Lecture1/firstExample.py
117
3.578125
4
test = "alabalanica turska panica" if len(test) > 10: print(''.join(test[0:10]) + '...') else: print test
8864c82483aeec033fa453c2245866c96f41aaa4
vokoramus/GB_python1_homework
/Homework__5/HW5_4.py
1,264
3.75
4
''' 4. Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл. ''' en_ru_dict = { "one": "один", "two": "два", "three": "три", "four": "четыре", } with open("HW5_4_text.txt", 'r', encoding="utf-8") as f_in, \ open("HW5_4_out.txt", 'w', encoding="utf-8") as f_out: for line in f_in.readlines(): words_list = line.rstrip().split() print("=" * 20) print(words_list) for w in words_list: w_lower = w.lower() print(w_lower) if w_lower in en_ru_dict: idx = words_list.index(w) words_list.insert(idx, en_ru_dict[w_lower].capitalize()) words_list.pop(idx + 1) f_out.write(" ".join(words_list) + "\n")
8a128cd92a015b23e48966c5b77a5d803761b9e1
vokoramus/GB_python1_homework
/Homework__5/HW5_3.py
1,007
4.09375
4
'''3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников.''' salary_average, salary_sum = 0, 0 n, n_min = 0, 0 SALARY_MIN = 20000 with open("HW5_3_text.txt", 'r', encoding="utf-8") as f: for line in f.readlines(): n += 1 data = line.strip().split() surname = data[0] salary = int(data[1]) salary_sum += salary if salary < SALARY_MIN: n_min += 1 print(surname) try: salary_average = salary_sum / n print(f"salary_average = {salary_average:.2f}", ) except ZeroDivisionError: print("There is no staff in your file")
005743d2ecbfe890ae852dffdec1c4e7779cdff8
vokoramus/GB_python1_homework
/Homework__4/HW4_4.py
781
3.84375
4
''' Представлен список чисел. Определите элементы списка, не имеющие повторений. Сформируйте итоговый массив чисел, соответствующих требованию. Элементы выведите в порядке их следования в исходном списке. Для выполнения задания обязательно используйте генератор. Пример исходного списка: [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11]. Результат: [23, 1, 3, 10, 4, 11] ''' list_1 = [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11] list_2 = [list_1[i] for i in range(len(list_1)) if list_1.count(list_1[i]) == 1] print(list_2)
567566abb3fad5fb82f4944fb222941988bf8fc8
vokoramus/GB_python1_homework
/Homework__1/HW1-4.py
458
4.25
4
'''4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.''' n = int(input("Введите n: ")) max_char = n % 10 while n > 0: last_chr = n % 10 if last_chr > max_char: max_char = last_chr n //= 10 print("max =", max_char)
edf2dc110ef2e76abd0f62335249dfaee1396ae4
dnlarson/Reverse_complement_DNA
/DNA-example.py
2,152
4.0625
4
#!/usr/bin/env python3 """ Author: Danielle Larson Purpose: Output the reverse-complement of the given DNA strand """ import os import sys import argparse # -------------------------------------------------- def get_args(): """get arguments""" parser = argparse.ArgumentParser( description='Reverse complement the DNA strand', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # parser.add_argument('STR', help='DNA strand', type = str, metavar = 'STR') parser.add_argument( '-o', '--outfile', action='store', dest='outfile', help = 'File of the Reversed DNA strand', metavar = "FILE", default = "out.txt") parser.add_argument( '-d', '--DNA', action='store', required = True, dest='DNA', help = 'File with DNA strand', metavar = "FILE", default = "DNA.txt") return parser.parse_args() # -------------------------------------------------- def main(): """main""" args = get_args() outfile = args.outfile DNA = args.DNA if not os.path.isfile(DNA): die('"{}" is not a DNA strand'.format(DNA)) output = '' with open("DNA.txt", "r") as f: DNA = f.readline() # print(DNA) for letter in DNA: if letter == 'A': output = 'T' + output elif letter == 'T': output = 'A' + output elif letter == 'C': output = 'G' + output elif letter == 'G': output == 'C' + output # print(output) with open(outfile, "w") as f: f.write(output) print('Output file written to "{}"'.format(outfile)) # -------------------------------------------------- def warn(msg): """Print a message to STDERR""" print(msg, file=sys.stderr) # -------------------------------------------------- def die(msg='Something bad happened'): """warn() and exit with error""" warn(msg) sys.exit(1) # -------------------------------------------------- if __name__ == '__main__': main()
11e76a2cdb4033107a6c3bb44b435d002c2edefd
SaishNarvekar/recommendation-system
/server/itinerary.py
2,052
3.546875
4
from server.route import Route from server.connection import Connection from server.util import Util util = Util() class Itinerary: def __init__(self,travelType,days,prefernce,state): self.travelType = travelType self.days = days self.prefernce = prefernce self.state = state self.output = {} def getItinerary(self): i = 0 if self.state == 'Goa': if self.travelType == 'Airway': route = Route('Vasco da Gama',self.days,self.prefernce,self.state) #List will get created by user and filled with data from front end itinerary = route.GameOver() self.output[i] = util.formatedOutput(itinerary) return self.output if self.travelType == 'Railway': route = Route('Vasco da Gama',self.days,self.prefernce,self.state) itinerary = route.GameOver() self.output[i] = util.formatedOutput(itinerary) i+=1 route = Route('Colva Beach',self.days,self.prefernce,self.state) #List will get created by user and filled with data from front end itinerary = route.GameOver() self.output[i] = util.formatedOutput(itinerary) return self.output if self.state == 'Rajasthan': if self.travelType == 'Airway': route = Route('Jaswant Thada',self.days,self.prefernce,self.state) #List will get created by user and filled with data from front end itinerary = route.GameOver() self.output[i] = util.formatedOutput(itinerary) return self.output if self.travelType == 'Railway': route = Route('Jaigarh Fort',self.days,self.prefernce,self.state) itinerary = route.GameOver() self.output[i] = util.formatedOutput(itinerary) return self.output
2b6a314f7e7ea8b26c44c84db441fa98095e84fc
noveoko/thecalculatorgamesolver
/parse.py
551
3.78125
4
import re def parse_all(string): regex = re.compile(r"((?P<add>\+\d+)|(?P<multiply>x\d+)|(?P<divide>\/\d+)|(?P<balance>\(\d+\))|(?P<subtract>\-\d+)|(?P<remove_digit>\<\<)|(?P<first_digit_to_second>(\d+)\=\>(\d+))|(?P<insert_number>\d))") match = regex.match(string) groups = match.groupdict() return [(a[0],only_numbers(a[1])) for a in groups.items() if a[1] != None][-1] def only_numbers(string): all_nums = [int(a) for a in re.sub('[^0-9]+',",", string).split(",") if a] return all_nums if __name__ == "__main__": pass
cd6dd1fe1eb4dc3b1f8a392b57423896da780acc
adams164/python-problems
/Digital-Dice/Gamow-Stern-elevator.py
1,334
3.546875
4
import numpy as np #When waiting at the 2nd floor in a 7 story building, what is the probability that the first elevator to arrive comes from above? #Simulate waiting for an elevator, returning true if it arrives from above. def fromAbove(numFloors,numElevators): rng = np.random.default_rng() elevatorPositions = rng.random((numElevators,2)) elevatorDistances = np.zeros(numElevators) for eIndex in range(numElevators): if elevatorPositions[eIndex,0] < 1/(numFloors-1): if elevatorPositions[eIndex,1] < 0.5: elevatorDistances[eIndex] = 1/(numFloors-1) + elevatorPositions[eIndex,0] else: elevatorDistances[eIndex] = 1/(numFloors-1) - elevatorPositions[eIndex,0] else: if elevatorPositions[eIndex,1] < 0.5: elevatorDistances[eIndex] = elevatorPositions[eIndex,0] - 1/(numFloors-1) else: elevatorDistances[eIndex] = 2 - elevatorPositions[eIndex,0] - 1/(numFloors-1) closestElevator = np.argmin(elevatorDistances) return elevatorPositions[closestElevator,0]>(1/(numFloors-1)) elevatorCount = 3 sampleCount = 100000 floorCount = 7 aboveCount = 0 for i in range(sampleCount): if fromAbove(floorCount,elevatorCount): aboveCount += 1 print(aboveCount/sampleCount)
dd8701107b306c12fd49dcb864ce35d29bc517c9
dk88/leet_practise_py
/src/binary_tree.py
4,867
3.859375
4
# encoding:utf-8 import sys __author__ = 'zhaoxiaojun' reload(sys) sys.setdefaultencoding('utf-8') # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def pre_order_traversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] if root: res.append(root.val) res += self.pre_order_traversal(root.left) res += self.pre_order_traversal(root.right) return res def mid_order_traversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] if root: res += self.mid_order_traversal(root.left) res.append(root.val) res += self.mid_order_traversal(root.right) return res def post_order_traversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] if root: res += self.post_order_traversal(root.left) res += self.post_order_traversal(root.right) res.append(root.val) return res def pre_order_traversal_literal(self, root): """ :type root: TreeNode :rtype: List[int] """ stack = [] res = [] while stack or root: while root: res.append(root.val) stack.append(root) root = root.left root = stack.pop() root = root.right return res def mid_order_traversal_literal(self, root): """ :type root: TreeNode :rtype: List[int] """ stack = [] res = [] while stack or root: while root: stack.append(root) root = root.left root = stack.pop() res.append(root.val) root = root.right return res def post_order_traversal_literal(self, root): """ :type root: TreeNode :rtype: List[int] """ stack = [] res = [] flag_list = [] while stack or root: while root: stack.append(root) flag_list.append(0) root = root.left root = stack.pop() flag = flag_list.pop() if flag == 0: stack.append(root) flag_list.append(1) root = root.right else: res.append(root.val) root = None return res def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if not t1 and not t2: return None if not t1 and not t2: return t2 if t1 and not t2: return t1 if t1 and t2: t3 = TreeNode(t1.val if t1 else 0 + t2.val if t2 else 0) t3.left = self.mergeTrees(t1.left, t2.left) t3.right = self.mergeTrees(t1.right, t2.right) return t3 def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ if not root: return root if root.val > R: return self.trimBST(root.left, L, R) elif root.val < L: return self.trimBST(root.right, L, R) else: root.left = self.trimBST(root.left, L, R) root.right = self.trimBST(root.right, L, R) return root if __name__ == '__main__': # root = TreeNode(1) # root.left = TreeNode(2) # root.right = TreeNode(3) # root.left.left = TreeNode(4) # root.left.right = TreeNode(6) # root.left.left.right = TreeNode(5) # root.left.right.left = TreeNode(7) # so = Solution() # print so.pre_order_traversal(root) # print so.pre_order_traversal_literal(root) # print so.mid_order_traversal(root) # print so.mid_order_traversal_literal(root) # print so.post_order_traversal(root) # print so.post_order_traversal_literal(root) so = Solution() # root1 = TreeNode(1) # root1.left = TreeNode(3) # root1.left.left = TreeNode(5) # root1.right = TreeNode(2) # # root2 = TreeNode(2) # root2.left = TreeNode(1) # root2.left.right = TreeNode(4) # root2.right = TreeNode(3) # root2.right.right = TreeNode(7) # print so.mergeTrees(root1, root2) root = TreeNode(3) root.left = TreeNode(0) root.right = TreeNode(4) root.left.right = TreeNode(2) root.left.right.left = TreeNode(1) new_root = so.trimBST(root, 1, 3) print so.mid_order_traversal(new_root)
7c9c2eb4f86bc4cc3df032d855dcf8b12ed32312
Brown0101/python_scripts
/reports/CSV_XLSX/convert_csv_to_xlsx_format.py
1,285
3.515625
4
import sys import csv import os import xlsxwriter # Get file name without extension file_name = os.path.splitext(os.path.basename(r"<file_location.csv>"))[0] + '.xlsx' # if we read f.csv we will write f.xlsx wb = xlsxwriter.Workbook("<filename_you_choose.xlsx") ws = wb.add_worksheet(file_name) # your worksheet title here # add background format color format1 = wb.add_format({'bg_color' : '#000033', 'bold': True, 'font_size' : 16, 'font_color': 'white', 'valign': 'vcenter'}) format2 = wb.add_format({'bg_color' : '#F0F0F0'}) # use this to determine the format to be used. flag = 'format2' with open(r'<file_location.csv>','r') as csvfile: table = csv.reader(csvfile) i = 0 # write each row from the csv file as text into the excel file # this may be adjusted to use 'excel types' explicitly (see xlsxwriter doc) for row in table: if '<Spreadsheet_Title_Name>' in row: ws.merge_range('A1:H1', "", format1) ws.write_row(i, 0, row, format1) elif not row: continue else: if flag == 'format2': ws.write_row(i, 0, row, format2) flag = '' else: ws.write_row(i, 0, row) flag = 'format2' i += 1 wb.close()
1532020913bb3d12e049d871a9d544fb0d5f4abc
KD4/TIL
/Algorithm/merge_two_sorted_lists.py
1,227
4.1875
4
# Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. # splice 꼬아 잇다 # 주어준 링크드리스트 두 개를 하나의 리스트로 만들어라. 두 리스트의 노드들을 꼬아서 만들어야한다. # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: cur = None result = None while l1 is not None or l2 is not None: if l2 is None or (l1 is not None and l1.val < l2.val): if result is None: result = l1 cur = l1 l1 = l1.next else: cur.next = l1 cur = l1 l1 = l1.next else: if result is None: result = l2 cur = l2 l2 = l2.next else: cur.next = l2 cur = l2 l2 = l2.next return result
c86b88b4c4f461561ad8030a64bfc7bd6dff4afa
Feynming/python_learning
/try_except.py
309
3.59375
4
#try except finally try: print('try...') x = 10 / 0 print('result:', x) except ZeroDivisionError as e: print("except:", e) finally: print("finally") print("End...") #raise def MyError(ValueError): pass def foo(s): n = int(s) if n == 0: raise MyError("invalid value:%s" % s) return 10 / n foo("0")
973fb85e4536fd264b43dc99339eb3c23310cebe
Feynming/python_learning
/dictSet.py
373
3.75
4
#dict常用api(大括号) d={'fey':'飞','ming':'明'} #print(d) print(d.get('fey')) d['sun']='孙' print(d) for (k,v) in d.items(): print("key:",k,"value:",v) #set s=set(range(10)) print(s) l=['fey','ming','sun','n'] t=set(s.upper() for s in l if isinstance(s,str)) print(t) t.add('HA') from collections import Iterable print(isinstance((),Iterable)) print("abs is",abs)
a5b4d29025f3141ca47057696c33a803958567ea
DevinKlepp/leetcode
/Easy/Tree/question98.py
621
3.765625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # https://leetcode.com/problems/validate-binary-search-tree/solution/ class Solution: def isValidBST(self, root): return self.check(root, float("-inf"), float("inf")) def check(self, root, left, right): if not root: return True if not left < root.val < right: return False return self.check(root.left, left, root.val) and self.check(root.right, root.val, right)
e7b86176bd6ed8aa3677c438ad41b29cdc89c720
DevinKlepp/leetcode
/Easy/Basic Logic/question88.py
531
3.671875
4
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: i, j = 0, 0 while n > 0 and m > 0: if nums1[m - 1] > nums2[n - 1]: nums1[m + n - 1] = nums1[m - 1] m -= 1 else: nums1[m + n - 1] = nums2[n - 1] n -= 1 if n > 0: # Reaches this if the first int in nums1 is larger than the rest in nums2 nums1[:n] = nums2[:n] # take the rest from nums2 and put them on the front
a6609406b527bae70d5176900ebbf350d785417f
tbrotz/ProjectEuler
/Problem0047.py
1,241
3.59375
4
#~ Distinct primes factors #~ Problem 47 #~ The first two consecutive numbers to have two distinct prime factors are: #~ 14 = 2 * 7 #~ 15 = 3 * 5 #~ The first three consecutive numbers to have three distinct prime factors are: #~ 644 = 2^2 * 7 * 23 #~ 645 = 3 * 5 * 43 #~ 646 = 2 * 17 * 19. #~ Find the first four consecutive integers to have four distinct prime factors. What is the first of these numbers? import math import itertools def sieve(n): "Return all primes <= n." np1 = n + 1 s = list(range(np1)) # leave off `list()` in Python 2 s[1] = 0 sqrtn = int(round(n**0.5)) for i in xrange(2, sqrtn + 1): # use `xrange()` in Python 2 if s[i]: # next line: use `xrange()` in Python 2 s[i*i: np1: i] = [0] * len(xrange(i*i, np1, i)) return filter(None, s) p=set(sieve(1000000)) def is_prime(n): return n in p pl=list(sieve(1000000)) min=1000000 l=[set([]) for i in range(0,1000000)] for i in pl: j=1 while (j*i<1000000): l[j*i]|=set([i]) if len(l[j*i])==4: if len(l[i*j-1])==4: if len(l[i*j-2])==4: if len(l[i*j-3])==4: if (i*j-1)<min: min=i*j-3 j+=1 print(min)
620f7c0b48e2c62ef6ce6a062d08b663c272bef9
tbrotz/ProjectEuler
/Problem0043.py
1,237
3.5
4
#~ Sub-string divisibility #~ Problem 43 #~ The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. #~ Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: #~ d2d3d4=406 is divisible by 2 #~ d3d4d5=063 is divisible by 3 #~ d4d5d6=635 is divisible by 5 #~ d5d6d7=357 is divisible by 7 #~ d6d7d8=572 is divisible by 11 #~ d7d8d9=728 is divisible by 13 #~ d8d9d10=289 is divisible by 17 #~ Find the sum of all 0 to 9 pandigital numbers with this property. import math import itertools l = range(0,10) sums=0 for i in itertools.permutations(l,10): n=sum([i[j]*10**j for j in range(0,10)]) d234=int(n%(10**9) / 10**6) if d234%2!=0: continue; d234=int(n%(10**8) / 10**5) if d234%3!=0: continue; d234=int(n%(10**7) / 10**4) if d234%5!=0: continue; d234=int(n%(10**6) / 10**3) if d234%7!=0: continue; d234=int(n%(10**5) / 10**2) if d234%11!=0: continue; d234=int(n%(10**4) / 10**1) if d234%13!=0: continue; d234=int(n%(10**3)) if d234%17!=0: continue; sums+=n print(sums,n)
b6364e51af1472c1eec2b3bef4e9aa5d68f4e2e4
CHuber00/Simulation
/Sprint-1-Python_and_Descriptive_Statistics/Deliverables/MoreCalculations.py
2,014
4.25
4
""" Christian Huber CMS 380, Fall 2020 / Sprint 1 / MoreCalculations This script reads a text file's values and calculates and prints the mean, median, variance, and standard deviation. """ from math import sqrt import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt def mean(x): """ Calculate and return the mean of input list x """ return sum(x) / len(x) def median(x): """ Calculate and return the median of input list x """ values.sort() # Calculate mean for middle indexes for even set # Averaging middle two indexes if(len(x)%2==0): return ((x[int(len(x)/2)]+x[int(len(x)/2)-1])/2) # Referencing the middle index of uneven set else: return(x[(int(len(x)/2))]) def variance(x): """ Calculate and return the variance of input list x """ m = mean(x) # Create an array with the value of each (element - mean)^2 v = [((i-m)**2) for i in x] return mean(v) def sDeviation(x): """ Calculate and return the standard Deviation of input list x """ return sqrt(variance(x)) values = [] # Read all data from the file into value list with open("data.txt") as f: data = f.readlines() for line in data: # Remove trailing whitespace line = line.strip() values.append(float(line)) dataMean = mean(values) dataMedian = median(values) dataVariance = variance(values) dataSDeviation = sDeviation(values) # Use matlibplot to output boxplot and histogram to pdf plt.figure() plt.boxplot(values) plt.title("Data.txt Values visualization in Boxplot") plt.xlabel("Data") plt.ylabel("Values") plt.savefig("MoreCalculationsBoxplot.pdf", bbox_inches = "tight") plt.figure() plt.hist(values,20) plt.title("Data.txt Histogram") plt.xlabel("Value") plt.ylabel("Frequency") plt.savefig("moreCalculationsHistogram.pdf", bbox_inches = "tight")
c9a709465ac644fd3bf62e82d97f20b195f24cfc
CHuber00/Simulation
/Sprint-3-Monte_Carlo_Simulation/Deliverables/LesPoissons.py
1,522
3.890625
4
""" Christian Huber CMS 380, Fall 2020 / Sprint 3 / The Ticket Problem This script plots the results of a binomial process and the poisson pmf for a series of coin flips """ from random import random import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from math import e from math import factorial ### FUNCTIONS ### # Calculate poisson probability mass function for frequency of heads # Takes highest numer of heads as argument def ppmf(most_heads): pmf = [((e**(-25))*(25)**(x))/factorial(x) for x in range(most_heads)] return pmf # Plot frequencies of head occurences and pmf in one histogram def plot(num_heads, pmf): plt.figure() plt.hist(num_heads,bins=25,density=True) plt.plot(pmf) plt.title("Frequency of Event 'Heads' and Poisson PMF of Coin Flips") plt.xlabel("Frequency of Event 'Heads'") plt.savefig('les_poissons_hist_and_pmf.pdf', bbox_inches='tight') # Simulate coin flips with binomial distribution def binom(): heads_count = 0 for trial in range(1000): flip = random() if (flip <= 0.025): heads_count = heads_count + 1 return record # Simulate the experiment def simulate(): heads = list() for trial in range(1000): flips = binom() heads.append(flips) heads.sort() poisson = list() poisson = ppmf(heads[-1]) plot(heads, poisson) if __name__ == '__main__': simulate()
baa582d919fa1f8ce36e82cf17de8cebcde36c85
Jasoncho1125/PythonTest
/py_p114-1.py
267
3.6875
4
from datetime import datetime thisYear = datetime.today().year age = int(input("올해 나이는 : ")) nextAge = 2050 - thisYear + age + 1 print("올해는 " + str(thisYear) + "년 입니다.") print("2050년은 %s살 이시네요" % str((2050 - thisYear + age)))
43d77f6121e5932ca60a1490d3f26a0ea8a6cf63
katelynarenas/order_dog_food
/food_order.py
1,837
4.03125
4
MAX_CAPACITY = 30 #the maximum amount of dogs the shelter can hold SMALL_DOG_MULTIPLIER = 10 #the amount of food to order per small dog MEDIUM_DOG_MULTIPLIER = 20 #the amount of food to order per medium dog LARGE_DOG_MULTIPLIER = 30 #the amount of food to order per large dog def order_dog_food(small_dogs: int, medium_dogs: int, large_dogs: int, leftover_food: float) -> float: """ Calculates the amount of food to order for the month given the number of dogs in each size category, the leftover food from the previous month in lbs, and a 20% buffer Returns the total_order in lbs """ if not isinstance(small_dogs, int) or not isinstance(medium_dogs, int) or not isinstance(large_dogs, int): raise Exception( "Please enter whole numbers for each dog size category") if not isinstance(leftover_food, (int, float)): raise Exception( "Please enter a number for the amount of food in lbs leftover from the previous month." ) if small_dogs < 0 or medium_dogs < 0 or large_dogs < 0: raise Exception("Please enter 0 or more dogs for each size category") sum_dogs = small_dogs + medium_dogs + large_dogs if sum_dogs > MAX_CAPACITY: raise Exception( f"You've entered {sum_dogs} which is more dogs than the shelter's max capacity of {MAX_CAPACITY}. Please check your numbers and try again." ) minimum_order = (small_dogs * SMALL_DOG_MULTIPLIER) + (medium_dogs * MEDIUM_DOG_MULTIPLIER) + (large_dogs * LARGE_DOG_MULTIPLIER) #buffer order with 20% more than the minimum needed buffer_order = minimum_order * 1.2 #subtract the amount of food leftover from the previous month total_order = buffer_order - leftover_food if total_order < 0: total_order = 0 return total_order
3a362ffa47ce0f41a33420c216daea735dc32772
Pradeep-Sulam/ProjectEuler
/12_triangle_number.py
988
3.515625
4
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # Let us list the factors of the first seven triangle numbers: # 1: 1 # 3: 1,3 # 6: 1,2,3,6 # 10: 1,2,5,10 # 15: 1,3,5,15 # 21: 1,3,7,21 # 28: 1,2,4,7,14,28 # We can see that 28 is the first triangle number to have over five divisors. # What is the value of the first triangle number to have over five hundred divisors? i = 1 while i > 0: tri_number = 0 counter = 0 for j in range(1, i+1): tri_number = tri_number + j for k in range(1, tri_number + 1): if tri_number%k == 0: counter = counter + 1 print("triangle number ", tri_number, "counter =", counter, "i value", i) if counter >= 500: print(tri_number) break i = i+1 print(tri_number) # Actual output is 76576500 and the i value is 12375
996654eccdb296f862f69b1652bee2d0da7189f2
Pradeep-Sulam/ProjectEuler
/7_nth_prime_number.py
350
3.984375
4
number = int(input("Enter the number ")) n = 1 prime_number_list = [] while len(prime_number_list) < number: counter = 0 for i in range(1, n+1): if n % i == 0: counter = counter + 1 if counter == 2: prime_number_list.append(n) n = n + 1 print("Length - ", len(prime_number_list)) print(prime_number_list)
b134ea99ee47a894bfb0206b206731aaaa0df369
facundo-hm/my-idea-of-fun
/color_shape_text/color_shape_text.py
2,605
3.671875
4
from typing import Dict, Tuple, Iterable from itertools import product import string import random # 8-bit colors COLORS_AMOUNT = 256 MAX_COLORS_TO_COMPUTE = 36 ITERATION_NUM = 3 MAX_TEXT_LENGTH = round(MAX_COLORS_TO_COMPUTE / ITERATION_NUM) letters = list(string.ascii_lowercase) colors = tuple(range(COLORS_AMOUNT)) # Amount of colors per letter colors_per_letter = round(COLORS_AMOUNT / len(letters)) # Extract chunks of colors and assign them to each letter colors_by_letters: Dict[str, Tuple[int, ...]] = { letters[idx]: colors[color_code:color_code + colors_per_letter] for idx, color_code in enumerate( range(0, len(colors), colors_per_letter) ) } def combine_colors(text: str) -> Iterable[Tuple[int, ...]]: letter_tuples: List[Tuple[int, ...]] = [] text_length = len(text) choices_per_letter = round(MAX_TEXT_LENGTH / text_length) difference = MAX_TEXT_LENGTH - (choices_per_letter * text_length) text_iteration = [] for i in range(text_length): if difference > i: text_iteration.append(choices_per_letter + 1) continue if (difference + i) < 0: text_iteration.append(choices_per_letter - 1) continue text_iteration.append(choices_per_letter) # iterate over a fix range for _ in range(ITERATION_NUM): text_colors = [] for idx, letter in enumerate(text): # use letters to get colors in each iteration. # add cartain amount of colors per letter randomly. # no matter how big or small is the text, # always display the same amount of colors. color_choice = random.choices( colors_by_letters.get(letter, (0,)), k=text_iteration[idx] ) text_colors.extend(color_choice) letter_tuples.append(text_colors) return product(*letter_tuples) def generate_colors_output(text: str) -> str: final_string: str = '' # use text to generate numbers based on the letters indexes # use those numbers to insert blank points to create shapes for colors_product in combine_colors(user_text): for color_code in colors_product: final_string += '\033[48;5;{}m '.format(color_code) final_string += '\033[0m' return final_string while True: user_text: str = input("Enter text:") if len(user_text) <= MAX_TEXT_LENGTH: output = generate_colors_output(user_text) print(output) else: print('The text maximum length should be {} characters'.format(MAX_TEXT_LENGTH))
0779044e55eb618e79e6cc91c7d8d59e614713dc
yamiau/Courses
/[Udemy] Web Scraping with Python - BeautifulSoup, Requests, Selenium/00 Data Structures Refresher/List Comprehension 2.py
777
4.21875
4
'''Nested lists''' carts = [['toothpaste', 'soap', 'toilet paper'], ['meat', 'fruit', 'cereal'], ['pencil', 'notebook', 'eraser']] #or person1 = ['toothpaste', 'soap', 'toilet paper'] person2 = ['meat', 'fruit', 'cereal'] person3 = ['pencil', 'notebook', 'eraser'] carts = [person1, person2, person3] print(carts) for value in carts: print(value) #print(my_list[row][column]) '''2D list''' my_matrix = [] #range(start inclusive, stop exclusive, step) for row in range(0, 25, 5): row_list = [] for column in range(row, row+5): row_list.append(column) my_matrix.append(row_list) print(my_matrix) for row in my_matrix: print(row) '''Using list comprehension''' new_matrix = [[column for column in range(row, row+5)] for row in range(0,25,5)] print(new_matrix)
bee679f46721866386f7365357602dfebe1d16a5
tom-borowik/A-Fun-Problem
/python/short.py
232
3.609375
4
def aSillyFunctionShort(list): '''A function that will sort a list of dictionaries and group them alphabetically by brand then type''' #Most compact solution return sorted(list, key=lambda k:(k['brand'], k['type']))
2e094d45956feada8fcc4c8fa79f7814dd3854ac
aleksei-g/11_duplicates
/duplicates.py
2,935
3.59375
4
import os import argparse def validate_dir(directory): message = None if not os.path.exists(directory): message = 'Directory \"%s\" not found!' % directory else: if not os.path.isdir(directory): message = 'Enter path \"%s\" is not directory!' % directory return message def get_list_file_names(directory): for root, dirs, file_names in os.walk(directory): for file_name in file_names: yield os.path.join(root, file_name) def compare_files(file_name_1, file_name_2): if file_name_1 != file_name_2: if os.path.basename(file_name_1) == os.path.basename(file_name_2): if os.path.getsize(file_name_1) == os.path.getsize(file_name_2): return True return False def search_duplicate_files(dir1, dir2): duplicate_files_dict = {} for file_name_1 in get_list_file_names(dir1): for file_name_2 in get_list_file_names(dir2): if compare_files(file_name_1, file_name_2): file_name = os.path.basename(file_name_1) if file_name in duplicate_files_dict: duplicate_files_dict[file_name].extend([file_name_1, file_name_2]) else: duplicate_files_dict[file_name] = [file_name_1, file_name_2] return duplicate_files_dict def print_duplicate_files(duplicate_files): if duplicate_files: print('Found duplicate files!') for num_file, file_name in enumerate(duplicate_files.keys(), start=1): print('%s. %s:' % (num_file, file_name)) file_paths = set(duplicate_files[file_name]) for num_path, file_path in enumerate(file_paths, start=1): print('\t %s) %s' % (num_path, file_path)) else: print('Duplicate files not found.') def createParser(): parser = argparse.ArgumentParser(description='Script to search \ for duplicate files.') parser.add_argument('-d1', '--dir1', required=True, metavar='DIRECTORY 1', help='Enter path to directory 1.') parser.add_argument('-d2', '--dir2', required=True, metavar='DIRECTORY 2', help='Enter path to directory 2.') return parser if __name__ == '__main__': parser = createParser() namespace = parser.parse_args() dirs_validation_fail = False for directory in namespace.dir1, namespace.dir2: message = validate_dir(directory) if message: dirs_validation_fail = True print(message) if not dirs_validation_fail: print_duplicate_files( search_duplicate_files(os.path.abspath(namespace.dir1), os.path.abspath(namespace.dir2)))
1e2f75864c4a4c30650ca7137eca2c2accd2245e
lithiumspiral/python
/list.py
382
3.625
4
import random import math def fillList(count) : list = [] for i in range(0, count) : list.append(random.randint(0,10)) return list def printList(lst) : for val in lst: print(val) def sumList(lst) : sum = 0 for val in lst: sum += val return sum myList = fillList(25) printList(myList) numSum = sumList(myList) print(numSum)
16ab5543da15a3db9c80b7526c55e3745eadf2af
lithiumspiral/python
/calculator.py
1,196
4.25
4
import math print('This calculator requires you to enter a function and a number') print('The functions are as follows:') print('S - sine') print('C - cosine') print('T - tangent') print('R - square root') print('N - natural log') print('X 0- eXit the program') f, v = input("Please enter a function and a value ").split(" ") v = float(v) while f != 'X' and f != 'x': if f == 'S' or f == 's' : calculation = math.sin(v) print('The sine of your number is ', calculation) elif f == 'C' or f == 'c' : calculation = math.cos(v) print('The cosine of your number is ', calculation) elif f == 'T' or f == 't' : calculation = math.tan(v) print('The tangent of your number is ', calculation) elif f == 'R' or f == 'r' : calculation = math.sqrt(v) print('The square root of your number is ', calculation) elif f == 'N' or f == 'n' : calculation = math.log10(v) elif f == 'X' or f == 'x' : print('Thanks for using the calculator') if f != 'X' and f != 'x': f, v = input("Please enter a function and a value ").split(" ") v = float(v) print('Thanks for using the calculator')
f0f22c7b782e95dd4cdba5fab35e35b6f204c32c
lithiumspiral/python
/listGen.py
565
3.90625
4
import random def createList(count) : list = [] for i in range(0, count) : list.append(random.randint(1,100)) return list def printList(lst) : for val in lst: print(val) def smallLarge(lst) : smallest = lst[0] largest = lst[0] for val in lst: if smallest > val : smallest = val if largest < val : largest = val return smallest, largest newlist = createList(25) printList(newlist) s, l = smallLarge(newlist) print('The smallest number is ', s, 'The largest number is ', l)
b1ff25530c6cf88241d32edb8d7e2d1472a31d9f
AmalyaSargsyan/HTI-1-Practical-Group-1-Amalya-Sargsyan
/Homework_3/rectangle_perimeter.py
876
3.796875
4
# Ստեղծել ծրագիր, որի միջոցով օգտագործողը կմուտքագրի ուղղանկյան անկյունների կոորդինատները # (x1, y1, x2, y2, x3, y3, x4, y4) որպես իրական թվեր և ծրագիրը կտպի ուղղանկյան պարագիծը։ # Ստեղծել և լուծման մեջ օգտագործել segment_length անունով ֆունկցիա, որը կստանա x1, y1, x2, y2 արգումենտներ # և կվերադարձնի նշված ծայրերով կողմի երկարությունը։ def segment_length(x1, y1, x2, y2): if x1 == x2: return y2 - y1 elif y1 == y2: return x2 - x1 coordinates = [float(i) for i in input().split()] length = coordinates[0:4] width = coordinates[2:6] perimeter = 2 * (segment_length(*length) + segment_length(*width)) print(perimeter)
739595d7e26f53842b00e744c069f128a3fda0b6
AmalyaSargsyan/HTI-1-Practical-Group-1-Amalya-Sargsyan
/Homework_3/missing_number.py
928
3.953125
4
# Ստեղծել ծրագիր, որի միջոցով օգտագործողը կմուտքագրի իրարից բացատով առանձնացված N-1 քանակությամբ թվեր, # որոնք գտնում են [1, N] միջակայքում և չեն կրկնվում։ Դա նշանակում է, որ այդ միջակայքում կա մի թիվ # որը բացակայում մուտքագրված արժեքի մեջ։ Ծրագիրը պետք է գտնի և տպի այդ թիվը։ def missing_number(numbers): numbers = [int(i) for i in numbers.split()] numbers.sort() if numbers[0] != 1: return 1 if numbers[-1] != len(numbers) + 1: return len(numbers) + 1 for i in range(2, len(numbers)): _missing_num = numbers[i - 1] + 1 if numbers[i] != _missing_num: return _missing_num print(missing_number(input("Enter numbers separated by space: ")))
9da94e9ef7ddcad683065fc65294e8a07a4ab1a2
ajithkumarkr1/AddSkill
/solutions/21. Merge Two Sorted Lists.py
414
3.5625
4
class Solution:    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:        if l1 == None:            return l2        elif l2 == None:            return l1        if l1.val < l2.val:            return ListNode(l1.val,self.mergeTwoLists(l1.next,l2))                    else:            return ListNode(l2.val,self.mergeTwoLists(l1,l2.next))
a673953ddc1b34392d59af17f7f383d81809bf5a
ajithkumarkr1/AddSkill
/solutions/23. Merge k Sorted Lists.py
656
3.78125
4
# Definition for singly-linked list. # class ListNode: #     def __init__(self, val=0, next=None): #         self.val = val #         self.next = next class Solution:    def mergeKLists(self, lists: List[ListNode]) -> ListNode:        ans=[]        for l in lists:            temp=l            while temp:                ans.append(temp.val)                temp=temp.next        ans.sort()        dummy=ListNode()        current=dummy        for i in ans:            current.next=ListNode(i)            current=current.next        return dummy.next        
d341acf0d4baf56501b0a4da2b6d87cc6b7e7022
ajithkumarkr1/AddSkill
/solutions/206. Reverse Linked List.py
476
3.8125
4
class Solution:    def reverseList(self, head: ListNode) -> ListNode:        self.head = head        current_node = self.head        prev_node = None        next_node = None        while current_node is not None:            next_node = current_node.next            current_node.next = prev_node            prev_node = current_node            current_node = next_node        head = prev_node        return head
40ddcaa8400a349a31e597c8b605387ec91f662c
alazarovieu/functions
/class/circle.py
168
4.25
4
import math print("This program calculates the area of any circle") r=input("Please enter a radius in cm: ") n=int(r) r=(n**2)*math.pi print(str(r)+" cm^2") print("x")
1e789177c591ca2aa7107fd0a83b3345de35c8f1
alazarovieu/functions
/functions/sumOfRandNums.py
188
3.640625
4
import random def fun(): total = 0 for i in range(0, 11): i = random.randint(0, 1000) total += i print("The total sum of the 10 numbers is: ", total) fun()
65804b4d3a11c893a722e50b3fa690dfa23b0c28
alazarovieu/functions
/functions/odd_or_even.py
225
4.0625
4
def fun2(number, odd=True): if number % 2 == 0: odd = False print(number, "is an even number!") else: print(number, "is an odd number") i = input("Please enter a number: ") n = int(i) fun2(n)
cde81feda8b326b3368d63a4351c0996f1fafea9
Emma-2016/introduction-to-computer-science-and-programming
/lecture06.py
2,253
3.890625
4
def squareRootBi(x, epsilon): assert x >= 0, 'x must be non-negative, not ' + str(x) assert epsilon > 0, 'epsilon must be postive, not ' + str(epsilon) low = 0 high = max(x, 1.0) #this sovle previous problem guess = (low + high) / 2.0 ctr = 1 while abs(guess**2 - x) > epsilon and ctr <= 1000: if guess ** 2 < x: low = guess else: high = guess guess = (low + high) / 2.0 ctr += 1 assert ctr <= 1000, 'Iteration count exceeded' print 'Bi method. Num. iterations:', ctr, 'Estimater', guess return guess squareRootBi(0.25, 0.0001) #speed of convergence #f(guess) = guess^2 - x #try to slve the f(guess) = 0 #that is:guess ** 2 - 16: what we looking for here is when the curve is cross with x axis #the basic idea is that you take a guess, and you find the tangent(切线) of the guess #let's take the guess 3, and tangent of the curve at 3. The next guess will be where the tangent crosses the x axis. #Instead of using Bisection method, use another method to find the next guess. #the utility of this rely upon the observation that most of time, the tangent line is a good approximation to the curve for values near the solution. #Therefore the x intersect of the tangent will be closer to right answer than the current guess #How could we find the intersect of tangent? #This is where the derivative comes in. #The slope of the tangent is given by the first derivative of the function f at the point of the guess. #The derivative of i'th guess is equal to two times the i'th guess (f'(guess) = 2 * guess) def squareRootNR(x, espilon): assert x >= 0, 'x must be non-negative, not ' + str(x) assert espilon > 0, 'epsilon must be positive, not ' + str(espilon) x = float(x) guess = x / 2.0 diff = guess ** 2 - x ctr = 1 while abs(diff) > espilon and ctr <= 100: guess = guess - diff / (2.0 * guess) diff = guess ** 2 - x ctr += 1 assert ctr <= 100, 'Iteration count exceeded' print 'NR method. Num. iterations:', ctr, 'Estiamtion' return guess print squareRootNR(16, 0.001) #method is a fancy word for function with a different syntax #the first arguement is always the object itself
d508ae43c03ea8337d2d5dcfeb3ccfc75555df4d
Emma-2016/introduction-to-computer-science-and-programming
/lecture15.py
1,958
4.34375
4
# Class - template to create instance of object. # Instance has some internal attributes. class cartesianPoint: pass cp1 = cartesianPoint() cp2 = cartesianPoint() cp1.x = 1.0 cp2.x = 1.0 cp1.y = 2.0 cp2.y = 3.0 def samePoint(p1, p2): return (p1.x == p2.x) and (p1.y == p2.y) def printPoint(p): print '(' + str(p.x) + ', ' + str(p.y) + ')' # shallow equality -- 'is': given two things, do they point to exactly the same reference? (object) # deep equality -- we can define. (value) class cPoint(): #def __init__(self, x, y): create an instance, use 'self' to refer to that instance #when call a class, it create an instance with all those internal attributes. __init__ create a pointer to that instance. #You need access to that, so it calls it, passing in self as the pointer to the instance. #That says, it has access to that piece of memory and now inside of that piece of memory, I can do thing like: #define self.x to be the value passed in for x. That is create a variable name x and a value associated with it. #self will always point to a particular instance def __init__(self, x, y): self.x = x self.y = y self.radius = math.sqrt(self.x * self.x + self.y * self.y) self. angle = math.atan2(self.y, self.x) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) def __str__(self): #print repretation return '(' + str(self.x) + ', ' + str(self.y) + ')' def __cmp__(self, other): return cmp(self.x, other.x) and cmp(self.y, other.y) #data hidding - one can only access instance values through defined methods. Python does not do this. # operator overloading class Segment(): def __init__(self, start, end): self.start = start self.end = end def length(self): return ((self.start.x - self.end.x) ** 2 + (self.start.y - self.end.y) ** 2) ** 0.5 #in fact, one should access the value through a defined method.
cc9986910553695a94fa4c0c837a3932cec73711
lloistborn/ans-chk
/answerchecker/shingle.py
187
3.609375
4
class Shingle(): def wordshingling(self, word): shingle = [] for i in range(0, len(word) - 2): shingle.append(word[i] + " " + word[i + 1] + " " + word[i + 2]) return shingle
16cccf3ea59693570bf2f56f136c351802586e9b
JoseHGT/Practca_Python
/Hoja_de_Trabajo_01.py
281
4.03125
4
# Python 3: Hoja de trabajo 0 peso = input ("¿Cuál es su peso en Kg?") estatura = input ("¿Cuál es su estatura en metros?") #Para calcular IMC = peso/(estatura*estatura) imc= round(float (peso)/float (estatura)**2,2 ) print(" Su indice de masa corporal es: IMC =",imc)
1f2ab55236635dec043ad89cbf109f76f4779d21
Ibrian93/mathematic-modelling
/lorenz-attractor/lorenz_attractor_1.py
1,568
3.984375
4
import numpy as np import matplotlib.pyplot as plt def lorenz(x, y, z, s=10, r=28, b=2.667): """ Given: x, y, z: a point of interest in three dimensional space s, r, b: parameters defining the lorenz attractor Returns: x_dot, y_dot, z_dot: values of the lorenz attractor's partial derivatives at the point x, y, z """ x_dot = s*(y - x) y_dot = r*x - y - x*z z_dot = x*y - b*z return x_dot, y_dot, z_dot dt = 0.01 num_steps = 10000 class LorenzEquation: def __init__(self, a = 0., b = 1., c = 1.05): self.a = a self.b = b self.c = c def numerical_iteration_simulation(self): xs = np.empty(num_steps + 1) ys = np.empty(num_steps + 1) zs = np.empty(num_steps + 1) #Set initial Values xs[0], ys[0], zs[0] = (self.a, self.b, self.c) # Step through time, calculating the partial derivatives at the current point # and using them to estimate the next point for i in range(num_steps): x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i]) xs[i + 1] = xs[i] + (x_dot * dt) ys[i + 1] = ys[i] + (y_dot * dt) zs[i + 1] = zs[i] + (z_dot * dt) ax = plt.figure().add_subplot(projection='3d') ax.plot(xs, ys, zs, lw=0.5) ax.set_xlabel("X Axis") ax.set_ylabel("Y Axis") ax.set_zlabel("Z Axis") ax.set_title("Lorenz Attractor") plt.show() LorenzEquation(0., 1., 1.05).numerical_iteration_simulation()
1a67c7a2594ff16b19e440727ddf80949a0b20a1
smflorentino/whiteboarder
/LinkedListRep.py
917
4.0625
4
# back end for maintaining opjects that will represent the nodes # and arrows on the "whiteboard" import numpy as np class node: def __init__(self, data): self.datum = data # contains the data self.nodes = None # contains the reference to the next node def add_node(self,node): np.insert(self.nodes,0,node) class linked_list: def __init__(self): self.cur_node = None def add_node(self, data): new_node = node() # create a new node new_node.data = data new_node.next = self.cur_node # link the new node to the 'previous' node. self.cur_node = new_node # set the current node to the new one. def get_Datum(self): return self.data def list_print(self): node = self.cur_node # cant point to ll! while node: print node.data node = node.next # def set_Datum():
c97c982f8c696edaa1dee4e1a38911c06e67929b
zedikram/I0320116_Zedi-Ikram-El-Fathi_Abyan_Tugas5
/I0320116_soal1_tugas5.py
241
3.921875
4
nama = (input('Harap masukan nama anda: ')) jenis = (input('Harap masukan jenis kelamin anda P/L: ')) # memeriksa bilangan if jenis =="P": print('Selamat datang, Bunda', nama ) else: print('Selamat datang, Papah', nama ) print()
d187e911c063e5d384b284a832cea22260191ab0
Smokebird/CS-365-final-project
/test.py
243
3.5625
4
x='3 + y*5' print(x) y=0 x = int(x) print (x) ###this does not work as i planed it would. If this had worked the equation could have been entereed as an string then when it access from the tabel turn into a int the manliptat it
f31062ef7b5bd7f95aeb66af868689d95b65e6a7
DChason/scripts-and-configs
/scripts/hdelete
1,329
3.515625
4
#! /usr/bin/python3 import argparse import os import subprocess import sys def create_parser(): parser = argparse.ArgumentParser( description="Simple tool to find and delete hidden OS files like thumbs.db or ds_store.") parser.add_argument("--d", dest="directory", default=os.getcwd(), type=str, help="The directory to run hdelete if you do not want to run in the current directory.") return parser def main(args): # initial command to find any instances of the hidden files in the desired directory: cmd = ["find", f"{args.directory}", "(", "-iname", ".DS_Store", "-o", "-iname", "Thumbs.db", "-o", "-iname", "._*", ")"] tmp = subprocess.run(cmd, shell=False, capture_output=True) result = tmp.stdout.decode() if not result: sys.exit(f"\nThere are no matching files in '{args.directory}'.") print(f"\n{result}") delete_files = str(input("Do you want to delete these files? [Y/n]: ")) if delete_files not in ["Y", "Yes", "y", "yes"]: sys.exit("\nAction cancelled.") # adding "-delete" flag to the command cmd.insert(len(cmd), "-delete") subprocess.run(cmd, shell=False) print("\nFiles deleted.") if __name__ == "__main__": main_parser = create_parser() args = main_parser.parse_args() main(args)
6afe3be82d2d82d9e9473cdfb7eb3d0592e429d0
aakshay001/Loan_calculator
/project92.py
1,190
3.578125
4
import streamlit as st @st.cache() def calculate_emi(p,n,r): n = n*12 r = r/12 emi = p*(r/100)*((1+(r/100))**n)/(((1+(r/100))**n)-1) return round(emi,3) def calculate_outstanding_balance(p,n,r,m): n = n*12 r = r/12 R = (1+(r/100)) balance = (p*(R**n - R**m))/((R**n) - 1) return round(balance,3) st.title("EMI Calculator App") p = st.number_input("Principal Amount", value=1000, step=1000) tenure = st.number_input("Tenure(in months)", value=12, step=1) roi = st.number_input("Rate of Interest", value=7.0, step=0.1) m = st.number_input("Outstanding Months", value=0, step=1) st.write("Principal Amount: ",p) st.write("Tenure: ",tenure,"Months") st.write("Rate of Interest: ",roi,"%") st.write("Outstanding Months: ",m,"Months") option = st.selectbox("Enter Your Choice",("Calculate EMI","Outstanding Balance")) if st.button("Calculate"): if option == "Calculate EMI": emi = calculate_emi(p,tenure/12,roi) st.write("Calculated EMI is: ",emi) elif option == "Outstanding Balance": balance = calculate_outstanding_balance(p,tenure/12,roi,m) st.write("Outstanding Balance: ",balance)
6ff862cd669330fd672f46d259f844c04af1557f
JulioCCQ/AprendiendoPython.py
/Acumulado.py
607
3.8125
4
#se declara variables int y str acumulado=int(0) numero=str("") #En este ciclo se utiliza while with true #como condicion en el cual se formara un ciclo #infinito hasta que el numero sea vacio # y se utilice el comando break while True: numero=input("Dame un numero entero: ") if numero=="": #Este imprime si el estatus esta vacío y sale print("Vacío. Salida de programa") break else: #Si se proporciona valor se suma para ser calculado acumulado+=int(numero) salida="Monto acumulado: {}" print(salida.format(acumulado))
fd7ca17cc8add406f52f3f8007ff5e806b70fa1a
Ithric/hypertorch
/hypertorch/searchspaceprimitives.py
1,349
3.515625
4
class SearchSpacePrimitive(object): pass class IntSpace(SearchSpacePrimitive): def __init__(self, from_int, to_int, default=None): self.from_int = from_int self.to_int = to_int self.default = default def __str__(self): return "IntSpace(from_int={}, to_int={})".format(self.from_int, self.to_int) def __repr__(self) -> str: return self.__str__() class FloatSpace(SearchSpacePrimitive): def __init__(self, from_float, to_float, default=None): self.from_float = from_float self.to_float = to_float self.default = default def __str__(self): return "FloatSpace(from_float={}, to_float={})".format(self.from_float, self.to_float) def __repr__(self) -> str: return self.__str__() class NoSpace(SearchSpacePrimitive): def __init__(self, value): self.exact_value = value def __str__(self): return "Exactly({})".format(self.exact_value) def __repr__(self) -> str: return self.__str__() class OneOfSet(SearchSpacePrimitive): def __init__(self, set_values, default=None): self.set_values = [k for k in set_values] self.default = default def __str__(self): return "OneOfSet({})".format(self.set_values) def __repr__(self) -> str: return self.__str__()
6803c5e0ea81704b8ab6b34af918d8e9db7df6f8
fredssbr/MITx-6.00.1x
/example-conditional.py
229
3.953125
4
565645# -*- coding: utf-8 -*- """ Created on Sat Sep 10 18:17:16 2016 @author: frederico """ x = int(input('Enter an integer:')) if x%2 == 0: print('Even number.') else: print('Odd number.') print('Finished execution.')
3f835498966366c4a404fc4eb00725bbca57fee9
fredssbr/MITx-6.00.1x
/strings-exercise2.py
304
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 10 19:59:32 2016 @author: frederico """ #Exercise 2 - Strings str1 = 'hello' str2 = ',' str3 = 'world' print('str1: ' + str1) print('str1[0]: ' + str1[0]) print('str1[1]: ' + str1[1]) print('str1[-1]: ' + str1[-1]) print('len(str1): ' + str(len(str1)))
ab79d66c5431f9f808e7973e5fd3cc8093a84ffe
fredssbr/MITx-6.00.1x
/charIsInRecursive.py
907
3.75
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 26 18:43:20 2016 @author: frederico.x.silva """ def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' #print("String: ", aStr) lower = "" higher = "" middle = "" midPos = 0 # Your code here if len(aStr) == 0: return False elif len(aStr) == 1: if char == aStr: return True else: return False else: midPos = len(aStr)%2 lower = aStr[:midPos] middle = aStr[midPos] higher = aStr[midPos+1:] if char < middle: return isIn(char, lower) elif char > middle: return isIn(char, higher) else: return True #char is equal middle print(isIn("x", "abcdefghi"))
00ce7ddd2e3fe18691908492ddd2de4ebde05559
ckceddie/OOP
/OOP_Bike.py
878
4.25
4
# OOP Bike # define the Bike class class bike(object): def __init__ (self , price , max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print "bike's price is " + str(self.price) print "maximum speed : " + str(self.max_speed) print "the total miles : "+str(self.miles) return self def ride(self): print "Riding : " self.miles += 10 print "the miles is "+str(self.miles) return self def reverse(self): print "Reversing : " self.miles -= 5 print "the miles is "+str(self.miles) return self # create instances and run methods bike1 = bike(99.99, 12) bike1.displayInfo() bike1.ride() bike1.ride() bike1.ride() bike1.reverse() bike1.displayInfo() bike2=bike(1000,20) bike2.displayInfo()
d5ec93909c1d754b2d559e4b8b461f118f79b16b
ehpessoa/Python
/Automate-The-Boring-Stuff-With-Python/Chapter 04 - Lists/character_picture_grid.py
766
3.5625
4
#! python3 # character_picture_grid.py - Converts a list to a rotated printout grid = [ ['.', '.', '.', '.', '.', '.'], ['.', '0', '0', '.', '.', '.'], ['0', '0', '0', '0', '.', '.'], ['0', '0', '0', '0', '0', '.'], ['.', '0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0', '.'], ['0', '0', '0', '0', '.', '.'], ['.', '0', '0', '.', '.', '.'], ['.', '.', '.', '.', '.', '.'] ] def character_picture_grid(input_grid): """ Prints grid list as strings :param input_grid: list of lists of string :return: None """ for i in range(len(input_grid[0])): line = '' for row in input_grid: line += row[i] print(line) character_picture_grid(grid)
75392d96521ad4f5676e65cf82bdee6b25e3c0f1
ehpessoa/Python
/Automate-The-Boring-Stuff-With-Python/Chapter 13 - Working with PDF and Word Documents/pdf_paranoia.py
3,150
3.5625
4
#! python3 # pdf_paranoia.py # usage: python pdf_paranoia {encrypt or decrypt} {folder_path} {password} import os import sys import PyPDF2 from PyPDF2.utils import PdfReadError def encrypt(folder_path, password): """ Encrypts all pdf files in given directory with given password :param folder_path: String :param password: String :return: None """ os.chdir(folder_path) for root, dir_names, file_names in os.walk('.'): for file in file_names: if file.endswith('.pdf'): pdf_file = open(os.path.abspath(os.path.join(root, file)), 'rb') pdf_reader = PyPDF2.PdfFileReader(pdf_file) pdf_writer = PyPDF2.PdfFileWriter() encrypted_pdf_name = f'{file[:-4]}_encrypted.pdf' for page_num in range(pdf_reader.numPages): pdf_writer.addPage(pdf_reader.getPage(page_num)) pdf_writer.encrypt(password) result_pdf = open(os.path.abspath(os.path.join(root, encrypted_pdf_name)), 'wb') pdf_writer.write(result_pdf) print(f'Encrypted {encrypted_pdf_name}') result_pdf.close() pdf_file.close() def decrypt(folder_path, password): """ Decrypts all pdf files in given directory with given password :param folder_path: String :param password: String :return: None """ os.chdir(folder_path) for root, dir_names, file_names in os.walk('.'): for file in file_names: if file.endswith('.pdf'): pdf_file = open(os.path.abspath(os.path.join(root, file)), 'rb') pdf_reader = PyPDF2.PdfFileReader(pdf_file) if pdf_reader.isEncrypted: try: pdf_reader.decrypt(password) pdf_writer = PyPDF2.PdfFileWriter() unencrypted_pdf_name = f'{file[:-4]}_unencrypted.pdf' for page_num in range(pdf_reader.numPages): pdf_writer.addPage(pdf_reader.getPage(page_num)) result_pdf = open(os.path.abspath(os.path.join(root, unencrypted_pdf_name)), 'wb') pdf_writer.write(result_pdf) print(f'Unencrypted {unencrypted_pdf_name}') result_pdf.close() pdf_file.close() except PyPDF2.utils.PdfReadError: print(f'Password for {file} is incorrect') continue def main(): """ Retrieves command line args :return: None """ if len(sys.argv) > 2: folder_path = sys.argv[2] password = sys.argv[3] if sys.argv[1] == 'encrypt': encrypt(folder_path, password) elif sys.argv[1] == 'decrypt': decrypt(folder_path, password) else: print('usage: python pdf_paranoia {encrypt or decrypt} {folder_name} {password}') if __name__ == '__main__': main()
6b20406d423409b7a977d67e670b61022f4f0976
ehpessoa/Python
/Automate-The-Boring-Stuff-With-Python/Chapter 03 - Functions/the_collatz_sequence.py
329
4.4375
4
#! python3 # the_collatz_sequence.py - Take user input num and prints collatz sequence def collatz(num): print(num) while num != 1: if int(num) % 2: num = 3 * num + 1 else: num = num // 2 print(num) user_num = input('Enter a number ') collatz(user_num)
e2d745324b2465f7cfb709bf924d97638742456b
jkbstepien/ASD-2021
/graphs/exercises/09_02_ob_find_cycle_4.py
827
3.6875
4
def bfs(G): n = len(G) for i in range(n): queue = [i] distances = [-1] * n distances[i] = 0 visited = [False] * n parent = [None] * n while queue: v = queue.pop(0) for j in range(n): if G[v][j] == 1 and not visited[j]: parent[j] = v visited[j] = True distances[j] = distances[v] + 1 queue.append(j) elif (G[v][j] == 1 and parent[v] != j and distances[v] + 1 == distances[j] == 2): return True return False if __name__ == "__main__": graph = [[0, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1], [1, 1, 1, 0]] print(bfs(graph))
639a47c01e32c471b846092125d32ddd23461a1e
jkbstepien/ASD-2021
/trees/bst-tree.py
9,647
4.125
4
class BSTNode: """ Class represents a single node of binary tree. """ def __init__(self, key, value): self.left = None self.right = None self.parent = None self.key = key self.value = value self.count_elem = 1 class BSTree: """ Class representing Binary Search Tree with it's operations. """ def __init__(self, root=None): self.root = root def inorder(self, *args): """ Produces list of nodes, obtained in inorder traversal. (Left, Root, Right) """ if len(args) == 0: lst = [] node = self.root else: node = args[0] lst = args[1] if node.left: self.inorder(node.left, lst) lst.append(node.key) if node.right: self.inorder(node.right, lst) return lst def preorder(self, *args): """ Produces list of nodes, obtained in preorder traversal. (Root, Left, Right) """ if len(args) == 0: lst = [] node = self.root else: node = args[0] lst = args[1] lst.append(node.key) if node.left: self.inorder(node.left, lst) if node.right: self.inorder(node.right, lst) return lst def postorder(self, *args): """ Produces list of nodes, obtained in postorder traversal. (Left, Right, Root) """ if len(args) == 0: lst = [] node = self.root else: node = args[0] lst = args[1] if node.left: self.inorder(node.left, lst) if node.right: self.inorder(node.right, lst) lst.append(node.key) return lst def find(self, key, *args): """ Find node in binary tree with key attribute key. """ if len(args) == 0: start = self.root else: start = args[0] if not start: return None if start.key == key: return start elif start.key < key: return self.find(key, start.right) else: return self.find(key, start.left) def insert(self, key, value, *args): """ Inserts a new node with key attribute key and value attribute value into binary tree. """ if not self.root: self.root = BSTNode(key, value) elif len(args) == 0: if not self.find(key, self.root): self.insert(key, value, self.root) else: to_add = BSTNode(key, value) parent = args[0] parent.count_elem += 1 if to_add.key < parent.key: if not parent.left: parent.left = to_add to_add.parent = parent else: self.insert(key, value, parent.left) else: if not parent.right: parent.right = to_add to_add.parent = parent else: self.insert(key, value, parent.right) def get_height(self, *args): """ Obtain height of binary tree. Root + highest subtree. """ if len(args) == 0: node = self.root else: node = args[0] if not node: return 0 elif not node.left and not node.right: return 1 else: return 1 + max(self.get_height(node.left), self.get_height(node.right)) def get_min(self, *args): """ Obtain from binary tree a node with min key. """ if len(args) == 0: start = self.root else: start = args[0] if start.left: return self.get_min(start.left) else: return start def get_max(self, *args): """ Obtain from binary tree a node with max key. """ if len(args) == 0: start = self.root else: start = args[0] if start.right: return self.get_max(start.right) else: return start def get_ith_elem(self, elem_idx): """ Finds element with i-th size in a binary tree. """ node = self.root # Check if elem_idx is in tree range. if elem_idx > node.count_elem: return -1 while node.right is not None or node.left is not None: # Check if we are in the right place in a tree. if node.left is not None and node.left.count_elem + 1 == elem_idx: return node.key elif node.left is not None and node.left.count_elem >= elem_idx: node = node.left else: # If not any of the above, try to go right and decrease # index of element by how many nodes we've passed. if node.left is not None: elem_idx -= node.left.count_elem node = node.right elem_idx -= 1 if node.right: # Case where there is no more left nodes, but exist # further right node. if node.count_elem - node.right.count_elem == elem_idx: return node.key return node.key @staticmethod def delete_leaf(node): """ Deletes node in binary tree, leaf case. """ parent_node = node.parent if parent_node: if parent_node.left == node: parent_node.left = None else: parent_node.right = None def delete_one_child(self, node): """ Deletes node in binary tree, which has one child. """ parent_node = node.parent if node.key == self.root.key: if node.right: self.root = node.right node.right = None else: self.root = node.left node.left = None else: if parent_node.right == node: # Removing right node with one child. if node.left: parent_node.right = node.left parent_node.right.parent = parent_node node.left = None else: parent_node.right = node.right parent_node.right.parent = parent_node node.right = None else: # Removing left node with one child. if node.left: parent_node.left = node.left parent_node.left.parent = parent_node node.left = None else: parent_node.left = node.right parent_node.left.parent = parent_node node.right = None def swap_nodes(self, node1, node2): """ Swap positions of node1 and node2. """ swap_1 = node1 swap_2 = node2 tmp_key = swap_1.key tmp_val = swap_1.value if swap_1.key == self.root.key: self.root.key = swap_2.key self.root.value = swap_2.value swap_2.key = tmp_key swap_2.value = tmp_val elif swap_2.key == self.root.key: swap_1.key = self.root.key self.root.key = tmp_key self.root.value = tmp_val else: swap_1.key = node2.key swap_1.value = node2.value swap_2.key = tmp_key swap_2.value = tmp_val def delete_two_children(self, node): """ Deletes node in binary tree, which has two children. """ if self.get_height(node.left) > self.get_height(node.right): to_swap = self.get_max(node.left) self.swap_nodes(node, to_swap) if not to_swap.right and not to_swap.left: to_remove = self.get_max(node.left) self.delete_leaf(to_remove) else: to_remove = self.get_max(node.left) self.delete_one_child(to_remove) else: to_swap = self.get_min(node.right) self.swap_nodes(node, to_swap) if not to_swap.right and not to_swap.left: to_remove = self.get_min(node.right) self.delete_leaf(to_remove) else: to_remove = self.get_min(node.right) self.delete_one_child(to_remove) def delete(self, key): """ Delete the node from binary tree with key attribute key. """ node = self.find(key, self.root) if node: if not node.left and not node.right: self.delete_leaf(node) elif not (node.left and node.right): self.delete_one_child(node) else: self.delete_two_children(node) def main(): # Tests tree = BSTree() nodes = [10, 5, 2, 7, 9, 20] for node in nodes: tree.insert(node, None) print(tree.inorder()) print(tree.preorder()) print(tree.postorder()) for i in range(1, 7): print(f"{i} - elem : {tree.get_ith_elem(i)}") print(f"min: {tree.get_min().key}") print(f"max: {tree.get_max().key}") print(f"tree height: {tree.get_height()}") tree.delete(5) print(tree.inorder()) if __name__ == "__main__": main()
e573f700709125ccfd74996c4eac12b7c30dbece
jkbstepien/ASD-2021
/graphs/ford-fulkerson.py
1,609
3.75
4
from queue import PriorityQueue def bfs(graph, s, t, parent) -> bool: queue = PriorityQueue() visited = [False for _ in range(len(graph))] queue.put(s) visited[s] = True while not queue.empty(): u = queue.get() for idx in range(len(graph[u])): if visited[idx] is False and graph[u][idx] > 0: visited[idx] = True parent[idx] = u queue.put(idx) return visited[t] def ford_fulkerson(graph, source, sink) -> int: """ Algorithm finds max-flow in directed graph. Uses Ford-Fulkerson's method with Edmond-Karp's technique for finding paths in graph. """ n = len(graph) parents = [-1 for _ in range(n)] max_flow = 0 while bfs(graph, source, sink, parents): flow_on_path = float("inf") s = sink while s != source: # Find minimum value on current path. flow_on_path = min(flow_on_path, graph[parents[s]][s]) s = parents[s] max_flow += flow_on_path v = sink while v != source: u = parents[v] graph[u][v] -= flow_on_path graph[v][u] += flow_on_path v = parents[v] return max_flow def main(): graph = [ [0, 8, 4, 0, 0, 0], [0, 0, 0, 12, 0, 0], [0, 0, 0, 2, 4, 0], [0, 0, 0, 0, 0, 10], [0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0] ] source, sink = 0, 5 res = ford_fulkerson(graph, source, sink) if res == 12: print("good answer") if __name__ == "__main__": main()
6604cf3f68749b72d0eeb22a76e03075d2b87a02
jkbstepien/ASD-2021
/graphs/cycle_graph_adj_list.py
1,087
4.125
4
def cycle_util(graph, v, visited, parent): """ Utility function for cycle. :param graph: representation of a graph as adjacency list. :param v: current vertex. :param visited: list of visited vertexes. :param parent: list of vertexes' parents. :return: boolean value for cycle function. """ visited[v] = True for u in graph[v]: if not visited[u]: parent[u] = v cycle_util(graph, u, visited, parent) elif visited[u] and parent[u] != v: return True return False def cycle(graph, s=0): """ Function determines whether graph has a cycle. :param graph: graph as adjacency list. :param s: starting vertex. :return: boolean value. """ n = len(graph) visited = [False] * n parent = [False] * n return cycle_util(graph, s, visited, parent) if __name__ == "__main__": G = [[1, 3], [2, 0], [3, 1], [4, 0], [3]] G2 = [[1, 3], [2, 0], [1], [4, 0], [3]] G3 = [[1, 2], [2, 0], [0, 1]] print(cycle(G)) print(cycle(G2)) print(cycle(G3))
2938c36dff020bbdc9b01d7bc17cb29c81f61b1a
heeyeon456/chagokchagok
/python/basic/10.반복문.py
255
3.828125
4
#while, for, do~while(x) a = 1 while a<=5: if a==3: break print("a=", a) a += 1 else: print("반복문 정상탈출") print("반복문 강제탈출 ") n = 0 while n<5: n += 1 if n == 3: continue print("n=", n)
7de069cd334c90f1d71ce8cbc3b624b7bc02f9c1
heeyeon456/chagokchagok
/python/sqlite/dbTools.py
1,136
3.90625
4
import sqlite3 class DBTools: def __init__(self, dbname, table_name): self.dbname = dbname self.tablename = table_name def createTable(self): try: conn = sqlite3.connect(self.dbname) sql = 'create table if not exists {}(name var(20), ' \ 'count int)'.format(self.tablename) conn.execute(sql) print("테이블 생성 성공") except Exception as err: print(err) conn.close() return conn def insertTable(self, data): command = f"insert into {self.tablename} values(?,?)" try : conn = sqlite3.connect(self.dbname) conn.execute(command, data) conn.commit() except Exception as err: print(err) def selectTable(self): sql = f"select * from {self.tablename}" try: conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute(sql) dt = cur.fetchall() except Exception as err: print(err) conn.close() return dt
55ef8b25082b22e3878894c1cdf94d4bae6d23b1
heeyeon456/chagokchagok
/python/class/22.special_method.py
1,361
4.0625
4
# special method # object 의 멤버함수 class Test: #object def __init__(self): print("init call") self.a = 0 self.b = 0 self.myDic = {} #공백 dictionary def setData(self,x,y): self.a = x self.b = y def show(self): print(self.a, self.b) # 상위 클래스 object 에 있는거 재정의 def __repr__(self): return f'a={self.a} b={self.b}' def __add__(self, other): print('add call') return self.a + other def __setitem__(self, key, value): print('setitem call') self.myDic[key] = value def __getitem__(self, item): return self.myDic[item] obj = Test() print(obj) # obh.__repr__() obj['aa'] = 10 # obj.__setitem('aa', 10) obj['bb'] = 20 # obj.__setitem('bb', 10) print(obj['aa']) #obj.__getitem__('aa') print(obj.myDic) # d = {'aa': 1} # d['aa'] = 10 # 있으면 수정 # d['bb'] = 20 # 없으면 추가 """ obj = Test() print( obj ) # obj.__repr__() 로 바꿔줌 obj.setData(10, 20) rst = obj+100 # obj.__add__(100) print(rst) # 문자열 클래스 객체 s = 'abc' print(s+'def') # special method 로 두개의 문자열에 연결되도록 정의되어 있음 # 파이썬에서 변수는 객체 또는 레퍼런스 # my = [10,20,30,40] # 힙메모리에 리스트 클래스 객체 할당 # print( my ) """
6ab8af2dc1a37cb5cb05b723cab2b3a8bfee7591
heeyeon456/chagokchagok
/python/sqlite/12.database_1.py
3,218
4
4
import sqlite3 as sql3 # DB가 없으면, 생성후 접송 # DB가 있으면, 접솝 def createTable(): try: conn = sql3.connect('test.db') sql_command = 'create table if not exists student(name var(20),' \ 'age int, birth date)' conn.execute(sql_command) conn.close() print("테이블 생성 성공") except Exception as err: print("테이블 생성 실패") def insertTable(): # insert, delete, update 이 세가지 구문은 commit 이 반드시 필요 try: command = "insert into student values('홍길동',20,'1999-10-11')" conn = sql3.connect('test.db') conn.execute(command) conn.commit() # 명령 확정 conn.close() print("테이블 추가 성공") except Exception as err: print("추가 실패") conn.close() def insertFormat(name, age, birth): try: command = "insert into student values(?,?,?)" conn = sql3.connect('test.db') conn.execute(command, (name, age, birth)) conn.commit() # 명령 확정 conn.close() print("테이블 추가 성공") except Exception as err: print("추가 실패") conn.close() def insertDataBulk(): try: sql = "insert into student values(?,?,?)" conn = sql3.connect('test.db') data =[('김철수',30,'1989-10-10'), ('이황',40,'1979-12-15'), ('이이',50,'1969-03-18')] conn.executemany(sql, data ) conn.commit() conn.close() print("insert success") except Exception as err: print(err) def updateData(): try: sql="update student set name=?, age=? where name=?" db = sql3.connect("test.db") db.execute(sql, ('이황황',20, '이황') ) db.commit() db.close() print("update data ") except Exception as err: print(err) def deleteData(): try: sql="delete from student where name=?" db = sql3.connect("test.db") db.execute(sql, ('이황황',) ) db.commit() db.close() print("delete data ") except Exception as err: print(err) def selectData(): try: sql = "select * from student" db = sql3.connect("test.db") # connection 개체가 아닌 커서 개체로 sql execute cur = db.cursor() cur.execute(sql) dt = cur.fetchall() #db.execute(sql) db.close() print(dt) for n,a,b in dt: print(n,a,b) except Exception as err: print(err) def selectCur(): try: sql="select * from student" db = sql3.connect("test.db") cur = db.cursor() cur.execute(sql) for n,a,b in cur: print( n,a,b ) db.close() except Exception as err: print(err) def deleteCursor(): try: sql="delete from student where age=?" db = sql3.connect("test.db") cur = db.cursor() cur.execute(sql, (30, )) print("삭제 된 갯수", cur.rowcount) db.commit() db.close() except Exception as err: print(err) deleteCursor()
4f939ce42d7d1c263cf67adc968c1dda300928f9
heeyeon456/chagokchagok
/python/basic/08.삼항연산자.py
280
3.640625
4
a = 5 rst = 100 if a>0 else 200 print(rst) rst = [200, 100][False] print(rst) rst = {True:100, False:200}[a>0] print(rst) score = input("점수 입력:") score = int(score) result = "합격" if score >= 70 else "불합격" result=["불합격", "합격"][score>=70] print(result)
56aa944ae7790c902fecef53123f9fc2649ea828
heeyeon456/chagokchagok
/python/basic/06.대입연산자.py
91
3.8125
4
a=3 # a = a+2 # a +=2 # a = a**2 a**=2 print(a) n = 1 # n = n+1 n +=1 # n++ (X) print(n)
968aed0029a1689771d090fce423d427ed330b3a
heeyeon456/chagokchagok
/python/regex/05.매칭메타문자.py
411
3.59375
4
import re s1 = 'apple kiwi banana straw' s2 = 'apple kiwi banana application' try: #match = re.search('ap+le|straw|melon', s1) #print( match.group() ) #my = re.findall('ap+le|straw|melon', s1) #print(my) #matchs = re.finditer('ap+le|straw|melon', s1) #for m in matchs: # print( m ) my = re.findall('ap[a-z]+', s2) print(my) except Exception as err: print("Not Found")
2894f3ac5c5270423e33b9d63732ff0485a4fc41
heeyeon456/chagokchagok
/python/class/14.class_basic.py
1,006
3.53125
4
class Test: # 생성자 함수 def __init__(self): print("init call") self.a = 10 self.b = 20 def setData(self, x, y): print('setData self 주소', id(self)) self.a = x self.b = y def show(self): print('show self 주소', id(self)) print(self.a, self.b) # heap 메모리에 a,b 변수를 올려주고, obj 가 할당된 메모리의 시작주소를 반환한다. # obj 주소값 자체는 global 변수로 저장한다. obj = Test() # 다른 언어 new Test() # obj.__init__(obj) print('obj 주소', id(obj)) obj.setData(100, 200) # obj.setData(obj,100,200) 파이썬 컴파일러가 이렇게 조정 obj.show() # obj.show(obj) print() obj1 = Test() print('obj1 주소', id(obj1)) obj1.setData(11,22) obj1.show() # 동일한 클래스에서 여러개의 객체가 발생할 경우, #멤qj 데이터는 메모리 별도로 (heap) # 멤버 함수(코드)는 공유 # 어떻게 각각의 멤버데이터 영역에 r/w self
a6b8fb03fbae70083b96048fdedb701d0d2587e3
umashankar43631/python-duplicate_list_program
/number_duplication.py
1,042
4.09375
4
#program to seperate the duplicate items and no duplicate items in the given list and to display the count lst1 = [1,2,3,4,5,6,2,1,5,6,7,8,4,12,11,10,5,5,5,1,1,2,8] no_duplicates=[] duplicate_items=[] print ("Original list is : ",lst1) lst1.sort() print("After Sorting : ",lst1) duplicate_count = [] dup_count =0 for i in range(len(lst1)): if(i==0): no_duplicates.append(lst1[i]) else: if lst1[i] not in no_duplicates: if(dup_count!=0): duplicate_count.append(dup_count) dup_count = 0 no_duplicates.append(lst1[i]) else: dup_count+= 1 if lst1[i] not in duplicate_items : duplicate_items.append(lst1[i]) print("no-Duplicate list and duplictes-list") print(no_duplicates,duplicate_items,sep='\n') print("count of duplicates is : ") print(tuple(zip(duplicate_items,duplicate_count))) print("no change in the list after the program and the original sorted list is : \n",lst1)
a87996752698edb6022666a131c1c8d08bc0d071
harleymayes/HomemadeEncryption
/key.py
396
3.796875
4
import random def generatekey(): keystore = open("key.txt", 'w') word = input("Enter encryption word:") length = len(word) multiplier = random.randint(1,length) key = length * multiplier keystore.write(str(key)) keystore.close() return(key) def retrievekey(): keystore = open("key.txt", 'r') key = keystore.read() keystore.close() return(key)
e79c3953658bfb4d394f2f91e08e1655e36e3be7
okipriyadi/NewSamplePython
/SamplePython/samplePython/database/MongoDB/_06_find_and_query.py
6,878
4.25
4
""" You can use the find() method to issue a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection. Queries can return all documents in a collection or only the documents that match a specified filter or criteria. You can specify the filter or criteria in a document and pass as a parameter to the find() method. The find() method returns query results in a cursor, which is an iterable object that yields documents. Prerequisites The examples in this section use the log collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset. In the mongo shell connected to a running mongod instance, switch to the test database. use test Query for All Documents in a Collection To return all documents in a collection, call the find() method without a criteria document. For example, the following operation queries for all documents in the restaurants collection. =========================== db.log.find() =========================== Untuk mengetahui jumlah record di tabel tersebut gunakan =========================== db.log.count() =========================== Untuk mengskip =========================== db.log.find().skip(12092) =========================== Limit the Number of Documents to Return The limit() method limits the number of documents in the result set. The following operation returns at most 5 documents in the bios collection: =========================== db.log.find().limit( 5 ) =========================== Order Documents in the Result Set The sort() method orders the documents in the result set. The following operation returns documents in the bios collection sorted in ascending order by the name field: =========================== db.log.find().sort( { _id: 1 } ) =========================== 1 untuk ascending -1 untuk descending contoh kita akan mencari di kolom message yang mengandung kata PA-003 : *****(kalau di sql rumusnya seperti ini : select * from users where name like '%m%') ========================================== db.log.find({"msg" : /.*PA-003.*/}) ========================================== contoh lain : ============================================================= db.users.insert({name: 'paulo'}) db.users.insert({name: 'patric'}) db.users.insert({name: 'pedro'}) db.users.find({name: /a/}) ###like '%a%' out: paulo, patric db.users.find({name: /^pa/}) ###like 'pa%' out: paulo, patric db.users.find({name: /ro$/}) ###like '%ro' out: pedro ============================================================= """ """ The result set contains all documents in the restaurants collection. Specify Equality Conditions The query condition for an equality match on a field has the following form: { <field1>: <value1>, <field2>: <value2>, ... } If the <field> is a top-level field and not a field in an embedded document or an array, you can either enclose the field name in quotes or omit the quotes. If the <field> is in an embedded document or an array, use dot notation to access the field. With dot notation, you must enclose the dotted name in quotes. Query by a Top Level Field The following operation finds documents whose borough field equals "Manhattan". db.restaurants.find( { "borough": "Manhattan" } ) The result set includes only the matching documents. Query by a Field in an Embedded Document To specify a condition on a field within an embedded document, use the dot notation. Dot notation requires quotes around the whole dotted field name. The following operation specifies an equality condition on the zipcode field in the address embedded document. db.restaurants.find( { "address.zipcode": "10075" } ) The result set includes only the matching documents. For more information on querying on fields within an embedded document, see Embedded Documents. Query by a Field in an Array The grades array contains embedded documents as its elements. To specify a condition on a field in these documents, use the dot notation. Dot notation requires quotes around the whole dotted field name. The following queries for documents whose grades array contains an embedded document with a field grade equal to "B". db.restaurants.find( { "grades.grade": "B" } ) The result set includes only the matching documents. For more information on querying on arrays, such as specifying multiple conditions on array elements, see Arrays and $elemMatch. Specify Conditions with Operators MongoDB provides operators to specify query conditions, such as comparison operators. Although there are some exceptions, such as the $or and $and conditional operators, query conditions using operators generally have the following form: { <field1>: { <operator1>: <value1> } } For a complete list of the operators, see query operators. Greater Than Operator ($gt) Query for documents whose grades array contains an embedded document with a field score greater than 30. db.restaurants.find( { "grades.score": { $gt: 30 } } ) The result set includes only the matching documents. Less Than Operator ($lt) Query for documents whose grades array contains an embedded document with a field score less than 10. db.restaurants.find( { "grades.score": { $lt: 10 } } ) The result set includes only the matching documents. Combine Conditions You can combine multiple query conditions in logical conjunction (AND) and logical disjunctions (OR). Logical AND You can specify a logical conjunction (AND) for a list of query conditions by separating the conditions with a comma in the conditions document. db.restaurants.find( { "cuisine": "Italian", "address.zipcode": "10075" } ) The result set includes only the documents that matched all specified criteria. Logical OR You can specify a logical disjunction (OR) for a list of query conditions by using the $or query operator. db.restaurants.find( { $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] } ) The result set includes only the documents that match either conditions. Sort Query Results To specify an order for the result set, append the sort() method to the query. Pass to sort() method a document which contains the field(s) to sort by and the corresponding sort type, e.g. 1 for ascending and -1 for descending. For example, the following operation returns all documents in the restaurants collection, sorted first by the borough field in ascending order, and then, within each borough, by the "address.zipcode" field in ascending order: db.restaurants.find().sort( { "borough": 1, "address.zipcode": 1 } ) The operation returns the results sorted in the specified order. Additional Information In the MongoDB Manual, see find(), Cursors, and sort(). In the MongoDB Manual, see also Query Documents tutorial, Projection tutorial, Query and Projection Operators reference, and Cursor Methods. """
d64c67795595e66b99cb36a1458443a6ebc52486
okipriyadi/NewSamplePython
/SamplePython/samplePython/Networking/_celery/tasks.py
6,648
3.546875
4
#create celery application tasks """ In order to use celery's task queuing capabilities, our first step after installation must be to create a celery instance. This is a simple process of importing the package, creating an "app", and then setting up the tasks that celery will be able to execute in the background. """ from celery import Celery app = Celery('tasks', backend='amqp', broker='amqp://') """ The first argument to the Celery function is the name that will digunakan to tasks to identify them. The backend parameter is an optional parameter that is necessary if you wish to query the status of a background task, or retrieve its results. If your tasks are simply functions that do some work and then quit, without returning a useful value to use in your program, you can leave this parameter out. If only some of your tasks require this functionality, enable it here and we can disable it on a case-by-case basis further on. The broker parameter specifies the URL needed to connect to our broker. In our case, this is the RabbitMQ service that is running on our server. RabbitMQ operates using a protocol called "amqp". If RabbitMQ is operating under its default configuration, celery can connect with no other information other than the amqp:// scheme. """ print "----------------Membuat Tugas ----------------------------------" @app.task(ignore_result=True) def print_hello(): print 'hello there' """ Each celery task must be introduced with the decorator @app.task. This allows celery to identify functions that it can add its queuing functions to. After each decorator, we simply create a function that our workers can run. Because this function does not return any useful information (it instead prints it to the console), we can tell celery to not use the backend to store state information about this task. This is less complicated under the hood and requires fewer resources. Next, we will add another function that will generate prime numbers. This can be a long-running process, so it is a good example for how we can deal with asynchronous worker processes when we are waiting for a result. """ @app.task def gen_prime(x): multiples = [] results = [] for i in xrange(2, x+1): if i not in multiples: results.append(i) for j in xrange(i*i, x+1, i): multiples.append(j) return results """ Because we care about what the return value of this function is, and because we want to know when it has completed (so that we may use the results, etc), we do not add the ignore_result parameter to this second task. Save and close the file. """ """ ----------------------------------- Running the celery worker Server ----------------------------------- We can now start a worker processes that will be able to accept connections from applications. It will use the file we just created to learn about the tasks it can perform. Starting a worker instance is as easy as calling out the application name with the celery command. We will include a "&" character at the end of our string to put our worker process in the background: buka shell $ celery worker -A tasks & This will start up an application, and then detach it from the terminal, allowing you to continue to use it for other tasks. ----------------------------------- Calling the task ----------------------------------- We can use the worker process(es) we spawned to complete work in the background for our programs. Instead of creating an entire program to demonstrate how this works, we will explore the different options in a Python interpreter: ============================================= python ============================================= At the prompt, we can import our functions into the environment: ============================================= from tasks import print_hello from tasks import gen_prime ============================================= If you test these functions, they appear to not have any special functionality. The first function prints a line as expected: ============================================= print_hello() ============================================= hasilnya: ============================================= hello there ============================================= The second function returns a list of prime numbers: ============================================= primes = gen_prime(1000) print primes ============================================= If we give the second function a larger range of numbers to check, the execution hangs while it calculates: ============================================= primes = gen_prime(50000) ============================================= Stop the execution by typing "CTRL-C". This process is clearly NOT COMPUTING in the background. To access the background worker, we need to use the .delay method. Celery wraps our functions with additional capabilities. This method is used to pass the function to a worker to execute. It should return immediately: ============================================= primes = gen_prime.delay(50000) ============================================= This task is now being executed by the workers we started earlier. Because we configured a backend parameter for our application, we can check the status of the computation and get access to the result. To check whether the task is complete, we can use the .ready method: ============================================= primes.ready() ============================================= hasilnya: ============================================= False ============================================= A value of "False" means that the task is still running and a result is not available yet. When we get a value of "True", we can do something with the answer. ============================================= primes.ready() ============================================= hasilnya ============================================= True ============================================= We can get the value by using the .get method. If we have already verified that the value is computed with the .ready method, then we can use that method like this: ============================================= print primes.get() ============================================= If, however, you have not used the .ready method prior to calling .get, you most likely want to add a "timeout" option so that your program isn't forced to wait for the result, which would defeat the purpose of our implementation: print primes.get(timeout=2) This will raise an exception if it times out, which you can handle in your program. """
d661472a0e0a43d481e4788780f20c3187f86f2f
okipriyadi/NewSamplePython
/SamplePython/samplePython/database/SQLite/sqliteEx.py
3,929
3.75
4
import sqlite3 con = sqlite3.connect('Toko.db') # prepare a cursor object using cursor() method cur = con.cursor() #Query put Here cur.execute('SELECT SQLITE_VERSION()') # Fetch a single row using fetchone() method. data = cur.fetchone() #print the data print "SQLite version: %s" % data #Create tabel #cur.execute('''CREATE TABLE Customers(CustomerID INTEGER PRIMARY KEY AUTOINCREMENT, #CustomerName TEXT, ContactName TEXT, Address TEXT, City TEXT, PostalCode TEXT, Country TEXT)''') def insertCustomer(): name = raw_input("Customer Name: ") contactName = raw_input("Contack Name: ") address = raw_input("Address Name: ") city =raw_input("City : ") post = raw_input("Postal Code :") country = raw_input("Country :") cur.execute('''INSERT INTO Customers(CustomerName, ContactName, Address, City, PostalCode, Country) VALUES(?,?,?,?,?,?)''',(name, contactName, address, city, post, country)) con.commit() def tampilkan(): for i in cur: print "\n" for j in i: print j def showQuery(): query = "Select * From Customers ORDER BY CustomerName Desc" cur.execute(query) tampilkan() def search(): searchKey = raw_input("masukan kata kunci") query = "SELECT * FROM Customers WHERE CustomerName LIKE '%" + searchKey + "%' OR ContactName LIKE '%"+searchKey+ "%' OR Address LIKE '%"+searchKey+"%' OR City LIKE '%"+searchKey+"%' OR PostalCode LIKE '%"+searchKey+"%' OR Country LIKE '%"+searchKey+"%'" cur.execute(query) tampilkan() def delete(): search() IdDelete = raw_input("Pilih ID untuk di delete : ") query = "DELETE FROM Customers WHERE CustomerID = '"+IdDelete+"'" cur.execute(query) print "No Id :", IdDelete, "berhasil di delete" con.commit() def editKontak(): search() CustomerID = raw_input("Masukan no customer Id yang akan diedit") nama = raw_input("masukan nama :") query = "UPDATE Customers SET CustomerName='"+ nama +"', City='Hamburg' WHERE CustomerID='"+ CustomerID +"'" cur.execute(query) con.commit() def menuCustomer(): pilihan = "0" while pilihan !="9": print "===========Menu============" print "1. Add new customer" print "2. Show All" print "3. Cari" print "4. Delete" print "5. Edit" print "9. Exit" pilihan = raw_input("Choose the number :") if pilihan =="1": insertCustomer() if pilihan =="2": showQuery() if pilihan =="3": search() if pilihan =="4": delete() if pilihan =="5": editKontak() def menuUtama(): pilihan = "0" while pilihan !="9": print "===========Menu============" print "1. Masuk Tabel Customer" print "2. Sample Inner join" print "3. Left Join" print "9. Exit" pilihan = raw_input("Choose the number :") if pilihan =="1": menuCustomer() if pilihan =="2": query = "select orderan.order_id, Customers.CustomerName, orderan.order_date from Orderan JOIN Customers ON orderan.id_person = customers.CustomerID ORDER BY Customers.CustomerName" cur.execute(query) tampilkan() if pilihan =="3": query = "select orderan.order_id, Customers.CustomerName, orderan.order_date from Orderan LEFT JOIN Customers ON orderan.id_person = customers.CustomerID ORDER BY Customers.CustomerName" cur.execute(query) tampilkan() if pilihan =="4": query = "select orderan.order_id, Customers.CustomerName, orderan.order_date from Orderan RIGHT OUTER JOIN Customers ON orderan.id_person = customers.CustomerID ORDER BY Customers.CustomerName" cur.execute(query) tampilkan() menuUtama()
830aaaa0664c6d8f993de0097927ff4c385c6d4e
okipriyadi/NewSamplePython
/SamplePython/samplePython/Modul/memcache/_01_Using_memcache.py
1,261
4.21875
4
""" kesimpuan sementara saya, memcache digunakan untuk menyimpan sebuah value di memori cache sehingga program lain bisa mengambil value tersebut dengan cara mencari key yang telah ditetapkan coba lihat value di file ini bisa didapatkan oleh file _02_test.py It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system. Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage. <http://www.danga.com/memcached> If you really want to dig into it, I'd look at the source. Here's the header comment: """ import memcache mc = memcache.Client(['127.0.0.1:11211'], debug=0) mc.set("some_key", "Some value") value = mc.get("some_key") print "value 1", value mc.set("another_key", 3) value = mc.get("another_key") print "value 2", value mc.delete("another_key") value = mc.get("another_key") print "value 3", value """ mc.set("key", "1") # note that the key used for incr/decr must be a string. mc.incr("key") mc.decr("key") key = derive_key(obj) obj = mc.get(key) if not obj: obj = backend_api.get(...) mc.set(key, obj) # we now have obj, and future passes through this code # will use the object from the cache. """
3f398d75509ca53fc9b9d907f1121ea6233b5f37
okipriyadi/NewSamplePython
/SamplePython/Basic Source /Dasar/variableAndCasting.py
1,007
3.765625
4
print 9/4 #karna keduanya integer maka menghasilkan INTEGER print 9.0/4 #menghasilkan float karna salah satunya float print float(9)/4 #pake casting juga bisa print int(9/4) #hasilnya int, int akan membulatkan kebawah print round(9.0/4) #hasilnya adalah hasil dengan pembulatan berdasarkan angka setelah koma. lbh kecil dr 0,5 akan membulankan ke bawah, dan sebaliknya print round(10.0/4) c=1 d=2 e=3 print c+d+e print str(c) + str(d) + str(e) f = "9" #print f+3 #akan menghasilkan error karna string gak bisa ditambah denga INTEGER print int(f)+3 d = [type(c)] d= str(d) print d, type(d), d[0] print "Angka dibelakang koma" x = "12.33423423423424" print x y = float("{0:.3f}".format(float(x))) print type(y) print "\nMengkonversi dari dictionary menjadi objek" class DBStruct: def __init__(self, **entries): self.__dict__.update(entries) A = {'A':'SDASD','B':'DASDSA','C':'WERWR','D':'ZXCZC'} dict_konversi = DBStruct(**A) print dict_konversi print dict_konversi.B print dict_konversi.D
03d41b53695b5cd140934c7d2ad4f3e6344e5002
okipriyadi/NewSamplePython
/SamplePython/samplePython/Modul/os/_11_TempFile_Write.py
400
3.71875
4
""" By default, the file handle is created with mode ’w+b’ so it behaves consistently on all platforms, and the caller can write to it and read from it. After writing, the file handle must be “rewound” using seek() in order to read the data back from it. """ import os import tempfile with tempfile.TemporaryFile() as temp: temp.write('Some data') temp.seek(0) print temp.read()
dc191b7153e036ca6050a135c668b195cd2558d2
okipriyadi/NewSamplePython
/SamplePython/Basic Source /ifForWhile/for.py
603
3.921875
4
for nomor in [1,2,"tiga",4,5]: print nomor tabel = [ [1, "dua", 3], ["siji",2,"telu"], ["hiji","dua", "tiga"] ] for nomor in tabel : print nomor print "bandingkan dengan for yg ini\n" for nomor in tabel : for number in nomor: print number print "\n" for nomor in range(3) : #range menghasilkan daftar bilangan sesuai paramater, dalam hal ini nomber = [0,1,2]] print nomor for nomor in range(1,3) : #range menghasilkan daftar bilangan sesuai paramater, dalam hal ini nomber = [0,1,2]] print nomor
d93db45bbff954b5957cf7d8b62363877c7b0e84
okipriyadi/NewSamplePython
/SamplePython/build_in_modul/_04_getattr.py
678
4.5625
5
""" Objects in Python can have attributes. For example you have an object person, that has several attributes: name, gender, etc. You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc. But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called gender_attribute_name """ class Hello_world(): def __init__(self): self.Pariabel = "saya orang sunda" def saja(self): print "pulangkan saja " a = Hello_world() b = getattr(a, "Pariabel") print b c = getattr(a, "saja") c()
747a7106f59a9e54aec3c2b87089bc380cd9ccb4
okipriyadi/NewSamplePython
/SamplePython/samplePython/Modul/os/_17_previlage_level_and_run_as_different_user.py
1,899
3.609375
4
""" The first set of functions provided by os is used for determining and changing the process owner ids. These are most frequently used by authors of daemons or special system programs that need to change permission level rather than run as root . This section does not try to explain all the intricate details of UNIX security, process owners, etc. See the references list at the end of this section for more details. The following example shows the real and effective user and group information for a process, and then changes the effective values. This is similar to what a daemon would need to do when it starts as root during a system boot, to lower the privilege level and run as a different user. sebelum menjalankan program coba cek GID(Group ID) dan UID(User ID) di sistem operasinya, untuk linux coba gunakan cat /etc/passwd. ganti GID dan UID dibawah dengan GID & UID yang sesuai The values do not change because when it is not running as root, a process cannot change its effective owner value. Any attempt to set the effective user id or group id to anything other than that of the current user causes an OSError . Running the same script using sudo so that it starts out with root privileges is a different story. """ import os TEST_GID=1000 TEST_UID=1000 def show_user_info(): print 'User (actual/effective) : %d / %d' % (os.getuid(), os.geteuid()) print 'Group (actual/effective) : %d / %d' % (os.getgid(), os.getegid()) print 'Actual Groups:', os.getgroups() return print 'BEFORE CHANGE:' show_user_info() try: os.setegid(TEST_GID) except OSError: print 'ERROR: Could not change effective group.rerun as root' else: print 'CHANGED GROUP:' show_user_info() print try: os.seteuid(TEST_UID) except OSError: print 'ERROR: Could not change effective user. rerun as group' else: print 'CHANGE USER:' show_user_info() print