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 |
|---|---|---|---|---|---|---|
8a21d626471ee40247d391619d5c2d89ec8080a0 | TouailabIlyass/python_sys | /th2_2.py | 426 | 3.546875 | 4 | import threading
a=0
lock=threading.Semaphore(1)
def inc():
global a,lock
lock.acquire()
for x in range(1000000):
a=a+1
lock.release()
def main():
#global a,lock
#lock=threading.Lock()
#a=0
print('we start a = ',a)
t1=threading.Thread(target=inc,name='t1')
t2=threading.Thread(target=inc,name='t2')
t1.start()
t2.start()
t1.join()
t2.join()
print('fin a = ',a)
if __name__ == '__main__':
main()
|
0a31a39fc54b6000dd04355a6c2588035740d0c0 | Taker2626/MauMau | /Move.py | 942 | 3.796875 | 4 | '''Lets a player make a move'''
def Move(Master,Player_lst,Turn):
from copy import copy
from Message import Clear,Card_display
Hand=Master[Player_lst[Turn]]
Clear()
print('Your current hand:\n')
Card_display(Hand)
if len(Master['Trash'])!=0:
Top=Master['Trash'][-1]
print('Current Top card:\n')
print(Top)
else:
Top=0
print('Play any card, you go ahead and start <3')
Playable=[]
for i in Hand:
if Top==0:
Playable=copy(Hand)
elif i[0] == Top[0] or i[1] == Top[1] or i[3]=='*':
Playable.append(i)
if len(Playable)>0:
print('You can play the following cards:\n')
Card_display(Playable)
return (int(input('Which card would you like to play?: '))-1)
#checked and working
else:
print('Oh dear you will have to draw a card.')
return -1
#checked and working
|
fcdf4562ab9b593d77cc143da95c131b15e8c2e7 | Fabrizio-Yucra/introprogramacion | /Listas (Array)/ejercicio 3.py | 744 | 4 | 4 | base = float(input("Ingrese la base de su figura: "))
altura = float(input("Ingrese la altura de su figura: "))
numero = 1
lM = 0
lm = 0
if base > altura:
lM = base
lm = altura
else:
lM = altura
lm = base
no_entran = []
si_entran = []
while numero > 0:
radio = float(input("Ingrese un radio: "))
numero = radio
if numero == 0:
numero = 0
diametro = 2 * radio
if lM > 0:
if diametro <= lm:
lM = lM - diametro
si_entran.append(radio)
else:
no_entran.append(radio)
else:
no_entran.append(radio)
print(f"Los circulos que si pueden entrar a la figura son {si_entran}")
print(f"Los circulos que no pueden entrar a la figura son {no_entran}") |
82ed876cc4ca54552505c94f93e475ef9e6a42a5 | Fabrizio-Yucra/introprogramacion | /Practico_1/ejercicio 11.py | 578 | 3.9375 | 4 | from datetime import date
print("Ingrese su fecha de nacimiento.")
dia = int(input("Día: "))
mes = int(input("Mes: "))
año = int(input("Año: "))
fecha_de_nacimiento = date(año, mes, dia)
hoy = date.today()
operacion = (hoy.year - fecha_de_nacimiento.year)
operacion_1 = (hoy.day - fecha_de_nacimiento.day)
operacion_2 = (hoy.month - fecha_de_nacimiento.month)
if operacion_2 <= 0:
if operacion_1 >= 0:
print(f"Usted tiene {operacion} años. ")
else:
print(f"Usted tiene {operacion -1} años. ")
else:
print(f"Usted tiene {operacion} años. ")
|
c1f66fd41dc5001ba3889ffb4d27ddaf3910a497 | Fabrizio-Yucra/introprogramacion | /Practico_1/ejercicio 3.py | 386 | 4 | 4 | numero_1 = int(input("Ingrese un numero entero: "))
numero_2 = int(input("ingrese un segundo numero entero: "))
if numero_1 % numero_2 == 0:
print(f"La division es exacta")
print(f"Cociente = {numero_1 / numero_2} ")
print(f"Resto = 0")
else:
print(f"La division no es exacta")
print(f"Cociente = {numero_1 // numero_2}")
print(f"Resto = {numero_1 % numero_2}")
|
98d41fcfec5ce89314bfd77dde2ee2c655b69b37 | Fabrizio-Yucra/introprogramacion | /Practico_1/ejercicio 5.py | 442 | 3.859375 | 4 | variable_1 = input("Ingrese una palabra: ")
variable_2 = input("ingrese otra palabra: ")
if len(variable_1) > len(variable_2):
print(f"La palabra {variable_1} tiene {len(variable_1) - len(variable_2)} letras mas que {variable_2}")
elif len(variable_1) == len(variable_2):
print("Las dos palabras tienen el mismo largo")
else:
print(f"La palabra {variable_2} tiene {len(variable_2) - len(variable_1)} letras mas que {variable_1}")
|
a22ae353b847aaf12bc32aa1bef8e5cba1a54d77 | Fabrizio-Yucra/introprogramacion | /variables 2/ejercicio2.py | 225 | 3.78125 | 4 | dividendo = int(input("ingrese el dividendo :"))
divisor = int(input("ingrese el divisor :"))
operacion = dividendo % divisor
mensaje = f"El resto obtenido al dividir {dividendo} entre {divisor} es {operacion}"
print(mensaje) |
8a31d2d035ce465fc3627008172f5d69d2b8e305 | Fabrizio-Yucra/introprogramacion | /Practico_1/ejercicio 4.py | 92 | 4 | 4 | numero = int(input("Ingrese un numero: "))
for a in range(0, numero + 1):
print(2 ** a)
|
b22a96344344d3dbfa349bbc83a4b0f6283d19ac | chiting765/LC_Everyday | /705_Design_HashSet.py | 787 | 3.5625 | 4 | class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.keyRange = 769
self.buckets = [[] for i in range(self.keyRange)]
def add(self, key: int) -> None:
index = key % self.keyRange
if key not in self.buckets[index]:
self.buckets[index].append(key)
def remove(self, key: int) -> None:
index = key % self.keyRange
if key in self.buckets[index]:
self.buckets[index].remove(key)
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
index = key % self.keyRange
if key in self.buckets[index]:
return True
else:
return False
|
85d379bd305b6b7de56e87e54389a1c54a495610 | Jumaroag/tp-lights-out-python | /traductor.py | 433 | 3.71875 | 4 | import tablero
tablero.posciciones_del_tablero()
def traductor():
print("¿Qué poscición deseas jugar?")
a = input()
a = str(a)
a = a.lower()
if (a in tablero.posciciones_del_tablero()):
print(tablero.posciciones_del_tablero()[a])
elif (a not in tablero.posciciones_del_tablero()):
print("Poscicion no valida, elija una poscición comprendida entre A1 y E5")
traductor()
traductor() |
98699800f9537bbe9e702fbe77b18f697f6ff0b5 | steve1281/mathquizer | /mathquiz.py | 6,669 | 3.53125 | 4 | #!/usr/bin/env python
import time
from math import ceil
import pygame
from quiz import quiz
from sprites import Chicken, Question, Answer, Feedback, TimerBox, ScoreBox
from colors import *
class Main():
def __init__(self):
pygame.init()
self.font = pygame.font.Font(None, 36)
self.clock = pygame.time.Clock()
self.fps = 30
size = width, height = 800, 640
self.window = pygame.display.set_mode(size)
self.initMathTool()
self.initSprites()
self.initGameStats()
self.runGame()
def initMathTool(self):
self.boxes = []
for i in range(1, 13):
for j in range(1, 13):
box = pygame.Surface((40,32))
sbox = pygame.sprite.Sprite()
text = self.font.render(str(i*j), 1, (10, 10, 20))
textpos = text.get_rect()
textpos.centerx = box.get_rect().centerx
textpos.centery = box.get_rect().centery
box.fill(gray_red)
box.blit(text, textpos)
sbox.image = box
sbox.rect = ((i*46,j*38),(40,32))
self.boxes.append(sbox)
def initSprites(self):
self.chickens = [ Chicken(600, 10), Chicken(660, 5), Chicken(720, 10)]
self.timerbox = TimerBox("0")
self.question = Question("")
self.scorebox = ScoreBox("")
self.answer = Answer("")
self.feedback = Feedback("")
def initGameStats(self):
self.chicken_count = len(self.chickens)
self.timer_set = 30
self.entered = ""
self.question_number = 0
self.question_count = 10
self.old_time = 0
self.start_time = time.time()
self.actual_answer = quiz[self.question_number]['answer']
self.question_text = quiz[self.question_number]['question']
def decode(self, key):
k = key - pygame.K_0
if k>=0 and k <= 9:
return str(k)
else:
return ""
def runGame(self):
running_game = True
running_intro = False
running_done = False
running = True
while running:
self.window.fill(gray)
if running_game:
for event in pygame.event.get():
if (event.type == pygame.QUIT or
event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
running = False
if event.type == pygame.KEYDOWN:
self.feedback.setText("")
self.entered = self.entered + self.decode(event.key)
if event.key == pygame.K_BACKSPACE:
self.entered = self.entered[:-1]
elif event.key == pygame.K_RETURN:
if len(self.entered) > 0:
ans = int(self.entered)
else:
ans = -1
if ans == self.actual_answer:
self.question_number += 1
if self.question_number == len(quiz):
self.question_number = 0
if self.question_number == self.question_count:
endtime = time.time()
self.actual_answer = quiz[self.question_number]['answer']
self.question_text = quiz[self.question_number]['question']
self.entered = ""
self.feedback.setText("Got last question, try another!")
else:
self.feedback.setText("Last try was wrong, try again.")
self.chicken_count -= 1
if self.chicken_count < 0:
self.chicken_count = 0
# display pass button
for b in self.boxes:
self.window.blit(b.image,b.rect)
self.question.setText(self.question_text)
self.window.blit(self.question.image, self.question.rect)
self.answer.setText(self.entered)
self.window.blit(self.answer.image, self.answer.rect)
self.window.blit(self.feedback.image, self.feedback.rect)
score = self.timer_set - (time.time() - self.start_time )
score = int(ceil(score))
if self.old_time <> score:
self.old_time = score
self.timerbox.setText(str(score))
if self.timerbox:
self.window.blit(self.timerbox.image, self.timerbox.rect)
if score <= 0:
running_game = False
running_done = True
self.scorebox.setText(str(self.question_number))
self.window.blit(self.scorebox.image, self.scorebox.rect)
for i in range(self.chicken_count):
self.window.blit(self.chickens[i].image, self.chickens[i].rect)
pos = pygame.mouse.get_pos()
for i in range(len(self.boxes)):
s = self.boxes[i]
r = pygame.Rect( s.rect)
if r.collidepoint(pos[0],pos[1]):
pygame.draw.rect(s.image, yellow, pygame.Rect((0,0),(44,32)),3)
s1 = self.boxes[i % 12]
s2 = self.boxes[i - i% 12]
pygame.draw.rect(s1.image, yellow, pygame.Rect((0,0),(44,32)),3)
pygame.draw.rect(s2.image, yellow, pygame.Rect((0,0),(44,32)),3)
else:
pygame.draw.rect(s.image, gray_red, pygame.Rect((0,0),(44,32)),3)
elif running_done:
for event in pygame.event.get():
if (event.type == pygame.QUIT or
event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
running = False
self.scorebox.setText(str(self.question_number))
self.window.blit(self.scorebox.image, self.scorebox.rect)
for i in range(self.chicken_count):
self.window.blit(self.chickens[i].image, self.chickens[i].rect)
self.clock.tick(self.fps)
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
Main()
|
838399d50bf54c75975ad1ee7225f3fb237b712a | SamT16/CS1-Labs | /Python/Lab 72/frac_to_dec.py | 120 | 3.65625 | 4 | var1 = input("input the Numerator")
var2 = input("input the Denominator")
print var1,"/", var2,"=",
print var1/var2
|
cfd6b1b4b42ec2afac072e0fbcaa0043f6bd2d15 | PawningPawns/First-GitHub-Test | /return.py | 876 | 3.734375 | 4 | print("Hellow World!")
class Transaction:
sales_tax = 0.1
def __init__(self, total, discount_rate):
self.total = total
self.tax = Transaction.sales_tax * total
self.discount = disocunt_rate
self.total_discount = int(total - (total * discount))
def change_rate(self):
self.change_rate = self.total
return self.change_rate
def output_value(self):
self.output = self.total
self.discount_output = self.total_discount
return self.output
return self.discount_output
def print_value(self):
print('{} tax, {} total, {} discounted total'.format(Transaction.sales_tax, self.output, self.discount_output))
sale_input = int(input())
sale_discount = int(input))
foo1 = Transaction(sale_input, sale_discount)
foo1.print_value()
print('{} total, {} discount'.format(foo1.total, foo1.discount))
|
0bdfcc13e4cb2faa012624babf6181f456923641 | teja0508/Clothing-Analysis-Forecasting---RNN | /Clothing Retail Sales -Seasonality Analysis And Forecasting - RNN.py | 5,167 | 3.640625 | 4 | """
Clothing Retail Sales -Seasonality Analysis & Forecasting With Recurrent Neural Networks -RNN :
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
#By Using Parse_Date=True , pandas will automatically detect date column as datetime object :
df=pd.read_csv('RSCCASN.csv',parse_dates=True,index_col='DATE')
print(df.head())
print(df.info())
df.columns=['Sales']
sns.set_style('whitegrid')
df.plot(figsize=(12,8))
plt.show()
"""
Determining Train / Test Split Index :
"""
print(len(df))
print(len(df)-18)
test_size=18
test_ind=len(df)-test_size
print(test_ind)
"""
Here , For forecasting we should train our model for atleast a year 's cycle , in order to get it familiar with
the seasonality of sales..For simplicity , i will be taking 18 as test size , since 18 months = 1.5 years
and before that , rest of the data will be my training data :
"""
train=df.iloc[:test_ind]
test=df.iloc[test_ind:]
print(train)
print(test)
"""
SCALING OF DATA :
"""
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler()
scaled_train=scaler.fit_transform(train)
scaled_test=scaler.transform(test)
"""
TimeSeriesGenerator :
For validation test set generator my batch size must be less than test size , i.e. , 18 , in order
to run properly without error. I would be taking my length of batch as 12 , because it is one whole
year..
"""
from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator
length=12
generator=TimeseriesGenerator(scaled_train,scaled_train,length=length,batch_size=1)
X,y=generator[0]
print(X)
print(y)
print(scaled_train[13])
"""
CREATING MODEL:
"""
from tensorflow.keras.layers import Dense,SimpleRNN,LSTM
from tensorflow.keras.models import Sequential
n_features=1 #Sales column
model=Sequential()
model.add(LSTM(100,activation='relu',input_shape=(length,n_features)))
model.add(Dense(1))
model.compile(loss='mse',optimizer='adam')
print(model.summary())
from tensorflow.keras.callbacks import EarlyStopping
early_stop=EarlyStopping(monitor='val_loss',patience=2)
validation_gen=TimeseriesGenerator(scaled_test,scaled_test,length=length,batch_size=1)
model.fit_generator(generator,epochs=20,validation_data=validation_gen,callbacks=[early_stop])
losses=pd.DataFrame(model.history.history)
losses.plot()
plt.show()
test_predictions=[]
first_eval_batch=scaled_train[-length:]
current_batch=first_eval_batch.reshape(1,length,n_features)
for i in range(len(test)):
current_pred=model.predict(current_batch)[0]
test_predictions.append(current_pred)
current_batch=np.append(current_batch[:,1:,:],[[current_pred]],axis=1)
true_pred=scaler.inverse_transform(test_predictions)
df2=test.copy()
df2['Predictions']=true_pred
print(df2)
df2.plot(figsize=(12,8))
plt.title('Sales VS Predicitons')
plt.show()
"""
FORECASTING VALUES INTO UNKNOWN FUTURE By USING FULL DATASET AS TRAINING:
"""
full_Scaler=MinMaxScaler()
full_scaled_data=full_Scaler.fit_transform(df) #Transforming Full Data :
length=12
generator=TimeseriesGenerator(full_scaled_data,full_scaled_data,length=length,batch_size=1)
model=Sequential()
model.add(LSTM(100,activation='relu',input_shape=(length,n_features)))
model.add(Dense(1))
model.compile(loss='mse',optimizer='adam')
model.fit_generator(generator,epochs=8)
"""
periods is the number of months we want to predict , so here i took 12 , as i want to predict
next 12 months forecast.You can take any number you want .. but do remember , longer the length
of period , more will be the noisy data....
SO it would be much better if you choose the same length for periods as
the length of your test size , i.e. , 12..
"""
forecast=[]
periods=12
first_eval_batch=scaled_train[-length:]
current_batch=first_eval_batch.reshape(1,length,n_features)
for i in range(periods):
current_pred=model.predict(current_batch)[0]
forecast.append(current_pred)
current_batch=np.append(current_batch[:,1:,:],[[current_pred]],axis=1)
forecast_pred=full_Scaler.inverse_transform(forecast)
print(df)
print(forecast_pred)
#You can see that forecast_pred values are actually values predicted after the dataframe's values
"""
Now let us create a proper dataframe with comparisons..
we have to create new timestamp range for future predictions
"""
"""
pd.date_Range will create automatically new dates with intervals , start parameter will take the
starting point , one after our original dataframe , periods is intervals , i.e., 12[already defined
into periods variable], freq=offset aliases MS -> monthly sequence intervals
"""
forecast_index=pd.date_range(start='2019-11-01',periods=periods,freq='MS')
print(forecast_index)
forecast_Df=pd.DataFrame(data=forecast_pred,index=forecast_index,columns=['Forecast'])
print(forecast_Df)
ax=df.plot()
forecast_Df.plot(ax=ax)
plt.title("Forecasting Sales Prediction Into Unknown Future")
plt.show()
ax=df.plot()
forecast_Df.plot(ax=ax)
plt.xlim('2018-01-01','2020-12-01') #Zoom our graph into mentioned X - AXIS Values
plt.title("Forecasting Sales Prediction Into Unknown Future between 2018 to 2020")
plt.show() |
1432a19e35b9e79f342d5c30dac680092a040db8 | james-lawlor/Lawlor_Utils | /print_random_lines.py | 1,962 | 3.625 | 4 | #Purpose: select random lines from a file
#Input: a text file with any headers/metatdata beginning with #
import sys
import getopt
from time import clock
from random import SystemRandom
def main(argv):
input_filename = ""
output_filename = ""
fraction_to_print = 0
added_metadata = False
try:
opts, args = getopt.getopt(argv, "hi:o:f:")
except getopt.GetoptError:
print "print_random_lines.py -i <input filename> -o <output filename> -f <fraction to print>"
sys.exit(2)
for opt, arg in opts:
if opt == "-h":
print "print_random_lines.py -i <input filename> -o <output filename> -f <fraction to print>"
sys.exit(2)
elif opt == "-i":
input_filename = arg
elif opt == "-o":
output_filename = arg
elif opt == "-f":
fraction_to_print = float(arg)
if input_filename == "" or output_filename == "" or fraction_to_print <= 0 or fraction_to_print >= 1:
print "Incorrect or missing options."
print "print_random_lines.py -i <input filename> -o <output filename> -f <fraction to print>"
sys.exit(2)
with open(input_filename, "r") as input_file_handle:
with open(output_filename, "w") as output_file_handle:
for line in input_file_handle:
if line.startswith("#"):
output_file_handle.write(line)
else:
if added_metadata is False:
output_file_handle.write("#Using print_random_lines.py, approximately %.2f percent of lines have been selected from " % (fraction_to_print*100) + input_filename + "\n")
added_metadata = True
random_number = SystemRandom(clock()).random()
if random_number <= fraction_to_print:
output_file_handle.write(line)
if __name__=="__main__":
main(sys.argv[1:]) |
b2996db8afbe2f952cf6bec133cfe69c1dbab752 | gurehf000109/python_big_and_small | /what's big.py | 256 | 3.734375 | 4 | def max(num1,num2):
if(num1>num2):
resert = num1
else:
resert = num2
return resert
x=eval(input("first number"))
y=eval(input("secend number"))
print(x,"와",y,"중 큰수는",max(x,y),"이고 작은수는",min(x,y),"이다")
|
e34df7e05d79e028fedd543098f2e2bf335f527b | AkshatBhat/Tic-Tac-Toe-Game | /MilestoneProject1.py | 4,227 | 4.03125 | 4 | def display_board(board):
print(' '+board[7]+' '+'|'+' '+board[8]+' '+'|'+' '+board[9]+' ')
print('--- --- ---')
print(' '+board[4]+' '+'|'+' '+board[5]+' '+'|'+' '+board[6]+' ')
print('--- --- ---')
print(' '+board[1]+' '+'|'+' '+board[2]+' '+'|'+' '+board[3]+' ')
def player_input():
print('Input will be asked again and again until correct data is fed!')
player1_marker = ''
player2_marker = ''
player1_marker = input("Player 1 Choose 'X' or 'O': ")
while player1_marker!='X' and player1_marker!='O':
player1_marker = input("Player 1 Choose 'X' or 'O': ")
if player1_marker=='X':
player2_marker = 'O'
print("Player 1 plays as 'X'")
print("Player 2 plays as 'O'")
return (player1_marker,player2_marker)
else:
player2_marker = 'X'
print("Player 1 plays as 'O'")
print("Player 2 plays as 'X'")
return (player1_marker,player2_marker)
def place_marker(board, marker, position):
if board[position]==' ':
board[position] = marker
def win_check(board, mark):
return mark==board[7]==board[8]==board[9] or mark==board[4]==board[5]==board[6] or mark==board[1]==board[2]==board[3] or mark==board[7]==board[4]==board[1] or mark==board[8]==board[5]==board[2] or mark==board[9]==board[6]==board[3] or mark==board[7]==board[5]==board[3] or mark==board[9]==board[5]==board[1]
from random import randint
def choose_first():
return randint(1,2)
def space_check(board, position):
if board[position]!=' ':
return False
else:
return True
def full_board_check(board):
for i in board[1:]:
if i==' ':
return False
return True
def player_choice(i,z,board):
move = int(input('Player {} --> {} your move position: '.format(i,z)))
if space_check(board,move):
return move
else:
return -1
flag = False
print('Welcome to Tic Tac Toe!')
test_board = ['@',' ',' ',' ',' ',' ',' ',' ',' ',' ']
display_board(test_board)
(p1,p2) = player_input()
first = choose_first()
print('At Random, Player {} will go first...'.format(first))
if first==1:
while True:
m1 = player_choice(1,p1,test_board)
while (m1)==-1:
print('Position already taken ...')
m1 = player_choice(1,p1,test_board)
place_marker(test_board,p1,m1)
display_board(test_board)
if win_check(test_board,p1):
print("Player 1 has WON!!")
flag = True
break
if full_board_check(test_board):
break
m2 = player_choice(2,p2,test_board)
while (m2)==-1:
print('Position already taken ...')
m2 = player_choice(2,p2,test_board)
place_marker(test_board,p2,m2)
display_board(test_board)
if win_check(test_board,p2):
print("Player 2 has WON!!")
flag = True
break
if full_board_check(test_board):
break
if not flag:
print("GAME DRAW!!")
if first==2:
while True:
m2 = player_choice(2,p2,test_board)
while (m2)==-1:
print('Position already taken ...')
m2 = player_choice(2,p2,test_board)
place_marker(test_board,p2,m2)
display_board(test_board)
if win_check(test_board,p2):
print("Player 2 has WON!!")
flag = True
break
if full_board_check(test_board):
break
m1 = player_choice(1,p1,test_board)
while (m1)==-1:
print('Position already taken ...')
m1 = player_choice(1,p1,test_board)
place_marker(test_board,p1,m1)
display_board(test_board)
if win_check(test_board,p1):
print("Player 1 has WON!!")
flag = True
break
if full_board_check(test_board):
break
if not flag:
print("GAME DRAW") |
573ed22b1e142cdb4e136d7b6c39e697bfe6b917 | dosdarwin/BMI | /bmi.py | 410 | 4.21875 | 4 | height = (float(input('what is your height(in cm):')))/100
weight = float(input('what is your weight(in kg):'))
BMI = float(weight/(height*height))
if BMI < 18.4:
print('your BMI is',BMI, ',too light!')
elif 18.5 <= BMI <= 23.9:
print('your BMI is', BMI, ',perfect!')
elif 24 <= BMI <= 26.9:
print('your BMI is', BMI, ',a little too heavy!')
else:
print('your BMI is',BMI, ',too heavy!!!!!!!!') |
19618a68a2ef38c0a2d35eb10c9e60ecbe0532d5 | gsantam/competitive-programming | /cracking_the_code/chapter_2/remove_node.py | 1,214 | 3.96875 | 4 | class Node():
def __init__(self,data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def appendNode(self,data):
node = Node(data)
if self.head == None:
self.head = node
else:
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = node
def prependNode(self,data):
node = Node(data)
node.next = self.head
self.head = node
def deleteWithValue(self,data):
if self.head == None:
return
if self.head.data == data:
self.head = self.head.next
return
current_node = self.head
while current_node.next is not None:
if current_node.next.data == data:
current_node.next = current_node.next.next
return
current_node = current_node.next
def delete_node(ll,node):
if node is None:
return
next_node = node.next
node.data = next_node.data
node.next = next_node.next
return ll
|
2a2dd08a7e87992273c96c42418ad1d571d65e63 | gsantam/competitive-programming | /cracking_the_code/medium/ways_of_encoding.py | 564 | 3.5625 | 4 | """
data = "123"
ways_of_encodig("123")
ways_of_encodig("23") + ways_of_encodig("3")
1 + 1 +1
"""
def ways_of_encodig(message):
global ways_of_encofing
if len(message)==0:
return 1
if message[0]=="0":
return 0
if len(message)==1:
return 1
if int(message[0:2]) <= 26:
return ways_of_encodig(message[1:]) + ways_of_encodig(message[2:])
else:
return ways_of_encodig(message[1:])
print(ways_of_encodig("111111"))
|
ba2bfbc8460e4e45f6996c891b7ede22490d6f3d | gsantam/competitive-programming | /facebook_prep/colourful_numbers.py | 460 | 3.640625 | 4 | def is_colourful(number):
seen_numbers = set()
number_str = str(number)
for i,digit_str in enumerate(number_str):
product = 1
for j in range(i,len(number_str)):
product=int(number_str[j]) * product
if not (i==0 and j == len(number_str)-1):
if product in seen_numbers:
return False
seen_numbers.add(product)
return True
print(is_colourful(3245))
|
55e9496a34932f667e1b5aecc18db85a2fb2313e | gsantam/competitive-programming | /hackerrank/preparation-kit/sort/fraudulent_activity_notifications.py | 1,472 | 3.765625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import os
def median(historical_expenditures,d):
i = 0
number_visited = 0
central_point = d//2 if d%2 == 0 else d//2 + 1
while number_visited < central_point:
number_visited+=historical_expenditures[i]
i+=1
if d%2 == 1:
return i-1
else:
j = i-1
while number_visited < central_point + 1:
number_visited+=historical_expenditures[i]
i += 1
return (j+i-1)/2
def activityNotifications(expenditure,d):
n_alarms = 0
historical_expenditures = [0 for i in range(200+1)]
n_expenditures = 0
trailing_array = []
for day_expenditure in expenditure:
trailing_array.append(day_expenditure)
n_expenditures+=1
if n_expenditures>d:
if n_expenditures>d+1:
historical_expenditures[trailing_array[len(trailing_array)-d-2]]-=1
median_number = median(historical_expenditures,d)
if day_expenditure >= 2*median_number:
n_alarms+=1
historical_expenditures[day_expenditure] +=1
return n_alarms
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nd = input().split()
n = int(nd[0])
d = int(nd[1])
expenditure = list(map(int, input().rstrip().split()))
result = activityNotifications(expenditure, d)
fptr.write(str(result) + '\n')
fptr.close()
|
12ef0a6b8a036b9061b44917cd054d28fa08b8ef | gsantam/competitive-programming | /leetcode/easy/valid-palindrome.py | 598 | 3.625 | 4 | class Solution:
def check_letter(self,char):
if (char>="a" and char<="z") or (char>="0" and char<="9"):
return True
return False
def isPalindrome(self, s: str) -> bool:
i = 0
j = len(s)-1
while i<j:
if not self.check_letter(s[i].lower()):
i+=1
elif not self.check_letter(s[j].lower()):
j-=1
elif s[i].lower()!=s[j].lower():
return False
else:
i+=1
j-=1
return True
|
377d0acc018a61ddaf201a98b7857e4ad2463582 | gsantam/competitive-programming | /leetcode/easy/combinations.py | 440 | 3.53125 | 4 | class Solution:
def helper(self,current,n,k):
if len(current)==k:
self.all.append(current)
return
prev = 0
if len(current)>0:
prev = current[-1]
for i in range(prev+1,n+1):
self.helper(current+[i],n,k)
def combine(self, n: int, k: int) -> List[List[int]]:
self.all = []
self.helper([],n,k)
return self.all
|
eded6122abdb10c2be9160b51b6d8755aa986e76 | gsantam/competitive-programming | /advent_of_code/2020/5/1.py | 464 | 3.71875 | 4 | seats = open("input.txt","r").readlines()
highest = 0
for seat in seats:
down = 0
up = 127
left = 0
right = 7
for letter in seat:
if letter == "F":
up = (down+up)//2
if letter == "B":
down = (down+up)//2
if letter == "R":
left = (left+right)//2
if letter == "L":
right = (left+right)//2
seat_id = up*8 + right
highest = max(highest,seat_id)
print(highest)
|
df77d3ec7ca8b5999bd23811e11589311a4c36bb | gsantam/competitive-programming | /cracking_the_code/chapter_2/partition_by_x.py | 2,131 | 4 | 4 | class Node():
def __init__(self,data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def appendNode(self,data):
node = Node(data)
if self.head == None:
self.head = node
else:
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = node
def appendNodes(self,data_list):
for data in data_list:
self.appendNode(data)
def prependNode(self,data):
node = Node(data)
node.next = self.head
self.head = node
def deleteWithValue(self,data):
if self.head == None:
return
if self.head.data == data:
self.head = self.head.next
return
current_node = self.head
while current_node.next is not None:
if current_node.next.data == data:
current_node.next = current_node.next.next
return
current_node = current_node.next
def print_list(self):
if self.head is None:
return
else:
actual_node = self.head
while actual_node is not None:
print(actual_node.data,end = " ")
actual_node = actual_node.next
"""
x = 5
6 -> 2 -> 3 -> 2 => 6 -> 2 -> 3 -> 2 -> 6 => 2 -> 3 -> 2 -> 6
"""
def partition_ll_by_x(ll,x):
if ll.head is None:
return
last_node = ll.head
length = 1
while last_node.next is not None:
last_node = last_node.next
length+=1
if length==1:
return
actual_node = ll.head
for i in range(length):
if actual_node.data>=x:
node = Node(actual_node.data)
last_node.next = node
last_node = node
actual_node.data = actual_node.next.data
actual_node.next = actual_node.next.next
else:
actual_node = actual_node.next
|
ca763b7533760c31f2e2c603dcfb82a6193d1dd4 | gsantam/competitive-programming | /leetcode/sort-characters-by-frequency.py | 443 | 3.5625 | 4 | class Solution:
def frequencySort(self, s: str) -> str:
count = dict()
for letter in s:
if letter not in count:
count[letter] = 0
count[letter] +=1
count = {k: v for k, v in sorted(count.items(), key=lambda item: item[1],reverse = True)}
final_str = ""
for k, v in count.items():
final_str+=k*v
return final_str
|
9877e9112764f61e99d7839cad687611a905ab21 | gsantam/competitive-programming | /advent_of_code/2019/6/2.py | 886 | 3.6875 | 4 | orbits = open("input.txt","r").read().split("\n")
orbit_dict = dict()
in_orbit = set()
for orbit in orbits:
if orbit!='':
planet_1 = orbit.split(")")[0]
planet_2 = orbit.split(")")[1]
if planet_1 not in orbit_dict:
orbit_dict[planet_1] = []
if planet_2 not in orbit_dict:
orbit_dict[planet_2] = []
orbit_dict[planet_1].append(planet_2)
orbit_dict[planet_2].append(planet_1)
found = False
stack = [(0,"YOU")]
visited = set()
while not found:
planet_ = stack.pop()
planet = planet_[1]
depth = planet_[0]
if planet not in visited:
visited.add(planet)
if planet=="SAN":
found = True
else:
if planet in orbit_dict:
for orbit_planet in orbit_dict[planet]:
stack.append((depth+1,orbit_planet))
print(depth -2 )
|
cabdd31e43d25c7977ce15823d859f2e48e441c7 | riteshsharthi/botx | /FAQ/nlp_engine/extractors/email_extractor.py | 351 | 3.90625 | 4 | import re
def email_extractor(input):
match = re.search(r'[\w\.-]+@[\w\.-]+', input)
return match.group(0)
if __name__ == '__main__':
user_input=input("Enter Email information: ")
print(email_extractor(user_input))
#Ref: https://stackoverflow.com/questions/17681670/extract-email-sub-strings-from-large-document |
d9f6e6dc65781bdfdc6018f2817c35a0c3b4d6b4 | riteshsharthi/botx | /FAQ/nlp_engine/extractors/Date_Extractor_Month_name_Final.py | 1,071 | 3.921875 | 4 | from dateutil.parser import parse
import datetime
class DateMonthYear:
def __init__(self):
pass
#self.input = input
def date_extractor(self,input):
date = parse(input, fuzzy=True)
#d = dict({'month': date.month, 'year': date.year})
month=date.month
switcher={
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'November',
12:'December',
}
month_name=switcher.get(month)
d = dict({'month': month_name, 'year': date.year})
for x, y in d.items():
x,y = x,y
x,y = x,y
return d
if __name__ == '__main__':
user_input=input("Enter Date Information: ")
obj=DateMonthYear()
print(obj.date_extractor(user_input))
#date_extractor(user_input)
|
d999688c971c11599747b52a8f1630c1f56e3542 | Ryandalion/Python | /Repetition Structures/Distance Travelled/Distance Travelled/Distance_Travelled.py | 777 | 4.4375 | 4 | # Function that asks the user to input the number of hours they have driven and the speed at which they were driving, the program will then calculate the total distance travelled per hour
distanceTravelled = 0;
numHours = int(input("Please enter the number of hours you drove: "));
speed = int(input("Please enter the average speed of the vehicle: "));
while (numHours < 0):
numHours = int(input("Hours cannot be negative. Please enter the number of hours you drove: "));
while(speed < 0):
speed = int(input("Speed cannot be negative. Please enter the average speed of the vehicle: "));
print("HOUR ---------- DISTANCE TRAVELLED")
for x in range (1, numHours+1, 1):
distanceTravelled = x * speed;
print(x, " ", distanceTravelled,"miles"); |
9cd6a8de3348b4ce3d3209894b1b4bd896d36455 | Ryandalion/Python | /Functions/Home Insurance Cost Evaluator/Home Insurance Cost Evaluator/Home_Insurance_Cost_Evaluator.py | 884 | 4.09375 | 4 | # Function that calculates the home insurnace price given the replacement cost of the home
def calculatePrice(houseCost): # Function calculates the home insurance coverage the user should get based on the property value
replacement = houseCost * .80; # Coverage for 80 % of the home's value
print("The home insurance cost for a house valued at $", houseCost,"requires a minimum insured cost of $", replacement);
def main(): # Main function is responsible for primary handling of functions and user input
print("Home Insurance Cost Estimator");
houseCost = int(input("Enter the replacement cost of the home: "));
while(houseCost < 0): # Input validation
houseCost = int(input("Enter the replacement cost of the home: "));
calculatePrice(houseCost); # Call the calculatePrice to evaluate the dollar coverage amount need for the user's property
main(); |
3d9f49a20ba365934e8a47255bde04df1db32495 | Ryandalion/Python | /Dictionaries and Sets/File Analysis/File Analysis/File_Analysis.py | 1,525 | 4.1875 | 4 | # Program will read the contents of two text files and determine a series of results between the two, such as mutual elements, exclusive elements, etc.
def main():
setA = set(open("file1.txt").read().split()); # Load data from file1.txt into setA
setB = set(open("file2.txt").read().split()); # Load data from file2.txt into setB
mutualElements = setA.intersection(setB); # Mutual Elements - Intersection between the two sets. The values found in both sets.
unionElements = setA.union(setB); # Union Elements - The total array of elements between the two sets
exclusiveElements = unionElements - mutualElements; # Exclusive Elements - List of elements that are exclusive to set A and exclusive to set B, combined
setAelements = unionElements-setB; # Set A Elements - All elements exclusive to set A only
setBelements = unionElements-setA; # Set B Elements - All elements exclusive to set B only
print("Here is some data about the text files"); # Display the data to the user
print("\nMutual Elements: ", mutualElements); # Mutual elements
print();
print("\nExclusive Elements: ", exclusiveElements); # Exclusive elements
print();
print("\nAll Elements: ", unionElements); # Union of set A and set B
print();
print("\nElements of Set A (exclusive): ", setAelements); # Exclusive elements of set A
print();
print("\nElements of Set B (exclusive): ", setBelements); # Exclusive elements of set B
print("Set A and Set B Analysis\n");
main(); # Execute main
|
8104fe235a31ab6451b31519e5c807892c13ef2f | Ryandalion/Python | /Functions/Odd Even Counter/Odd Even Counter/Odd_Even_Counter.py | 961 | 4.0625 | 4 | # Program generates 100 random numbers and determines the number of even and odd numbers in the batch
import random; # Import random module to access randint function
def even_odd(number): # Function determines wheter the parameter is even or odd
if(number % 2 == 0): # If the remainder of the number is zero than the number is even
print("The random number is",number,"and it is even");
print();
else: # Number is odd
print("The random number is",number,"and it is odd");
print();
def main(): # Main function responsible for generating loop and sending argument to determine if even or odd
for x in range (1, 101, 1): # Generate 100 random numbers
number = random.randint(1,1001); # Generate a number between 1 and 1000
even_odd(number); # Send the randomly generated number as an argument to the even_odd function where it's status will be determined
print("Even or Odd Evaluator");
print();
main(); |
564b68912dd8b44e4001a22d92ff18471a55fbe4 | Ryandalion/Python | /Decision Structures and Boolean Logic/Age Calculator/Age Calculator/Age_Calculator.py | 568 | 4.4375 | 4 | # Function takes user's age and tells them if they are an infant, child, teen, or adult
# 1 year old or less = INFANT
# 1 ~ 13 year old = CHILD
# 13 ~ 20 = TEEN
# 20+ = ADULT
userAge = int(input('Please enter your age: '));
if userAge < 0 or userAge > 135:
print('Please enter a valid age');
else:
if userAge <= 1:
print('You are an infant');
elif userAge > 1 and userAge < 13:
print('You are a child');
elif userAge >= 13 and userAge <= 20:
print('You are a teen');
elif userAge >= 20:
print('You are an adult');
|
8a4d3456f828edb3893db4e6dd836873344b91e9 | Ryandalion/Python | /Functions/Future Value/Future Value/Future_Value.py | 1,862 | 4.59375 | 5 | # Program calculates the future value of one's savings account
def calculateInterest(principal, interestRate, months): # Function calculates the interest accumulated for the savings account given the arguments from the user
interestRate /= 100; # Convert the interest rate into a decimal
futureValue = principal * pow(1 + interestRate, months); # Assign the projected balance to the future value variable
return futureValue; # Return future value
def main(): # Function is responsible for user input and validation, calling required functions, and displaying the project account balance to the user
principal = float(input("Enter the current savings account balance: ")); # Collect current balance of savings account
while(principal < 0):
principal = float(input("Account balance must be greater than zero. Enter the current savings account balance: "));
interestRate = float(input("Enter the current interest rate: ")); # Collect the interest rate for the savings account
while(interestRate < 0):
interestRate = float(input("Interest rate must be greater than zero. Enter the current interest rate: "));
months = int(input("Enter the number of months you wish to find the projection for: ")); # Collect the number of months the balance will stay in savings
while(months < 0):
months = int(input("Months be greater than zero. Enter the number of months you wish to find the projection for: "));
account_value = calculateInterest(principal, interestRate, months); # Send the user's inputs as parameters to the calculate interest function and assign the return value to account_value
print("The account will be worth $", format(account_value,'.2f'),"in",months,"months"); # Display the projected account balance to the user
print("Savings Account Future Value Calculator");
print();
main(); |
39cd605853421bafc6abaeda2b905e3bf06b6c6e | Ryandalion/Python | /Functions/Rock, Paper, Scissors!/Rock, Paper, Scissors!/Rock__Paper__Scissors_.py | 2,151 | 4.46875 | 4 | # Program is a simple rock paper scissors game versus the computer. The computer's hand will be randomly generated and the user will input theirs. Then the program will determine the winner. If it is a tie, a rematch will execute
import random; # Import random module to use randint
def generate_random(): # Generate a random number that corresponds to either rock,paper, or scissors
randNum = random.randint(1,3);
return randNum; # Return the generated number to caller
def calculate_winner(userHand, computerHand): # Function calculates the winner between computer and user
if(userHand == 1 and computerHand == 3):
print("User Wins");
elif(userHand == 2 and computerHand == 1):
print("User Wins");
elif(userHand == 3 and computerHand == 2):
print("User Wins");
elif(userHand == 3 and computerHand == 1):
print("Computer Wins");
elif(userHand == 1 and computerHand == 2):
print("Computer Wins");
elif(userHand == 2 and computerHand == 3):
print("Computer Wins");
else: # If it is a draw then we set tie status to true and return to caller
print("It is a tie");
tieStatus = 0;
return tieStatus;
def main(): # Function is responsible for getting user input and calling the appropriate functions and handling the while loop
status = 1;
while(status != -1): # Keep looping until status equals -1
computerHand = generate_random(); # Generate a random number and assign it to computer hand
print("Select your move");
print("1. Rock");
print("2. Paper");
print("3. Scissors");
userHand = int(input()); # Get user's selection
status = calculate_winner(userHand, computerHand); # Send the user's and the computer's hand as arguments to the calculate_winner function
if(status == 0): # If the return value from calculate_winner is 0, a tie has occured and we execute another round
status = 1;
else: # There was a winner and we assign status -1 to exit the while loop and program
status = -1;
print("Rock, Paper, or Scissors");
print();
main(); |
5c7ddb25c658ac69730fa38f111e21dd1531a893 | Ryandalion/Python | /Repetition Structures/Tuition Increase/Tuition Increase/Tuition_Increase.py | 414 | 3.921875 | 4 | # Function that calculates the projected semester tuition amount for next 5 years conditional to a 3 percent increase in tuition each year
tuition = 8000;
increase = 0;
rate = .08;
totalCost = 0;
for x in range (0, 5, 1):
for y in range(0,4,1):
totalCost += tuition;
print("Tuition for year " + str(x + 1) + " is: $", format(totalCost,'.2f'));
tuition += (tuition * rate);
totalCost = 0;
|
456726f300be31e6ea1e3c7659b2370a3b77c53f | Ryandalion/Python | /Strings/Average Number of Words/Average Number of Words/Average_Number_of_Words.py | 3,028 | 4.40625 | 4 | # Program counts the number of words per each sentence in a text file.
def main():
inputFile = open('text.txt','r'); # Open the text file in read only mode
textFile = inputFile.readlines(); # Copy all the contents of the file into the textFile variable
inputFile.close(); # Close the input file
docLength = len(textFile); # Set docLength to the length of the textFile variable
count = 0; # Variable responsible for counting in the loop
numWords = 0; # Counts the number of words per sentence
average = 0; # The average is equal to all the words in the whole document divided by the number of sentences
totalAvg = []; # List holds the number of words per sentence
while count < docLength: # Loop until count exceeds the length of the list
textFile[count] = textFile[count].rstrip('\n'); # First remove the invisible newline characters from the textFile
if "," in textFile[count]: # If there is a comma element inside the textFile list, we remove and replace it with a blank
textFile[count] = textFile[count].replace(',','');
if "-" in textFile[count]: # If there is a hyphen in the textFile list, we remove the hyphen and replace it with a blank
textFile[count] = textFile[count].replace('-',' ');
converted = textFile[count].split(); # We split the element of the list into subelements to separate all words and numbers
index = 0; # Variable is used for indexing the subelements of the elements of the list
numDigits = 0; # Variable is responsible for counting the number of integers that occur amongst the subelements
# CONVERTED = LIST -> LIST ELEMENT -> LIST OF LIST ELEMENT SUB-ELEMENTS
while index < len(converted): # Loop until index is greater than the length of the list of subelements of a list element
if converted[index].isdigit(): # If the subelement is a digit then we increment numDigits by one and increase the index also
numDigits += 1;
index += 1;
else: # The subelement is word so we increment index by one
index += 1;
numWords = len(textFile[count].split()); # Get the number of subelements within the element of the list
numWords = numWords - numDigits; # numWords is equal to the total number of subelements minus numWords
totalAvg.append(numWords); # Append the number of words to the totalAvg list
count += 1; # Increment count by 1
totalSum = sum(totalAvg); # Total sum is calculated using the built-in list function sum that calculates the sum of a list
average = totalSum/docLength; # Average is equal to the sum divided by the number of elements in the textFile list (original file that derived all content from the input file)
print("The average number of words per sentence is",average,"words"); # Print the average number of words per each sentence in the document
print("Number of Words Counter\n");
main(); # Execute main
|
c19b84caf9895177da8ccbcbd845ef5f03653e4d | Ryandalion/Python | /Functions/Fat and Carb Calorie Calculator/Fat and Carb Calorie Calculator/Fat_and_Carb_Calorie_Calculator.py | 1,465 | 4.34375 | 4 | # Function that gathers the carbohyrdates and fat the user has consumed and displays the amount of calories gained from each
def fatCalorie(fat): # Function calculates the calories gained from fat
calFat = fat * 9;
print("The total calories from",fat,"grams of fat is", calFat,"calories");
def carbCalorie(carbs): # Function calculates the calories gained from carbs
carbFat = carbs * 4;
print("The total calories from", carbs,"grams of carbs is", carbFat, "calories");
def main(): # Function gathers user information and validates it. Then sends the arguments to their respective functions`
fat = int(input("Enter the amount of fat in grams consumed today: ")); # Gather fat consumed from user
while(fat < 0): # Validate user input
fat = int(input("Input must be greater than zero. Enter the amount of fat in grams consumed today: "));
carbs = int(input("Enter the amount of carbs consumed today: ")); # Gather carbs consumed from user
while(carbs < 0): # Validate user input
carbs = int(input("Input must be greater than zero. Enter the amount of carbs consumed today: "));
print();
# All inputs have passed validation so we pass the variables to their respective functions
fatCalorie(fat); # Call fatCalorie function and pass fat as argument
print();
carbCalorie(carbs); # Call carbCalorie function and pass carbs as argument
print("Fat and Carb to Calorie Calculator");
print();
main(); |
5d4fa6aaab3cc50ab1b67c9ab5add9ca49d2f25a | Ryandalion/Python | /Decision Structures and Boolean Logic/Roman Numeral Converter/Roman Numeral Converter/Roman_Numeral_Converter.py | 1,269 | 4.21875 | 4 | # Function converts a number to a roman numeral
userNum = int(input('Please enter a literal number between 1 ~ 10 you wish to convert to a Roman numeral: '));
if userNum < 0 or userNum > 10:
print('Please enter a number between 1 and 10');
else:
if userNum == 1:
print('I');
else:
if userNum == 2:
print('II');
else:
if userNum == 3:
print('III');
else:
if userNum == 4:
print('IV');
else:
if userNum == 5:
print('V');
else:
if userNum == 6:
print('VI');
else:
if userNum == 7:
print('VII');
else:
if userNum == 8:
print('VIII');
else:
if userNum == 9:
print('IX');
else:
if userNum == 10:
print('X');
|
2b7ac8c5047791e80d7078a9f678b27c0c79d997 | Ryandalion/Python | /Lists and Tuples/Larger than N/Larger than N/Larger_than_N.py | 1,752 | 4.3125 | 4 | # Program generates a list via random generation and compares it to a user input number n which will determine if the elements within the last are greater than the number
import random; # Import the random module to generate a random integer
def main():
randNum = [0] * 10; # Intialize list with 10 elements of zero
for x in range(10): # Loop 10 times
randNum[x] = random.randint(0,10); # Generate a random number between 0 and 10
x+=1; # Increment x by one
userNum = int(input("Please enter a number: ")); # Get the user's number they wish to compare to the elements of the list
print(randNum); # Print list for verification purposes
numGreater = compareNum(randNum, userNum); # Send the list and the user number to the numGreater function to be evaluated
print("There are",numGreater,"numbers greater than",userNum); # Print the results that were returned by the compare function
def compareNum(userList, userNum): # Function will compare the elements in the list to the user specified number. It will calculate the number of elements that are greater than the user number
numGreater = 0; # Create a numGreater variable to hold the number of elements that are greater than the user specified number
for x in range(len(userList)): # Loop through the length of the list
if userNum < userList[x]: # If list element is greater than user number execute
numGreater += 1; # Increase the numGreater variable by one
x += 1; # Increase the counter variable
else: # If userNum is greater than the list element
x +=1; # Increase x by one
return numGreater; # Return the results to the caller
print("Larger than N\n")
main(); # Execute main
|
b1ed47ef656c15a64464b1c29438a848b42e3665 | TartanLlama/filerover | /filetypechecker.py | 984 | 3.8125 | 4 | """Contains a method to check if a file is text or not
Derived from code found here http://code.activestate.com/recipes/173220-test-if-a-file-or-string-is-text-or-binary/"""
import string, sys
text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
_null_trans = string.maketrans("", "")
def istextfile(filename, blocksize = 512):
"""Given a filename, return True if the file is text, False otherwise"""
return istext(open(filename).read(blocksize))
def istext(s):
"""For internal use only"""
if "\0" in s:
return False
if not s: # Empty files are considered text
return True
# Get the non-text characters (maps a character to itself then
# use the 'remove' option to get rid of the text characters.)
t = s.translate(_null_trans, text_characters)
# If more than 30% non-text characters, then
# this is considered a binary file
if float(len(t))/len(s) > 0.30:
return False
return True
|
65d62036b3be07a9f956a7d1f22de61e92cfd780 | Carlos-Quixtan/practica1-lengusles-Formales- | /prueba2.py | 1,286 | 3.921875 | 4 | import json
from io import open
#print("-------------------------------------------------------------------------------")
#print este cogigo es el bueno para cargar multiples archivos
#print("-------------------------------------------------------------------------------")
datos = input("ingrese dato " )
datos_separados= datos.split(', ') #me separa los datos y mete a un arreglo separado por coma
#print(datos_separados[1])
varCuantosDatosTieneArreglo = len(datos_separados) # para saber cuantos datos tiene el arreglo y con esto correr while
primeraPosicion = 0 #para imprmir la posicion cero del arreglo
while primeraPosicion < varCuantosDatosTieneArreglo:
#print(datos_separados[primeraPosicion])
#primeraPosicion = primeraPosicion + 1
file = open(datos_separados[primeraPosicion])
data = json.load(file)
file.close()
print(data) #sirve para comprobar que si esta cargando los datos
primeraPosicion = primeraPosicion + 1 # le voy sumando 1 a la posicion del arreglo para poder cargar
# todos los datos seleccionados
#variable_cargar =input("CARGAR ")
#variable_lista = [variable_cargar]
#print(datos,datos1)
#file = open(variable_cargar)
#data = json.load(file)
#file.close() |
153851d6acdbaf3e1bd029148de295962b71a1c8 | sushantmishra/pythonbasics | /exceptional2.py | 206 | 3.796875 | 4 | def convert(s):
""" Convert to an int"""
try:
x = int(s)
print("Convertion succeeded! x=",x)
except ValueError:
print("Convertion failed")
x = -1
return x |
9b940938a12425ab4a83156b28cb7246803e8815 | Matheus-Nazario/Persistencia_de_Dados_em_Arquivos | /ler_imprimir_linha_por_linha.py | 176 | 3.734375 | 4 | # ler arquivo de texto linha por linha
arquivo = open("arquivo.txt", "r")
for linha in arquivo: # percorre o arquivo
print(linha) # implime cada linha
arquivo.close()
|
aa9d436ce702a0e1f5388612bfbd491d689165b1 | jackhamel16/MSU-EMresearch-Misc | /rings_method3.py | 3,021 | 3.84375 | 4 | """ Plots rings by checking if points on a plane are within the desired ring,
then plots those points. Also appends them to a file"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
###### FUNCTIONS ######
def create_plane (max_rad,dot_dist):
"""
Creates a plane of dots that encapsulates the rings.
max_rad: radius of max ring, int or float.
dot_dist: distance between dots, int or float.
Returns: meshgrid arrays of the plane dots' x and y positions.
"""
length = max_rad*2
dot_count = length/dot_dist+1
x = np.linspace(0,length,dot_count) - max_rad
y = x[:]
X,Y = np.meshgrid(x,y)
return X,Y
def check_membership(plane_x,plane_y,max_rad,min_rad):
"""
Checks to see if all dots in the plane are in rings and adds them to list.
plane_x: meshgrid array of plane dots' x positions.
plane_y: meshgrid array of plane dots' y positions.
max_rad: radius of max ring, int or float.
min_rad: radius of min ring, int or floar.
Returns: 2 column array of [dot x pos, dot y pos].
"""
ring_dots_x = []
ring_dots_y = []
dot_count = 0
for i,x in np.ndenumerate(plane_x):
y = plane_y[i]
dot_rad = np.sqrt(x**2+y**2)
if dot_rad>=min_rad and dot_rad<=max_rad: #checks radial dist from origin
# dot is within rings.
ring_dots_x.append(x)
ring_dots_y.append(y)
dot_count += 1
return np.array(ring_dots_x),np.array(ring_dots_y),dot_count
def write_file(dot_x,dot_y,dot_z,tf,dc1,dc2,ds,dx,dy,dz):
"""
Appends dot positions to a file with all other needed data
This can be ran on a file multiple times to keep adding rings
"""
file_name = input("Enter save name: ")
file = open(file_name, "a")
for i,dot in np.ndenumerate(dot_x):
print("{:15.8f}{:15.8f}{:15.8f}{:15.8f}{:15.8f}{:15.8f}{:15.8f}\
{:15.8f}{:15.8f}{:15.8f}".format(dot_x[i],dot_y[i],\
float(dot_z),tf,dc1,dc2,ds,dx,dy,dz),file = file)
file.close()
def plot_rings(x,y):
"""
Plots rings as a scatter plot
"""
fig = plt.figure()
axes = fig.add_subplot(111)
axes.scatter(x,y)
###### END FUNCTIONS ######
def main():
"""
Runs whole program
"""
TRANS_FREQ = 2278.9013
DECAY1 = 10
DECAY2 = 10
DIPOLE_STR = 5.2917721e-4
DIPOLE_X = 1
DIPOLE_Y = 0
DIPOLE_Z = 0
MAX_RAD = 0.7
MIN_RAD = 0.6
DOT_DIST = 0.05 #distance in x and y ddirections between dots
DOT_Z = 0
plane_x, plane_y = create_plane(MAX_RAD, DOT_DIST)
# check_membership uses meshgrids as arguements so we create them here
dot_x, dot_y, dot_count = \
check_membership(plane_x, plane_y, MAX_RAD, MIN_RAD)
print("Dot count: "+str(dot_count))
plot_rings(dot_x,dot_y)
write_file(dot_x,dot_y,DOT_Z,TRANS_FREQ,DECAY1,DECAY2,\
DIPOLE_STR,DIPOLE_X,DIPOLE_Y,DIPOLE_Z)
|
b76a75995f2f4512e3cad477403cf22508da7d0a | jackhamel16/MSU-EMresearch-Misc | /min_dist_finder.py | 1,625 | 3.515625 | 4 | import numpy as np
dots_file = open("../sim_results/run16/dots.dat")
def get_coordinates(dots_file):
"""
grabs coordinates of dots from a dots file
returns n x 3 array of coordinates
"""
dots_line_list = [line for line in dots_file]
dot_pos_array = np.zeros((50,3))
dot_count = 0
for line in dots_line_list:
line_list = line.split()
dot_pos_array[dot_count][0] = line_list[0]
dot_pos_array[dot_count][1] = line_list[1]
dot_pos_array[dot_count][2] = line_list[2]
dot_count += 1
if dot_count > 49:
break
return dot_pos_array
def calculate_min_distance(dot_array):
"""
Calculates the minimum distance between two dots in the distribution
dot_array n x 3 array of dot positions
returns minimum distance
"""
min_distance = 10000000 # Needs to be a value greater than the likely min distance
for dot in dot_array:
x_dot,y_dot,z_dot = dot[0],dot[1],dot[2]
for dot in dot_array:
x_dist = x_dot - dot[0]
y_dist = y_dot - dot[1]
z_dist = z_dot - dot[2]
distance = np.sqrt(x_dist**2+y_dist**2+z_dist**2)
if (distance != 0) and distance < min_distance:
min_distance = distance
return min_distance
def main():
dots_file = open("../sim_results/run16/dots.dat")
dot_array = get_coordinates(dots_file)
dots_file.close()
min_dist = calculate_min_distance(dot_array)
print("Minimum separation in distribution is: ", str(min_dist))
|
daee14c84fcbbe19529eae9f874083297fc67493 | run-fourest-run/PythonDataStructures-Algos | /Chapter 3 - Python Data Types and Structures/Sets.py | 2,216 | 4.125 | 4 | '''
Sets are unordered collection of unique items. Sets are mutable, but the elements inside of them are immutable.
* Important distinctions is that the cannot contain duplicate keys
* Sets are typically used to perform mathmatical operations such as intersection, union, difference and complement.
Unlike sequence types, set types do not provide any indexing or slicing operations. There are also no keys associated with values.
'''
player_list = ['alex','spencer','don','don']
cod_players = set(player_list)
'''
Methods and operations:
'''
#len(s)
#length
length = len(cod_players)
#s.copy()
#copy
copy = cod_players.copy()
#s.add()
#add
copy.add('ryan')
#s.difference(t)
#difference --> returns all items in s but not in t
difference = cod_players.difference(copy)
#s.intersection(t)
#intersections --> returns a set of all items in both t and s
intersection = cod_players.intersection(copy)
#s.isdisjoint(t)
#is disjoint --> Returns True if S and t have no items in common
isdisjoint = cod_players.isdisjoint(copy)
#s.issubset(t)
# is subset --> Returns True if all items in s are also in t
subset = cod_players.issubset(copy)
#s.issuperset(t)
# is superset --> Returns True if all items in t are also in s
superset = cod_players.issuperset(copy)
#s.union(t)
# union --> returns a set of all items in s or t
union = cod_players.union(copy)
'''Mutable set object methods '''
#s.add(item)
#add
cod_players.add('doug')
#s.clear()
#clear
copy_cod_players = cod_players.copy()
copy_cod_players.clear()
#s.difference_update(t)
#difference update --? removes all items in s that are also in t
cod_players.difference_update(['spencer','alex'])
#s.discard(item)
#discard --> remove item from set
cod_players.discard('doug')
#s.intersection_update(t)
#intersection update --> removes all items from s that are not in the intersection of s and t
cod_players.intersection_update(['alex'])
#s.pop
#pop --> returns and removes
cod_players.pop('don')
#s.symetric_difference_updater
#symeteric difference updater --> removes all items from s that are not in the symettric difference of s and t (no idea what the fuck that means)
cod_players.symmetric_difference_update(['dontknow'])
|
541784722980135248e21e90d014e6114e95a7e5 | run-fourest-run/PythonDataStructures-Algos | /Chapter 5 - Algorithims/55_thinking_recursively.py | 733 | 3.796875 | 4 | from math import log10, ceil
'''
Python implementation of Karatsuba algo -
Demoing Recursion.
I really am totally lost here.
'''
def karasuba(x,y):
# the base case for recursion
if x < 10 or y < 10:
return x*y
# sets n, the number of digits of the highest input
n = max(int(log10(x) + 1 ), int(log10(y) + 1))
#routs up n/2
n_2 = int(ceil(n / 2.0))
#adds 1 if n is uneven
n = n if n % 2 == 0 else n + 1
a, b = divmod(x, 10**n_2)
c, d = divmod(y, 10**n_2)
#applies the three recursive steps
ac = karasuba(a,c)
bd = karasuba(b,d)
ad_bc = karasuba((a+b),(c+d)) - ac - bd
#performs the multiplication
return (((10**n) *ac) + bd + ((10**n_2)*(ad_bc)))
|
487ef0976d3e4c48df78864d75aa0c83f5339c7f | blqis/jeux | /Mini jeu.py | 2,661 | 3.609375 | 4 | class Aliment:
def __init__(self, nom, prix, point):
self.nom = nom
self.prix = prix
self.point = point
def acheter(self, perso):
if perso.argent >= self.prix:
print(self.nom + " achat possible")
perso.argent = perso.argent - self.prix
else:
print("achat impossible")
class Perso:
def __init__(self, prenom, poids, taille, argent, points_vie):
self.prenom = prenom
self.poids = poids
self.taille = taille
self.argent = argent
self.points_vie = points_vie
def nourrir(self, aliment):
n = aliment.point
if self.points_vie + n >= 0:
self.points_vie = self.points_vie + n
if n > 0:
return self.poids - n * 1/100
return self.poids + n * 1 / 100
return "impossible de se nourrir"
def sprint(self):
self.points_vie = self.points_vie + 1
self.points_vie = self.points_vie - (1 * 1 / 100)
def IMC(self):
if self.poids / self.taille **2 >= 18.5 and self.poids / self.taille **2 <= 25:
return True, "L'IMC de", str(self.prenom), "est de", str(self.poids / self.taille **2), "."
return False, "L'IMC de", str(self.prenom), "est de", str(self.poids / self.taille **2), "."
def bonne_sante(self):
if self.poids / self.taille **2 >= 18.5 and self.poids / self.taille **2 <= 25:
return str(self.prenom), "est en bonne santé."
return str(self.prenom), "n'est pas en bonne santé."
def affichage(self):
print(("{} pèse {} kg et mesure {} m. {} a {} euros et {} points de vie.").format(self.prenom, self.poids, self.taille, self.prenom, self.argent, self.argent, self.points_vie))
Morgane = Perso("Morgane", 50, 1.6, 5, 4)
Paul = Perso("Paul", 60, 1.8, 10, 2)
#Morgane.affichage()
#print(("Morgane pèse {} kg et mesure {} m. Morgane a {} euros et {} points de vie.").format(Morgane.poids, Morgane.taille, Morgane.argent, Morgane.argent, Morgane.points_vie))
#print(("Paul pèse {} kg et mesure {} m. Paul a {} euros et {} points de vie.").format(Paul.poids, Paul.taille, Paul.argent, Paul.argent, Paul.points_vie))
#print(Paul.IMC(), Paul.bonne_sante())
hamburger = Aliment("hamburger", 2, -3)
pomme = Aliment("pomme", 0.5, 1)
eau = Aliment("eau", 1, 1)
hamburger.acheter(Paul)
pomme.acheter(Paul)
eau.acheter(Paul)
Paul.nourrir(eau)
Paul.nourrir(pomme)
Paul.nourrir(hamburger)
paulp = Paul.points_vie
n = 0
while paulp < 4:
n += 1
paulp += 1
print(("Paul doit faire {} sprints.").format(n))
print(Paul.points_vie)
|
aa7224aef4f9c3d2b955f4f3fa08dccd43fba97e | Rifia/DSX | /labvsu/second.py | 2,694 | 3.65625 | 4 | # Лабораторная работа №2
# Input: текст и список слов (из файла и с клавиатуры)
# Задача: найти в тексте все слова, каждое из которых отличается от некоторого слова одной буквой
# и исправить такие слова на слова из списка
# FYI: 1й способ: в лоб, без стандартных встроенных функций по строкам 2й: с ними
# Output: если пользователь попросит, занести результат в файл
# TODO: нечувствительность к регистру
our_text_file = open("res/text_for_second_lab.txt")
word_list_file = open("res/word_list_for_second_lab.txt")
output = open("res/second_output.txt", "w")
def load_dictionary():
i = -1
j = 0
word_list = []
e = our_text_file.read(1)
expr = ('a' <= e <= 'z') or ('A' <= e <= 'Z') or e == '-'
while e != '':
i += 1
while expr:
word_list[i][j] = e
j += 1
e = our_text_file.read(1)
if not expr:
break
print(word_list)
def fix_typo():
text_list = []
hello_word = []
e = our_text_file.read(1)
while ('a' <= e <= 'z') or ('A' <= e <= 'Z') or e == '-':
hello_word.append(e)
e = our_text_file.read(1)
# функция сравнения и поиска слова
output.write(''.join(hello_word))
output.close()
hello_word.clear()
# идем по файлу
# каждое встречное слово заносится в переменную hello_word
# слово - это набор букв, внутри которого допустим только дефис из знаков препинания
# алгоритм выборки слова: слово - до появляения символа не буквы и не дефиса
# и сравнивается со словами, которые есть в списке
# если найдено различие в одной букве
# найти эту букву в слове
# и переписать прямо в файле
# алгоритм: нужно также запомнить место в файле, где произведена остановка
# чтобы потом по индексу отойти назад, заменить букву и перезаписать файл
# TODO: как работать с файлом при перезаписи
|
6bcc83323f6e28da180685293cbbae171a1d1927 | Bayuimamf/TugasADS | /nomor2.py | 180 | 3.953125 | 4 | n = int(input("n:"));
for i in range(1,n):
if i%5 ==0 and i%3 ==0:
print("FizzBuzz")
elif i%3 ==0:
print("Fizz")
elif i%5 ==0:
print("Buzz")
else :
print(i) |
aa727c6de6c93eeef66057a3967d611533d0b7b8 | rafaelvleite/TOTVS-Data-Challenge | /totvs-challenge.py | 4,079 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 14:27:47 2018
@author: rafaelleite
"""
# Recurrent Neural Network
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the training set
dataset_train = pd.read_csv('datasets/real_sales_train.csv')
training_set = dataset_train.iloc[:,0:2].values
# Feature Scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set)
# Creating a data structure with 7 timesteps and t+1 output
timesteps = 7
X_train = []
y_train = []
range_end = len(dataset_train)
for i in range(timesteps, range_end):
X_train.append(training_set_scaled[i-timesteps:i])
y_train.append(training_set_scaled[i])
X_train, y_train = np.array(X_train), np.array(y_train)
# Reshaping
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 2))
# Part 2 - Building the RNN
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
# Initialising the RNN
regressor = Sequential()
# Adding the input layer and the LSTM layer
regressor.add(LSTM(units = 300, input_shape = (timesteps, 2)))
# Adding the output layer
regressor.add(Dense(units = 2))
# Compiling the RNN
regressor.compile(optimizer = 'RMSprop', loss = 'mean_squared_error')
# Fitting the RNN to the Training set
regressor.fit(X_train, y_train, epochs = 50, batch_size = 1)
# Part 3 - Making the predictions and visualising the results
# Getting the real sales amounts
dataset_test = pd.read_csv('datasets/real_sales_test.csv')
test_set = dataset_test.iloc[:,0:2].values
faturamento_real = np.concatenate((training_set[0:range_end], test_set), axis = 0)
# Getting the predicted sales amounts
faturamento_real_escalado = sc.fit_transform(faturamento_real)
inputs = []
for i in range(range_end, 17):
inputs.append(faturamento_real_escalado[i-timesteps:i])
inputs = np.array(inputs)
inputs = np.reshape(inputs, (inputs.shape[0], inputs.shape[1], 2))
predicted_sales_amount = regressor.predict(inputs)
predicted_sales_amount = sc.inverse_transform(predicted_sales_amount)
# Visualising the results
plt.plot(faturamento_real[range_end:,1], color = 'red', label = 'Real Sales Amount')
plt.plot(predicted_sales_amount[:,1], color = 'blue', label = 'Predicted Sales')
plt.title('Sales Forecast')
plt.xlabel('Time')
plt.ylabel('Sales Amount')
plt.legend()
plt.show()
# Part 4 - Forecast for the next 6 days
#creating array with the next 6 days forecasts
inputs_forecast = []
for i in range(range_end, 17):
inputs_forecast.append(faturamento_real_escalado[i-timesteps:i])
proximos_dias = np.array([ [[1,0.15863574],[0,0.32075725],[0.2,0.38609812],[0.4,0.63792434],[0.6,0.41116043],[0.8,0.05466487],[1,0.146379]],
[[0,0.32075725],[0.2,0.38609812],[0.4,0.63792434],[0.6,0.41116043],[0.8,0.05466487],[1,0.146379], [0,0]],
[[0.2,0.38609812],[0.4,0.63792434],[0.6,0.41116043],[0.8,0.05466487],[1,0.146379], [0,0], [0,0]],
[[0.4,0.63792434],[0.6,0.41116043],[0.8,0.05466487],[1,0.146379], [0,0], [0,0], [0,0]] ,
[[0.6,0.41116043],[0.8,0.05466487],[1,0.146379], [0,0], [0,0], [0,0], [0,0]],
[[0.8,0.05466487],[1,0.146379], [0,0], [0,0], [0,0], [0,0], [0,0]]])
inputs_forecast = np.concatenate((inputs_forecast, proximos_dias))
forecast_sales_amount = regressor.predict(inputs_forecast)
forecast_sales_amount = sc.inverse_transform(forecast_sales_amount)
output = dataset_train
output = np.concatenate((output, forecast_sales_amount))
# Visualising the results
plt.plot(faturamento_real[0:,1], color = 'red', label = 'Real Sales Amount')
plt.plot(output[:,1], color = 'blue', label = 'Predicted Sales')
plt.title('Sales Forecast')
plt.xlabel('Time')
plt.ylabel('Sales Amount')
plt.legend()
plt.show()
|
90e9a6e867b5601d2ce5fc2ed648d980eb904b17 | PWalis/Intro-Python-I | /src/10_functions.py | 495 | 4.28125 | 4 | # Write a function is_even that will return true if the passed-in number is even.
# YOUR CODE HERE
def is_even(n):
if n % 2 == 0:
return True
else:
return False
print(is_even(6))
# Read a number from the keyboard
num = input("Your number here")
num = int(num)
# Print out "Even!" if the number is even. Otherwise print "Odd"
# YOUR CODE HERE
def even_odd():
global num
if num % 2 == 0:
return 'Even'
else:
return 'Odd'
print(even_odd())
|
65e41783b8468f030cf0371203be49b69cc4f259 | TBrockmeyer/clickprediction | /plot_descriptives.py | 3,794 | 3.921875 | 4 | # --- Code for creating scatter maps:
# Credits: Manoj Pravakar Saha on https://manojsaha.com/2017/03/08/drawing-locations-google-maps-python/
# --- Code for converting longitude and latitude values to cities:
# https://stackoverflow.com/questions/20169467/how-to-convert-from-longitude-and-latitude-to-country-or-city
import gmplot
import pandas as pd
from random import randint
def plot_map(path_to_csv_file, column_with_geo_codes):
# Convert column_with_geo_codes to int:
column_with_geo_codes = int(column_with_geo_codes)
#Set the cursor
# cur = db_conn.cursor()
# Initialize two empty lists to hold the latitude and longitude values
latitude = [40.835295]
longitude = [-97.700743]
# Import csv with data as dataframe
df = pd.read_csv(path_to_csv_file)
# TODO: Convert column "geo_location" to longitude and latitude, and scatter randomly for better visualization
# TODO: 1. Cut df's geo column after first two letters; add column with coordinates. Use for loop but
# SKIP GOOGLE SEARCH OF LOCATIONS!! But save routine anyway, may be needed later
i = 5
# Convert abbreviated location codes into country, state and area names (as far as applicable)
df_locations = pd.read_csv('csv/country_codes.csv')
### print ("df_locations.iloc[0:3,0:7]", df_locations.iloc[0:3,0:7])
### print ("column_with_geo_codes: ", column_with_geo_codes)
# Extract column with location information from main dataframe
df_entry_location = df.iloc[:,(column_with_geo_codes-1):(column_with_geo_codes)]
# Get the string element providing the location information from the current row in df_entry_location
df_entry_location_0 = df_entry_location.iloc[i,0]
# Determine where the country information ends (and state/area information begins, e.g. in US>TX>632)
try:
df_entry_country_index_end = df_entry_location_0.index(">", 0)
df_entry_country = df_entry_location_0[0:(df_entry_country_index_end)]
except ValueError:
# print ("enter EXCEPTION")
df_entry_country_index_end = len(df_entry_location_0)
df_entry_country = df_entry_location_0
### print ("df_entry_country", df_entry_country)
### print (df_entry_country_index_end)
### print (type(df_entry_country_index_end))
### print ()
# If an available 2-letter country code is found, look up if there is a corresponding country name in the country_codes series element
# First, create two series elements from df_locations, one with the country codes and one with the country names
df_locations_codes = df_locations.iloc[:,1:2]
df_locations_codes = df_locations_codes.iloc[:,0]
df_locations_countries = df_locations.iloc[:,0:1]
df_locations_countries = df_locations_countries.iloc[:,0]
# Determine length of latitude and longitude lists; create equally long lists with random values
# from range 0 to 10; add these lists to latitude and longitude arrays
# Close the cursor and the database connection
# cur.close()
# Create some statistics on users' geographical location
# First, create series element of geographical locations
counts = df_entry_location.iloc[:,0].value_counts()
print (type(counts))
print (counts)
if __name__ == "__main__":
import sys
if len(sys.argv) is not 3:
print ("Usage: python plot_map.py path_to_csv_file column_with_geo_codes_element_of{1, 2, 3, ...}")
else:
# PATH TO CSV FILE TO BE EXPLORED ON YOUR DISK
path_to_csv_file = sys.argv[1]
# NUMBER OF ROWS TO BE SHOWN
column_with_geo_codes = sys.argv[2]
plot_map(path_to_csv_file, column_with_geo_codes)
|
dfe9013698659d952e1d873f2fcf6d19497e185c | RobertHan96/CodeUP_BASIC100_Algorithm | /1046.py | 327 | 3.90625 | 4 | # 세개의 숫자를 입력받아 합과 평균을 출력하는 함수
# 평균은 소수점 첫째자리까지만 반올림해서 표현
def calc() :
a , b, c = input().split(' ')
a = float(a)
b = float(b)
c = float(c)
sum = a+b+c
avg = (a+b+c)/3
print(int(sum))
print(round(avg, 1))
calc() |
0aedd43fd685c050f300b29d7899c85ac6a81eaa | RobertHan96/CodeUP_BASIC100_Algorithm | /1088.py | 637 | 3.75 | 4 | # 1부터 입력한 정수까지 1씩 증가시켜 출력하는 프로그램을 작성하되,
# 3의 배수인 경우는 출력하지 않도록 만들어보자.
# 예를 들면,
# 1 2 4 5 7 8 10 11 13 14 ...
# 와 같이 출력하는 것이다.
# 참고
# 반복문 안에서 continue;가 실행되면 그 아래의 내용을 건너뛰고, 다음 반복을 수행한다.
# 즉, 다음 반복으로 넘어가는 것이다.
def skipThree():
num = int(input("1~100 사이의 정수를 입력하세요"))
i = 0
while i < num:
i += 1
if i % 3 == 0:
continue
print(i, end=" ")
skipThree()
|
a8c66d3b0a7a783d07b03b5f6b7fbb84294ac517 | RobertHan96/CodeUP_BASIC100_Algorithm | /1076.py | 266 | 3.8125 | 4 | # 소문자 a부터 입력한 문자까지 순서대로 공백을 두고 출력한다.
def printChar():
userInput = input()
inputAscii = ord(userInput)
i = ord('a')
while i <= inputAscii:
print(chr(i), end=" ")
i += 1
printChar()
|
7bed489506510173e2a236c8bf3be1fc372cdf15 | RobertHan96/CodeUP_BASIC100_Algorithm | /1054.py | 262 | 3.578125 | 4 | # 두개의 숫자를 입력받아 둘다 값이 1일때만 1을 출력하고, 아니면 0을 출력하는 함수
def calc():
a, b = input().split(' ')
a = int(a)
b = int(b)
if a and b == 1:
print(1)
else:
print(0)
calc()
|
ad0017b73937ba9313620bfc23101a2502707321 | Sumanthsjoshi/capstone-python-projects | /src/get_prime_number.py | 728 | 4.125 | 4 | # This program prints next prime number until user chooses to stop
# Problem statement: Have the program find prime numbers until the user chooses
# to stop asking for the next one.
# Define a generator function
def get_prime():
num = 3
yield 2
while True:
is_prime = True
for j in range(3, num, 2):
if num % j == 0:
is_prime = False
if is_prime:
yield num
num += 2
# Initialize a generator instance
g = get_prime()
# Get the user input
while True:
inp = input("Press enter to get next prime number(Enter any key to stop)")
if not inp:
print(next(g))
else:
print("Stopping the prime generator!!")
break
|
8c99ba43d3481a6190df22b51b93d2d94358f68c | abhic55555/Python | /Assignments/Assignment2/Assignment2_3.py | 440 | 4.15625 | 4 | def factorial(value1):
if value1 > 0:
factorial = 1
for i in range(1,value1 + 1):
factorial = factorial*i
print("The factorial of {} is {}".format(value1,factorial))
elif value1==0:
print("The factorial of 0 is 1 ")
else:-
print("Invalid number")
def main():
value1 = int(input("Enter first number : "))
factorial(value1)
if __name__ == "__main__":
main() |
3725b66c142dece6d0192de11e620e5288fa8c6e | abhic55555/Python | /Assignments/Assignment1/Assignment1_10.py | 178 | 4 | 4 | def getlength(value):
print("Length of {} is {}".format(value, len(value)))
def main():
value=input("Enter name : ")
getlength(value)
if __name__ == "__main__":
main() |
2ba3f3e3d780bbf16068d11e234adeb70655f175 | CHEN-LI-ff/data-analysis | /【链表】singlelinklist_test.py | 3,373 | 3.671875 | 4 | #! usr/bin/env python3
# -*- coding:utf-8 -*-
class Node(object):
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkList(object):
def __init__(self):
self.__head = None
# 单向链表的操作
def travel(self): # 遍历
cur = self.__head
while cur is not None:
print(cur.elem, end=" ")
cur = cur.next
print("")
def length(self): # 长度
count = 0
cur = self.__head
while cur is not None:
count += 1
cur = cur.next
return count
def search(self, item): # 搜索
cur = self.__head
while cur is not None:
if cur.elem == item:
return True
cur = cur.next
return False
def substance(self, item, newitem): # 替换
cur = self.__head
while cur is not None:
if cur.elem == item:
cur.elem = newitem
return
cur = cur.next
print("not find")
# 插入
def hinsert(self, item): # 在开始处插入
node = Node(item)
node.next = self.__head
self.__head = node
def append(self, item): # 在末尾插入
node = Node(item)
cur = self.__head
if self.__head is None:
self.__head = node
else:
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self, pos, item): # 在任意位置插入
node = Node(item)
if pos <= 0:
self.hinsert(item)
elif pos >= self.length():
self.append(item)
else:
count = 0
cur = self.__head
while count < (pos - 1):
count += 1
cur = cur.next
node.next = cur.next
cur.next = node
# 删除
def hdelete(self): # 在开始处删除
if self.__head is not None:
self.__head = self.__head.next
def tdelete(self): # 在末尾删除
cur = self.__head
prev = None
if self.__head is not None:
if self.__head.next is not None:
while cur.next is not None:
prev = cur
cur = cur.next
prev.next = None
else:
self.__head = None
# def delete(self, item): # 删除任意元素
if __name__ == "__main__":
sll = SingleLinkList()
print(sll.length())
sll.append(7)
sll.hinsert(111)
sll.hinsert(20)
sll.hinsert(555)
sll.append(568)
sll.travel()
print(sll.length())
sll.insert(1, 8888)
sll.travel()
sll.insert(-1, 8885)
sll.travel()
sll.insert(6, 8888)
sll.travel()
sll.insert(9, 8889)
sll.travel()
print(sll.search(8889))
print(sll.search(8885))
print(sll.search(10086))
print("*" * 50)
sll.substance(8888, 9999)
sll.travel()
sll.substance(10086, 9999)
sll.substance(8885, 110)
sll.travel()
sll.substance(8889, 1200)
sll.travel()
print("*" * 50)
print("*" * 50)
sll2=SingleLinkList()
sll2.hdelete()
sll2.travel() |
f06acfc27979f222274d5b400cfffc84eb25b7f5 | stoogoff/python-to-javascript | /test-e2e/python/list_comprehension_test.py | 749 | 3.5625 | 4 | import unittest
class ListComprehensionTests( unittest.TestCase ):
def test_ListComprehension_01( self ):
vz = ( 1, 2, 3, 4 )
l = [ v * 3 for v in vz ]
assert l == [ 3, 6, 9, 12 ]
def test_ListComprehension_02( self ):
vz = ( 1, 2, 3, 4 )
l = [ v * 3 for v in vz if 10 / v > 4 ]
assert l == [ 3, 6 ]
def test_ListComprehension_03( self ):
kvz = ( ( 10, 1 ), ( 20, 2 ), ( 30, 3 ) )
l = [ k * 5 + v for k, v in kvz if v * 10 > 15 ]
assert l == [ 102, 153 ]
def test_ListComprehension_04( self ):
kvz = ( ( 10, 1 ), ( 20, 2 ), ( 30, 3 ) )
l = [ kv[ 0 ] * 5 + kv[ 1 ] for kv in kvz if kv[ 1 ] * 10 > 15 ]
assert l == [ 102, 153 ]
|
8ba1f78a8d9ddaab71530743a28f3a0a4589cd09 | unikom2016/strukdat | /week2/insertion.py | 504 | 3.8125 | 4 | #!/usr/bin/env python
import string
def create(data):
for n in range(0,5):
data.append(0)
def traverseInput(data):
for i in range(0,5):
data.append(raw_input("Fill your data: "))
def traverseShow(data):
for x in range(0,5):
print(data[x])
def swap(dataA, dataB):
temp = dataA
dataA = dataB
dataB = temp
def sortBubble(data):
for i in range(0,5):
for j in range(0, i):
swap(data[j + 1], data[j])
list = []
create(list)
traverseInput(list)
traverseShow(list) |
a7e37d533bae15d8571f2cc00a653238e00dc590 | QAMichaelPeng/algs4-python | /algs4/commonutils/random_utils.py | 2,668 | 3.78125 | 4 | import random
from math import sqrt, log, ceil, exp
class StdRandom:
@staticmethod
def set_seed(seed=None):
random.seed(seed)
@staticmethod
def uniform():
"""
Generate a float number in [0.0, 1.0)
:return: a float number in [0.0, 1.0)
"""
return random.random()
@staticmethod
def uniform_int(n):
"""
Generate an int number in [0, n)
:return: an int number in [0, n)
"""
return random.randrange(n)
@staticmethod
def uniform_int_range(a: int, b: int) -> int:
"""
Generate an int number in [a, b)
:return: an int number in [a, b)
"""
return random.randrange(a, b)
@staticmethod
def uniform_range(a: float, b: float) -> float:
"""
Generate an float number in [a, b)
:return: an float number in [a, b)
"""
return random.uniform(a, b)
@staticmethod
def bernoulli(p: float = 0.5):
return 1 if StdRandom.uniform() < p else 0
@staticmethod
def gaussian(mu=0, sigma=1):
# Box Muller algorithm
while True:
x = StdRandom.uniform_range(-1, 1)
y = StdRandom.uniform_range(-1, 1)
r2 = x * x + y * y
if 0 < r2 < 1:
break
return x * sqrt(-2 * log(1 - r2) / r2) * sigma + mu
@staticmethod
def poisson(lam):
exp_lam = exp(-lam)
k = 0
p = 1
while p >= exp_lam:
k += 1
p *= StdRandom.uniform()
return k - 1
def main():
import matplotlib.pyplot as plt
test_functions = []
N = 1000000
a = -5
b = 23
test_functions.append((lambda: StdRandom.uniform_range(a, b), "uniform(%s, %s)" % (a, b)))
test_functions.append((lambda: StdRandom.uniform_int_range(a, b), "uniform_int(%d, %d)" % (a, b)))
p = 0.8
test_functions.append((lambda: StdRandom.bernoulli(p), "bernoulli(%s)" % p))
mu = 33.3
sigma = 44.4
test_functions.append((lambda: StdRandom.gaussian(mu, sigma), "gaussian(%s, %s)" % (mu, sigma)))
lam = 1
test_functions.append((lambda: StdRandom.poisson(lam), "poisson(%s)" % lam))
func_count = len(test_functions)
w = ceil(sqrt(func_count))
h = ceil(func_count / w)
n_bins = 100
fig, axs = plt.subplots(h, w, tight_layout=True)
for i, (func, desc) in enumerate(test_functions):
rfloats = [func() for _ in range(N)]
y, x = i // w, i % w
ax = axs[y][x]
ax.hist(rfloats, bins=n_bins)
ax.set_title(desc)
plt.show(block=True)
if __name__ == "__main__":
main()
|
8aad1cc8337cead4ed82ba6ba20f1f9f9b0e3ad2 | anujism/d6tstack | /d6tstack/read_excel_adv.py | 7,970 | 3.5625 | 4 | import numpy as np
import pandas as pd
from .helpers_ui import *
from openpyxl.utils import coordinate_from_string
def read_excel_advanced(fname, remove_blank_cols=False, remove_blank_rows=False, collapse_header=False,
header_xls_range=None, header_xls_start=None, header_xls_end=None, nrows_preview=3,
logger=None, **kwds):
"""
Excel Advanced Function - Set header ranges and remove blank columns and rows while converting excel to dataframe
Args:
fname_list (list): excel file names, eg ['a.xls','b.xls']
remove_blank_cols (boolean): to remove blank columns in output (default: False)
remove_blank_rows (boolean): to remove blank rows in output (default: False)
collapse_header (boolean): to convert multiline header to a single line string (default: False)
header_xls_range (string): range of headers in excel, eg: A4:B16
header_xls_start (string): Starting cell of excel for header range, eg: A4
header_xls_end (string): End cell of excel for header range, eg: B16
nrows_preview (integer): Initial number of rows to be used for preview columns (default: 3)
log_pusher (object): logger object that sends pusher logs
Returns:
df (dataframe): pandas dataframe
"""
ea = ExcelAdvanced([fname], remove_blank_cols=remove_blank_cols, remove_blank_rows=remove_blank_rows,
collapse_header=collapse_header, header_xls_range=header_xls_range,
header_xls_start=header_xls_start, header_xls_end=header_xls_end, nrows_preview=nrows_preview,
logger=logger)
return ea.read_excel_adv(fname, **kwds)
class ExcelAdvanced:
"""
Excel Advanced Class - Checks columns, generates preview, convert excel to dataframes.
Args:
fname_list (list): excel file names, eg ['a.xls','b.xls']
remove_blank_cols (boolean): to remove blank columns in output (default: False)
remove_blank_rows (boolean): to remove blank rows in output (default: False)
collapse_header (boolean): to convert multiline header to a single line string (default: False)
header_xls_range (string): range of headers in excel, eg: A4:B16
header_xls_start (string): Starting cell of excel for header range, eg: A4
header_xls_end (string): End cell of excel for header range, eg: B16
nrows_preview (integer): Initial number of rows to be used for preview columns (default: 3)
log_pusher (object): logger object that sends pusher logs
"""
def __init__(self, fname_list, remove_blank_cols=False, remove_blank_rows=False, collapse_header=False,
header_xls_range=None, header_xls_start=None, header_xls_end=None, nrows_preview=3, logger=None):
self.fname_list = fname_list
self.remove_blank_cols = remove_blank_cols
self.remove_blank_rows = remove_blank_rows
self.collapse_header = collapse_header
if not (header_xls_start and header_xls_end):
if header_xls_range:
header_xls_range = header_xls_range.split(':')
header_xls_start , header_xls_end = header_xls_range
self.header_xls_start = header_xls_start
self.header_xls_end = header_xls_end
self.nrows_preview = nrows_preview
self.logger = logger
def read_excel_adv(self, io, is_preview=False, **kwds):
"""
# TODO: Handle multiple sheets at once. Each sheet may have difference col and rows range.
Args:
io (string): excel file name or pandas ExcelFile object
is_preview (boolean): to get the dataframe with preview rows only.
Returns:
dataframe
"""
header = []
if self.header_xls_start and self.header_xls_end:
scol, srow = coordinate_from_string(self.header_xls_start)
ecol, erow = coordinate_from_string(self.header_xls_end)
# header, skiprows, usecols
header = [x for x in range(erow - srow + 1)]
usecols = scol + ":" + ecol
skiprows = srow - 1
if is_preview:
workbook = pd.ExcelFile(io)
rows = workbook.book.sheet_by_index(0).nrows
# Get only preview rows. Way to implement nrows (in read_csv)
skip_footer = (rows - skiprows - self.nrows_preview)
df = pd.read_excel(io, header=header, skiprows=skiprows, usecols=usecols,
skip_footer=skip_footer, **kwds)
else:
df = pd.read_excel(io, header=header, skiprows=skiprows, usecols=usecols, **kwds)
else:
df = pd.read_excel(io, **kwds)
if self.remove_blank_cols:
df = df.dropna(axis='columns', how='all')
if self.remove_blank_rows:
df = df.dropna(axis='rows', how='all')
if self.collapse_header:
if len(header) > 1:
df.columns = [' '.join([s for s in col if not 'Unnamed' in s]).strip().replace("\n", ' ')
for col in df.columns.values]
else:
df.rename(columns=lambda x: x.strip().replace("\n", ' '), inplace=True)
return df
def read_excel_adv_all(self, msg=None, is_preview=False):
dfl_all = []
for fname in self.fname_list:
if self.logger and msg:
self.logger.send_log(msg + ' ' + ntpath.basename(fname), 'ok')
df = self.read_excel_adv(fname, is_preview)
dfl_all.append(df)
return dfl_all
def preview_columns(self):
"""
Checks column consistency in list of files. It checks both presence and order of columns in all files
Returns:
col_preview (dict): results dictionary with
files_columns (dict): dictionary with information, keys = filename, value = list of columns in file
columns_all (list): all columns in files
columns_common (list): only columns present in every file
is_all_equal (boolean): all files equal in all files?
df_columns_present (dataframe): which columns are present in which file?
df_columns_order (dataframe): where in the file is the column?
"""
dfl_all = self.read_excel_adv_all(msg='scanning colums of', is_preview=True)
dfl_all_col = [df.columns.tolist() for df in dfl_all]
col_files = dict(zip(self.fname_list, dfl_all_col))
col_common = list_common(list(col_files.values()))
col_all = list_unique(list(col_files.values()))
col_unique = list(set(col_all) - set(col_common))
# find index in column list so can check order is correct
df_col_present = {}
for iFileName, iFileCol in col_files.items():
df_col_present[iFileName] = [ntpath.basename(iFileName), ] + [iCol in iFileCol for iCol in col_all]
df_col_present = pd.DataFrame(df_col_present, index=['filename'] + col_all).T
df_col_present.index.names = ['file_path']
# find index in column list so can check order is correct
df_col_order = {}
for iFileName, iFileCol in col_files.items():
df_col_order[iFileName] = [ntpath.basename(iFileName), ] + [
iFileCol.index(iCol) if iCol in iFileCol else np.nan for iCol in col_all]
df_col_order = pd.DataFrame(df_col_order, index=['filename'] + col_all).T
col_preview = {'files_columns': col_files, 'columns_all': col_all, 'columns_common': col_common,
'columns_unique': col_unique, 'is_all_equal': columns_all_equal(dfl_all_col),
'df_columns_present': df_col_present, 'df_columns_order': df_col_order}
self.col_preview = col_preview
return col_preview |
6844d8f64eb744883982d316af2822abee8548c2 | csdeep189/FullStackEngineer | /ReverseHash.py | 1,307 | 3.953125 | 4 | class RHash:
def __init__(self):
self.letters = 'acdegilmnoprstuw'
self.h = 7
#Function to reverse the hash given in the problem
#reverse of the given algorithm
# Int64 hash (String s) {
# Int64 h = 7
# String letters = "acdegilmnoprstuw"
# for(Int32 i = 0; i < s.length; i++) {
# h = (h * 37 + letters.indexOf(s[i]))
# }
# return h
# }
def reverseHash(self, n):
result = ''
while n > 0:
i = n % 37
try:
result += self.letters[i] # append the letter from the letters String
except IndexError:
print('Invalid Hash value')
n = int(n / 37)
if n == self.h:
return result[::-1] # reverse the result to get the correct hash
if n < self.h: # if value becomes less than the mentioned hash
print('Invalid Hash value')
if __name__ == '__main__':
RHashObj = RHash()
print(RHashObj.reverseHash(930846109532517)) # we have got our answer i.e "lawnmower"
print(RHashObj.reverseHash(680131659347)) # tested this value from question and answer matches the given string |
6f47d6cea76b8b29adfaf491e234496344442c08 | DavidZong/LEDPi | /ledmanual.py | 422 | 3.84375 | 4 | ## This program allows for the manual on off of the LEDs
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
while True:
print "Enter command: "
print "on, off or quit"
next = raw_input("> ")
if next == "quit":
GPIO.output(11, False)
break
elif next == "on":
GPIO.output(11, True)
elif next == "off":
GPIO.output(11, False)
else:
print "Please enter valid command"
GPIO.cleanup() |
17a51bf7ac1f42e8d862bb3eb0c7e23f9d8b0b7a | gaurabdey126/GitDemo | /Practice Questions/7. OOPs.py | 6,277 | 4.4375 | 4 | # OOP Exercise 1: Create a Vehicle class with max_speed and mileage instance attributes
# class Vehicle:
# def __init__(self, max_speed, mileage):
# self.max_speed = max_speed
# self.mileage = mileage
#
# car1 = Vehicle('100 km/hr', '11 ltr')
# car2 = Vehicle('150 km/hr', '9 ltr')
#
# print ('car1 -> max speed is:',car1.max_speed, ' mileage is:',car1.mileage,)
# print ('car2 -> max speed is:',car2.max_speed, ' mileage is:',car2.mileage)
#
# OUTPUT::::
# car1 -> max speed is: 100 km/hr mileage is: 11 ltr
# car2 -> max speed is: 150 km/hr mileage is: 9 ltr
#############################################################################################################################
# OOP Exercise 2: Create a Vehicle class without any variables and methods
# class Vehicle:
# pass
#########################################################################################################################
# OOP Exercise 3: Create a child class Bus that will inherit all of the variables and methods of the Vehicle class
# Create a Bus object that will inherit all of the variables and methods of the Vehicle class and display it.
#
# class Vehicle:
#
# def __init__(self, name, max_speed, mileage):
# self.name = name
# self.max_speed = max_speed
# self.mileage = mileage
#
# class Bus(Vehicle):
# pass
#
# bus1=Bus('Volvo','180 km/hr','8 km/ltr')
#
# print (bus1.name, bus1.max_speed, bus1.mileage, sep=', ')
#
# OUTPUT::::
# Volvo, 180 km/hr, 8 km/ltr
###########################################################################################################################
# OOP Exercise 4: Class Inheritance
# Given:
# Create a Bus class that inherits from the Vehicle class. Give the capacity argument of Bus.seating_capacity() a default value of 50.
# Use the following code for your parent Vehicle class. You need to use method overriding.
#
# class Vehicle:
# def __init__(self, name, max_speed, mileage):
# self.name = name
# self.max_speed = max_speed
# self.mileage = mileage
#
# def seating_capacity(self, capacity=80):
# return f"The seating capacity of a {self.name} is {capacity} passengers"
#
# class Bus(Vehicle):
# def seating_capacity(self, capacity=50):
# return f"The seating capacity of a {self.name} is {capacity} passengers"
#
# bus1=Bus('Volvo','180 km/hr','8 km/ltr')
# print (bus1.seating_capacity())
#
# OUTPUT:::::
# The seating capacity of a Volvo is 50 passengers
########################################################################################################################
# OOP Exercise 5: Define property that should have the same value for every class instance
# Define a class attribute”color” with a default value white. I.e., Every Vehicle should be white.
# Use the following code for this exercise.
#
# class Vehicle:
# color = 'White'
# def __init__(self, name, max_speed, mileage):
# self.name = name
# self.max_speed = max_speed
# self.mileage = mileage
#
# class Bus(Vehicle):
# pass
#
# class Car(Vehicle):
# pass
#
# bus1=Bus('Volvo','180 km/hr','8 km/ltr')
# car1=Car('BMW','250 km/hr','10 km/ltr')
#
# print ('Bus -> name:',bus1.name, 'max speed:',bus1.max_speed, 'mileage:',bus1.mileage, 'color:',bus1.color)
# print ('Car -> name:',car1.name, 'max speed:',car1.max_speed, 'mileage:',car1.mileage, 'color:',car1.color)
#
# OUTPUT:::
# Bus -> name: Volvo max speed: 180 km/hr mileage: 8 km/ltr color: White
# Car -> name: BMW max speed: 250 km/hr mileage: 10 km/ltr color: White
#############################################################################################################################
# OOP Exercise 6: Class Inheritance
# # Given:
# # Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle is seating capacity * 100.
# # If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge.
# # So total fare for bus instance will become the final amount = total fare + 10% of the total fare.
# # Note: The bus seating capacity is 50. so the final fare amount should be 5500.
# # You need to override the fare() method of a Vehicle class in Bus class.
# # Use the following code for your parent Vehicle class. We need to access the parent class from inside a method of a child class.
#
# class Vehicle:
# def __init__(self, name, mileage, capacity):
# self.name = name
# self.mileage = mileage
# self.capacity = capacity
#
# def fare(self):
# return float(self.capacity * 100)
#
# class Bus(Vehicle):
# def fare(self):
# total_fare= self.capacity * 100
# final_fare = total_fare + 0.1*(total_fare)
# return float(final_fare)
#
# veh1 = Vehicle ("BMW", 14, 5)
# print("Total Vehicle fare is:", veh1.fare())
#
# bus1 = Bus("School Volvo", 12, 50)
# print("Total Bus fare is:", bus1.fare())
#
# # OUTPUT:::::
# # Total Vehicle fare is: 500.0
# # Total Bus fare is: 5500.0
##################################################################################################################################################################
# OOP Exercise 7: Determine which class a given Bus object belongs to (Check type of an object)
#
# class Vehicle:
# def __init__(self, name, mileage, capacity):
# self.name = name
# self.mileage = mileage
# self.capacity = capacity
#
# class Bus(Vehicle):
# pass
#
# School_bus = Bus("School Volvo", 12, 50)
# print(type(School_bus)) # <class '__main__.Bus'>
####################################################################################################################
# OOP Exercise 8: Determine if School_bus is also an instance of the Vehicle class
# #
# class Vehicle:
# def __init__(self, name, mileage, capacity):
# self.name = name
# self.mileage = mileage
# self.capacity = capacity
#
# class Bus(Vehicle):
# pass
#
# School_bus = Bus("School Volvo", 12, 50)
# # # use Python's built-in isinstance() function
# print(isinstance(School_bus, Vehicle)) #True
######################################################################################################################
|
cc94a6f66b8c0eebef52e77556690aad8a308dc2 | gaurabdey126/GitDemo | /Practice Questions/Function.py | 3,500 | 3.90625 | 4 | #Create a function that can accept two arguments name and age and print its value
# def personal(name, age):
# print(name)
# print(age)
#
# personal('Gaurab', 32)
######################################################################################################
#Exercise 4: Create a function showEmployee() in such a way that it should accept employee name, and its salary and display both. If the salary is missing in the function call assign default value 9000 to salary
# def showEmployee(name, salary=9000): ###setting 9000 as default
# print ('Employee',name, 'salary is', salary)
#
# showEmployee('John')
# showEmployee('John', 12000)
#
# OUTPUT::::
# Employee John salary is 9000
# Employee John salary is 12000
###########################################################################################################################
# Exercise 3: Write a function calculation() such that it can accept two variables and calculate the addition and subtraction of them.
# # And also it must return both addition and subtraction in a single return call
#
# def calculation(a,b):
# sum=a+b
# if a>b:
# subtract=a-b
# else:
# subtract=b-a
# return sum,subtract
#
# print(calculation(100,1000))
#
# OUTPUT::::
# (1100, 900)
#################################################################################################################
# Exercise 5: Create an inner function to calculate the addition in the following way
# Create an outer function that will accept two parameters, a and b
# Create an inner function inside an outer function that will calculate the addition of a and b
# At last, an outer function will add 5 into addition and return it
#
# def outer(a,b):
# def inner(a,b):
# add1= a+b
# return add1
# add2=inner(a,b)+5
# print (add2)
#
# outer(100, 1000)
#
# OUTPUT:::
# 1105
#####################################################################################################################
# Exercise 6: Write a recursive function to calculate the sum of numbers from 0 to 10
# def calSum(num):
# if num:
# return num+calSum(num-1)
# else:
# return 0
#
# print (calSum(10))
#
# OUTPUT::::
# 55
########################################################################################################################
# Exercise 7: Assign a different name to function and call it through the new name
# def oldFunc(name, age):
# print ('Name of student is {} and age is {}'.format(name,age))
#
# newFunc= oldFunc
#
# newFunc('John',32)
#
# OUTPUT:::::
# Name of student is John and age is 32
######################################################################################################################
# Exercise 8: Generate a Python list of all the even numbers between 4 to 30
# def even(a,b):
# x=[]
# for i in range (a,b):
# if i%2==0:
# x.append(i)
# i+=1
# print (x)
#
# even(4,30)
# OUTPUT::::
# [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
# [OR]
# print(list( range(4, 30, 2))) ### [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
#################################################################################################################
# Exercise 9: Return the largest item from the given list
# aList = [4, 6, 8, 24, 12, 2]
# print(max(aList)) ### 24
##################################################################################################################
|
54018601625787d61a411ca80063ae79f639285e | gaurabdey126/GitDemo | /Initial Practice/Inheritance_Hands On.py | 4,621 | 3.96875 | 4 | #No link any of the classes
# class A:
# def feat1(self):
# print ('feat1 is working')
#
# def feat2(self):
# print ('feat2 is working')
#
# class B:
# def feat3(self):
# print('feat3 is working')
#
# def feat4(self):
# print('feat4 is working')
#
# class C:
# def feat5(self):
# print ('feat5 is working')
#
# a1=A()
# b1=B()
# c1=C()
#
# a1. #can access only feat1 and feat2
# b1. #can access only feat3 and feat4
# c1. #can access only feat5
###############################################################################################################################
##SINGLE LEVEL INHERITANCE BETWEEN A and B
##MULTI LEVEL INHERITANCE BETWEEN A and C
# class A:
# def feat1(self):
# print ('feat1 is working')
#
# def feat2(self):
# print ('feat2 is working')
#
# class B(A):
# def feat3(self):
# print('feat3 is working')
#
# def feat4(self):
# print('feat4 is working')
#
# class C(B):
# def feat5(self):
# print ('feat5 is working')
#
# a1=A()
# b1=B()
# c1=C()
#
# a1. #can access only feat1 and feat2
# b1. #can access only feat1 2 3 4
# c1. #can access only feat1 2 3 4 5
#####################################################################################################################################
## C can access features from both A and B (MULTIPLE INHERITANCE)
# class A:
# def feat1(self):
# print ('feat1 is working')
#
# def feat2(self):
# print ('feat2 is working')
#
# class B():
# def feat3(self):
# print('feat3 is working')
#
# def feat4(self):
# print('feat4 is working')
#
# class C(A,B):
# def feat5(self):
# print ('feat5 is working')
#
# a1=A()
# b1=B()
# c1=C()
#
# a1. #can access only feat1 and feat2
# b1. #can access only feat3 4
# c1. #can access only feat1 2 3 4 5
#################################################################################################################################
#CONSTRUCTOR IN INHERITANCE:
#1
# class A:
# def __init__(self):
# print('init A')
#
# def feat1(self):
# print ('feat1 is working')
#
# def feat2(self):
# print ('feat2 is working')
#
# class B(A):
# def feat3(self):
# print('feat3 is working')
#
# def feat4(self):
# print('feat4 is working')
#
# a1 = B() #since B doesnt have constructor, it will the constructor from A
# Output:::::
# init A
###########################################################################
#2
# class A:
# def __init__(self):
# print('init A')
#
# def feat1(self):
# print ('feat1 is working')
#
# def feat2(self):
# print ('feat2 is working')
#
# class B(A):
# def __init__(self):
# print('init B')
#
# def feat3(self):
# print('feat3 is working')
#
# def feat4(self):
# print('feat4 is working')
#
# # a1 = B() #since B HAVE a own constructor, it will take that rather than getting from classA
#
# # Output::::
# # init B
# ###################################################################################
# #3
#
# class A:
# def __init__(self):
# print('init A')
#
# def feat1(self):
# print ('feat1 is working')
#
# def feat2(self):
# print ('feat2 is working')
#
# class B(A):
# def __init__(self):
# print('init B')
# super().__init__() #this will call the Consructor from Super Class A
#
# def feat3(self):
# print('feat3 is working')
#
# def feat4(self):
# print('feat4 is working')
#
# a1 = B() #since B HAVE a own constructor, it will take that rather than getting from classA
#
# Output::::
# init B
# init A
#######################################################################################################################
#4
class A:
def __init__(self):
print('init A')
def feat1(self):
print ('feat1 is working')
def feat2(self):
print ('feat2 is working')
class B: #B is not sub class of A
def __init__(self):
print('init B')
def feat3(self):
print('feat3 is working')
def feat4(self):
print('feat4 is working')
class C(B,A):
def __init__(self):
super().__init__()
print('init C')
def feat5(self):
print ('feat5 is working')
a1 = C() #Object creation in C and calling the constructor
# OUTPUT:::::::::
# init A #It takes the order from Left to Right (A, B)
# init C
# init B #It takes the order from Left to Right (B, A)
# init C |
c6d023d790603e312690c71bcdbe4200b9e2472c | Nilesh7756/python-learning-scripts | /session-scripts/square.py | 85 | 3.5 | 4 | import sys
def square_num(num):
sq = num * num
print (sq)
square_num(5) |
6b89934c7911e7f1c24db7c739b46eb26050297c | Tyler668/Code-Challenges | /twoSum.py | 1,018 | 4.1875 | 4 | # # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# # (i.e., [0, 1, 2, 4, 5, 6, 7] might become[4, 5, 6, 7, 0, 1, 2]).
# # You are given a target value to search. If found in the array return its index, otherwise return -1.
# # You may assume no duplicate exists in the array.
# # Your algorithm's runtime complexity must be in the order of O(log n).
# # Example 1:
# # Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
# # Output: 4
# # Example 2:
# # Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3
# # Output: -1
# def search(nums, target):
# mid = len(nums) // 2
# # print(mid, nums[mid])
# if nums[mid] == target:
# return mid
# elif nums[mid] > target:
# lowerHalf
# nums = [4, 5, 6, 7, 0, 1, 2, 19]
# target = 0
# print(search(nums, target))
def double_char(txt):
solution = ''
for i in range(len(txt)):
double = 2 * txt[i]
solution += double
return solution
print(double_char("Hello"))
|
1027294d654d81120d1435e7512a67d4bed764a2 | Tyler668/Code-Challenges | /functions.py | 583 | 4.03125 | 4 | # pass-by-reference vs pass-by-value
# define a function that multiplies its input by 2
# Single values typically passed by value
def mult_by_2(x):
x = x*2
return x
y = 12
z = mult_by_2(y)
print(z)
myList = [1, 2, 3]
# Typically data structures passed into a function are passed by reference
def mult2_list(l):
for i in range(len(l)):
l[i] *= 2
print(myList)
mult2_list(myList)
print(myList)
def makeUpper(string):
string = string.upper()
return string
myString = "hello"
makeUpper(myString)
print(myString)
# Strings are pass by value
|
3d98d0a42963ab744fb4151ed58055a2678acb2b | Tyler668/Code-Challenges | /classes.py | 1,091 | 3.984375 | 4 | # Classes
class MedianFetcher:
def __init__(self): # Constructor self = this
# Define attributes
self.median = None # None = null and must be capitalized
self.numbers = []
# Inserts the value n into our class
def insert(self, n):
self.numbers.append(n)
self.numbers.sort()
# Where do we store n?
# Maybe we store it in self.median?
# What happens when we insert more values?
def get_median(self):
if len(self.numbers) == 1:
return self.numbers[0]
mid = len(self.numbers) // 2
if len(self.numbers) % 2 == 1:
# If it's odd
return self.numbers[mid]
else:
# If it's even
mean = ((self.numbers[mid] + self.numbers[mid -1])/2)
return mean
def foo():
pass # pass is like closing the braces to signify the end of a function
medianFetcher = MedianFetcher()
medianFetcher.insert(5)
medianFetcher.insert(6)
medianFetcher.insert(7)
medianFetcher.insert(9)
print(medianFetcher.get_median())
|
35c294e745ede8519ec47c83d4e9b583a52f3c9c | SaiJyothiGudibandi/Python_CS5590-490-0001 | /Assignments/Assignment7/Source/file_funs.py | 1,276 | 3.65625 | 4 | import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from collections import Counter
import string
text1 = ""
fr = open("sample").read()
sw = set(stopwords.words('english')) #stop words
for s in fr.lower().split():
if s not in sw:
text1 = text1 + ' ' + s
print ("Data after removing the stop words:")
print (text1)
print(" ")
puncs = set(string.punctuation) #punction removal
text2 = ''.join(s for s in text1 if s not in puncs)
print ("Data After Removing The Punctions:")
print(text2)
print(" ")
t = word_tokenize(text2) #tokenzing the data
rv = nltk.pos_tag(t)
rv = nltk.pos_tag(t)
text3 = []
for p in rv:
if 's' not in p[1]:
text3.append(p[0])
print ("Data After Removing Verbs:")
print (text3)
print(" ")
#counting the frequency
summary = ""
freq = Counter(text3).most_common(5)
print("Most Frequent Words:")
print (freq)
print(" ")
# summarizing the text
for most in freq:
for rew in sent_tokenize(fr.lower()):
if rew not in summary:
if most[0] in word_tokenize(rew):
summary = summary + rew
print("Sentences with frequent words:")
print(summary)
print(" ")
|
15be302b0b417de9eb462b731ad20a0d78e448d8 | SaiJyothiGudibandi/Python_CS5590-490-0001 | /ICE/ICE1/2/Reverse.py | 328 | 4.21875 | 4 | num = int(input('Enter the number:')) #Taking nput from the user
Reverse = 0
while(num > 0): #loop to check whether the number is > 0
Reminder = num%10 # finding the reminder for number
Reverse = (Reverse * 10) + Reminder
num = num // 10
print('Reverse for the Entered number is:%d' %Reverse)
|
e4682da4df50f7d7d22362843807ef0dfe54923c | PaperMadeGames/elements | /ai.py | 3,984 | 3.796875 | 4 | from board import Board
from copy import deepcopy
from random import choice
class AI:
def __init__(self, color):
# 'color' is the color this AI will play with (B or W)
self.color = color
def minimax(self, current_board, is_maximizing, depth, turn):
# Tries to find recursively the best value depending on which player is passed as an argument to the function
if depth == 0 or current_board.get_winner() is not None:
return self.get_value(current_board)
next_turn = 'B' if turn == 'W' else 'W'
board_color_up = current_board.get_color_up()
current_pieces = current_board.get_pieces()
piece_moves = list(map(lambda piece: piece.get_moves(current_board) if piece.get_color() == turn else False, current_pieces))
if is_maximizing:
# A max player will attempt to get the highest value possible.
maximum = -999
for index, moves in enumerate(piece_moves):
if moves == False:
continue
for move in moves:
aux_board = Board(deepcopy(current_pieces), board_color_up)
aux_board.move_piece(index, int(move["position"]))
maximum = max(self.minimax(aux_board, False, depth - 1, next_turn), maximum)
return maximum
else:
# A min player will attempt to get the lowest value possible.
minimum = 999
for index, moves in enumerate(piece_moves):
if moves == False:
continue
for move in moves:
aux_board = Board(deepcopy(current_pieces), board_color_up)
aux_board.move_piece(index, int(move["position"]))
minimum = min(self.minimax(aux_board, True, depth - 1, next_turn), minimum)
return minimum
def get_move(self, current_board):
# Receives a Board object, returns the move it finds best suited.
board_color_up = current_board.get_color_up()
current_pieces = current_board.get_pieces()
next_turn = "W" if self.color == "B" else "B"
player_pieces = list(map(lambda piece: piece if piece.get_color() == self.color else False, current_pieces))
possible_moves = []
move_scores = []
for index, piece in enumerate(player_pieces):
if piece == False:
continue
for move in piece.get_moves(current_board):
# The value of the key "piece" is the index of the piece on player_pieces that can make the move assigned on the key "move".
possible_moves.append({"piece": index, "move": move})
# If any jump move is available, only jump moves can be made (checkers rule).
jump_moves = list(filter(lambda move: move["move"]["eats_piece"] == True, possible_moves))
if len(jump_moves) != 0:
possible_moves = jump_moves
# Calls minimax for all possible moves and stores the moves with higher values.
for move in possible_moves:
aux_board = Board(deepcopy(current_pieces), board_color_up)
aux_board.move_piece(move["piece"], int(move["move"]["position"]))
move_scores.append(self.minimax(aux_board, False, 2, next_turn))
best_score = max(move_scores)
best_moves = []
for index, move in enumerate(possible_moves):
if move_scores[index] == best_score:
best_moves.append(move)
# Chooses a random move just in case there are more than one "good" move, then returns it properly.
move_chosen = choice(best_moves)
return {"position_to": move_chosen["move"]["position"], "position_from": player_pieces[move_chosen["piece"]].get_position()}
def get_value(self, board):
# Receives a Board object, returns a value depending on which player won or which player has the most pieces on board.
# The value is higher if the board benefits this AI and lower otherwise.
board_pieces = board.get_pieces()
if board.get_winner() is not None:
if board_pieces[0].get_color() == self.color:
return 2
else:
return -2
total_pieces = len(board_pieces)
player_pieces = len(list(filter(lambda piece: piece.get_color() == self.color, board_pieces)))
opponent_pieces = total_pieces - player_pieces
if player_pieces == opponent_pieces:
return 0
return 1 if player_pieces > opponent_pieces else -1 |
b14c3c6c1964d07f09fd4ca6bacb91844d61df60 | PaperMadeGames/elements | /piece.py | 4,488 | 3.96875 | 4 | from utils import get_position_with_row_col
class Piece:
def __init__(self, name):
# Example: <position><color><isKing?> 16WN
self.name = name
self.has_eaten = False # True if the piece instance has eaten a piece in its last move
def get_name(self):
return self.name
def get_position(self):
return self.name[:-2]
def get_color(self):
return self.name[-2]
def get_has_eaten(self):
return self.has_eaten
def is_king(self):
return True if self.name[-1] == 'Y' else False
def set_position(self, new_position):
# Receives a new position and assigns it.
# position_index is used because the position part of self.name can be a one or two digit number.
position_index = 1 if len(self.name) == 3 else 2
self.name = str(new_position) + self.name[position_index:]
def set_is_king(self, new_is_king):
is_king = "Y" if new_is_king else "N"
self.name = self.name[:-1] + is_king
def set_has_eaten(self, has_eaten):
self.has_eaten = has_eaten
def get_adjacent_squares(self, board):
# Receives a Board object, returns at max four squares, all of which are potential moves
current_col = board.get_col_number(int(self.get_position()))
current_row = board.get_row_number(int(self.get_position()))
all_coords = []
if self.is_king():
all_coords = [(current_row - 1, current_col - 1), (current_row - 1, current_col + 1), (current_row + 1, current_col - 1), (current_row + 1, current_col + 1)]
else:
if board.get_color_up() == self.get_color():
all_coords = [(current_row - 1, current_col - 1), (current_row - 1, current_col + 1)]
else:
all_coords = [(current_row + 1, current_col - 1), (current_row + 1, current_col + 1)]
# Because of the offset values above (+1 or -1), it's necessary to check if any invalid coordinates are on the list.
return list(filter(lambda coords: coords[0] != -1 and coords[0] != 8 and coords[1] != -1 and coords[1] != 8, all_coords))
def get_moves(self, board):
# Receives a board, returns all possible moves. For more info check test specifications.
def get_eat_position(piece, coords):
# Receives a piece that is obstructing this piece's way and its (row, column) coordinates.
# Returns the position to move in order to eat the piece, or None if it's impossible.
if (piece.get_color() == own_color) or (coords[0] in (0, 7)) or (coords[1] in (0, 7)):
return None
if coords[1] > current_col:
# (coords[0] - current_row) returns 1 if the target is below this piece, and -1 otherwise.
position_to_eat = (coords[0] + (coords[0] - current_row), coords[1] + 1)
else:
position_to_eat = (coords[0] + (coords[0] - current_row), coords[1] - 1)
position_num = get_position_with_row_col(position_to_eat[0], position_to_eat[1])
return None if board.has_piece(position_num) else position_num
current_col = board.get_col_number(int(self.get_position()))
current_row = board.get_row_number(int(self.get_position()))
possible_moves = []
own_color = self.get_color()
possible_coords = self.get_adjacent_squares(board)
close_squares = board.get_pieces_by_coords(*possible_coords)
empty_squares = []
for index, square in enumerate(close_squares):
# Empty squares are potential moves. Pieces are potential eating movements.
if square is None:
empty_squares.append(index)
else:
position_to_eat = get_eat_position(square, possible_coords[index])
if position_to_eat is None:
continue
possible_moves.append({"position": str(position_to_eat), "eats_piece": True})
if len(possible_moves) == 0:
# This is skipped if this piece can eat any other, because it is forced to eat it.
for index in empty_squares:
new_position = get_position_with_row_col(possible_coords[index][0], possible_coords[index][1])
possible_moves.append({"position": str(new_position), "eats_piece": False})
return possible_moves |
badb56f269035fdfb3c8b1c7af469bdf0816f797 | Pato38/EDI | /ejercicios python/tp3 prog-Piccadaci.py | 9,054 | 4.15625 | 4 | #1. Implementaremos una clase llamada Persona que tendrá como atributo (variable) el nombre de la persona y dos métodos (funciones).
# El primero de los métodos inicializará el atributo nombre y el segundo mostrará por pantalla el contenido del mismo.
# Definir dos instancias (objetos) de la clase Persona.
class Persona():
def __init__(self):
self.nombre=input("ingrese nombre del empleado: ")
def mostrar(self):
print(" El Nombre de la persona es : ",self.nombre)
def setNombre(self,nombre):
self.nombre=nom??
def getNombre(self):
return self.nombre
#2. Declarar una segunda clase llama Empleado que hereda de la clase Persona y agrega el atributo sueldo.
# Debe mostrar si tiene que pagar impuestos o no (sueldo superior a 3000). Crear un objeto de cada clase.
class Empleado(Persona):
def __init__ (self):
super().__init__()
self.sueldo=float(input("ingrese sueldo: "))
def mostrar(self):
super().mostrar()
print("Sueldo: ",self.sueldo)
def paga_imp(self):
if self.sueldo > 3000:
print(" Debe pagar impuesto")
else:
print("No paga impuesto")
Persona1= Persona()
Persona1.mostrar()
Empleado1=Empleado()
Empleado1.mostrar()
Empleado1.paga_imp()
#3. Realizar un programa que conste de una clase llamada Alumno que tenga como atributos el nombre y la nota del alumno.
# Definir los métodos para inicializar sus atributos, imprimirlos y mostrar un mensaje con el resultado de la nota
# y si ha aprobado o no.´
class Alumno():
def __init__(self):
print("alumno-nota")
self.nom = input("ingrese nombre del alumno: ")
self.nota = int(input("ingrese nota obtenida: "))
def setNota(self,nota):
self.nota = nota
def getNota(self):
return self.nota
def mostrar(self):
print(" Nombre: ",self.nom,"Nota: ",self.nota)
def aprobados(self):
if self.nota >= 7:
print( self.nom, "ha aprobado ")
else:
print( self.nom, "ha desaprobado")
alumno1=Alumno()
alumno1.mostrar()
alumno1.aprobados()
#4. Realizar un programa que tenga una clase Persona con las siguientes características.
#Implementar los métodos necesarios para inicializar los atributos, mostrar los datos e
#indicar si la persona es mayor de edad o no.
class Persona():
def __init__(self):
print("mayores de edad")
self.nom=input("ingrese nombre de la persona: ")
self.edad=int(input("ingrese edad: "))
def mostrar(self):
print(" ")
print("Nombre: ",self.nom)
print ( "edad: ",self.edad)
def setNombre(self,nom):
self.nom
def getNombre(self):
return self.nom
def __str__(self):
print(self.nom)
def mayoredad(self):
if self.edad >= 18:
print(" la persona es mayor de edad")
else:
print("la persona es menor de edad")
persona1=Persona()
persona1.mostrar()
persona1.mayoredad()
#5. Realizar una clase que administre una agenda. Se debe almacenar para cada contacto el nombre,
# el teléfono y el email. Además deberá mostrar un menú con las siguientes opciones
# Añadir contacto. Lista de contactos Buscar contacto Editar contacto Cerrar agenda
class Agenda():
def __init__(self):
self.contactos=[]
def menu(self):
print()
menu=[["1.agenda"],
["2.añadir contacto"],
["3.lista de contactos"],
["4.buscar contactos"],
["5.editar contacto"],
["6.cerrar agenda"]]
for i in range (6):
print(" ")
print (menu[i][0])
seleccion=input("Seleccione la opción deseada: ")
if seleccion == 1:
self.agenda()
elif seleccion == 2:
self.añadir()
elif seleccion == 3:
self.lista()
elif seleccion == 4:
self.buscar()
elif seleccion == 5:
self.editar()
elif seleccion == 6:
print("usted está saliendo de la agenda")
def añadir(self):
print(" ")
print("añadir nuevo contacto: ")
super().__init__()
seguir = 's'
while(seguir!='n'):
datos_contacto={}
datos_contacto={
'nom':input("ingrese nombre de contacto: "),
'tel':int(input("ingrese el teléfono del contacto: ")),
'email':input("ingrese el mail del contacto: ")}
self.contactos.append(datos_contacto)
seguir = input("¿Desea cargar un nuevo contacto? [s/n] ")
print(self.contactos)
return self.contactos
def lista(self):
print(" ")
print(" Lista de contactos")
if len(self.contactos) == 0:
print("no hay contactos en la lista")
else:
for i in range (len(self.contactos)):
print(self.contactos[i]['nom'])
def busqueda(self):
print(" ")
print("buscar contactos")
nom=input("introduzca el nombre de su contacto: ")
for i in range (len(self.contactos)):
if nom == self.contactos[i]['nom']:
print("Nombre: ",self.contactos[i]['nom'])
print("teléfono: ",self.contactos[i]['tel'])
print("mail: ",self.contactos[i]['email'])
return i
def editar(self):
print(" ")
print("editar contacto")
nom=input("introduzca el nombre de su contacto: ")
for i in range (len(self.contactos)):
if nom == self.contactos[i]['nom']:
finalizar=False
while finalizar == False:
print("1. nombre")
print("2.teléfono")
print("3.mail")
print("4.exit")
opcion=int(input("Seleccione el número de la opción que desea modificar: "))
if opcion == 1:
nom=input("introduzca el nuevo nombre: ")
self.contactos[i]['nom']=nom
elif opcion == 2:
tel=int(input("ingrese el nuevo número: "))
self.contactos[i][tel]=tel
elif opcion == 3:
email=input("ingrese nuevo mail: ")
self.contactos[i][email]=mail
elif opcion == 4:
exit()
finalizar=True
print(self.contactos)
agenda=Agenda()
agenda.menu()
agenda.añadir()
agenda.lista()
agenda.busqueda()
agenda.editar()
#6. En un banco tienen clientes que pueden hacer depósitos y extracciones de dinero.
# El banco requiere también al final del día calcular la cantidad de dinero que se ha depositado. deberán crear dos clases,
#la clase cliente y la clase banco. La clase cliente tendrá los atributos nombre y cantidad y los métodos __init__, depositar, extraer, mostrar_total.
#La clase banco tendrá como atributos 3 objetos de la clase cliente y los métodos __init__, operar y deposito_total.
class cliente():
def __init__(self,nom):
self.nom=nom
self.cant=0
def depositar(self,cant):
self.cant=self.cant + cant
def extraer(self,cant):
self.cant=self.cant - cant
def mostrar_total(self):
return self.cant
def imprimir(self):
print(" ")
print ("nombre del cliente: ",self.nom, " total de la cuenta: ",self.cant)
class banco():
def __init__(self):
self.depositos=0
self.extracciones=0
def operar(self,depositos,extracciones):
self.depositos = self.depositos + depositos
self.extracciones=self.extracciones + extracciones
def deposito_total(self):
total=0
total=self.depositos + total
print(" ")
print("el total de dinero depositado es: ", total)
cliente1=cliente("Marcos")
cliente1.depositar(322)
cliente1.extraer(22)
cliente1.mostrar_total()
cliente1.imprimir()
banco=banco()
banco.operar(300,22)
banco.deposito_total()
#7. Desarrollar un programa que conste de una clase padre Cuenta y dos subclases PlazoFijo y CajaAhorro.
#Definir los atributos titular y cantidad y un método para imprimir los datos en la clase Cuenta.
#La clase CajaAhorro tendrá un método para heredar los datos y uno para mostrar la información.
#La clase PlazoFijo tendrá dos atributos propios, plazo e interés.
#Tendrá un método para obtener el importe del interés (cantidad*interés/100) y otro método para mostrar la información,
#datos del titular plazo, interés y total de interés.
#Crear al menos un objeto de cada subclase.
class cuenta():
def __init__(self,nom,cant):
self.nom=nom
self.cant=cant
def imprimir(self):
print(" ")
print("nombre: ",self.nom)
print("cuenta en pesos: ",self.cant)
class cajaAhorro(cuenta):
def __init__(self,nom,cant):
super().__init__(nom,cant)
def mostrar(self):
print(" ")
print("nombre: ",self.nom)
print ("cantidad en su cuenta Caja de Ahorro: ",self.cant)
class PlazoFijo(cuenta):
def __init__(self,nom,cant,plazo,interes):
super().__init__(nom,cant)
self.plazo=plazo
self.interes=interes
def importe_interes(self):
self.total=self.cant*self.interes/100
def mostrar(self):
print(" ")
print("titular: ", self.nom)
print("porcentaje de interés: ", self.interes,)
print(" ")
print("el interes total en los plazos fijos es de: ", self.total)
cuenta=cuenta("Maria",3200)
cuenta.imprimir()
caja_de_ahorro= cajaAhorro("Juan",4000)
caja_de_ahorro.mostrar()
PlazoFijo=PlazoFijo("Maria",3200,30,10)
PlazoFijo.importe_interes()
PlazoFijo.mostrar()
|
71a0ae58b46c26804fc5b973720df51ff6769597 | Pato38/EDI | /ejercicios python-1/cerveceria.py | 1,270 | 3.9375 | 4 | #carga cerveza por tipo
def leer_barril():
barril={
'producto':input("ingrese producto: "),
'litros':int(input("ingrese los litros por barril: ")),
'proveedor':input("ingrese proveedor: "),
'porc_amarg':int(input("ingrese porcentaje de amargura: ")),
'porc_alcohol':int(input("ingrese porcentaje de alcohol: ")),
'precio':int(input("ingrese precio: ")),
'porc_lleno':int(input("ingrese porcentaje de cerveza en el barril: "))}
return barril
barril=leer_barril()
#carga los tipos de cerveza en una lista
def cargar_barril():
seguir='s'
productos=[]
i=0
while seguir!='n':
barril=leer_barril()
productos.append(barril)
seguir=input("desea cargar otra variedad: s/n ")
i=i+1
return productos
productos=cargar_barril()
print(productos)
def vendidas(litros_consumidos):
litro=int(input("Ingrese litros iniciales del barril "))
return litro - litros_consumidos
litros_consumidos=int(input("ingrese los litros consumidos "))
litro_final=ventas(litros_consumidos)
print (litro_final)
def ganancia(precio_vta):
precio=int(input("ingrese precio de compra de la cerveza: "))
return precio - precio_vta
precio_vta=int(input("ingrese el precio de la venta: "))
gan_final=ganancia(precio_vta)
print(gan_final)
|
53242aece8a7e2d465b0731d0beae34d5c24f718 | Pato38/EDI | /ejercicios python-1/jyfjhgjhjh.py | 272 | 3.828125 | 4 |
m_2=[[1,2],
[4,5]]
m_1=[[1,2],
[3,4]]
#busqueda secuencial del numero mayor en una matriz
objetivo=0
maximo=4
i=0
def busqueda_secuencial(m_1,diml,i):
while maximo!=objetivo and i<diml:
i=i+1
return maximo
maximo=busqueda_secuencial(m_1,2,i)
print(maximo)
|
43bdb82fb66a7b7a3ed86286fdf47ae5f2d04e2c | Pato38/EDI | /ejercicios python-1/suma recursiva.py | 509 | 3.609375 | 4 | #suma
n=10
def suma(n):
if n ==0:
return 0
else:
return n+suma(n-1)
suma(10)
print(suma(10))
#maximo recursivo
diml=4
max=0
i=0
arreglo=[]
def encontrar_maximo_recursivo(arreglo,i,diml,max):
if i == (diml):
return max
else:
if arreglo[i]> max:
return encontrar_maximo_recursivo(arreglo,i+1,diml,arreglo[i])
else:
return encontrar_maximo_recursivo(arreglo,i+1,diml,max)
arreglo=[1,2,8,3]
encontrar_maximo_recursivo(arreglo,i,4,max)
print(encontrar_maximo_recursivo(arreglo,i,4,max)) |
fd277e3d0bf4085ab27e8904ac2ca689f2220d00 | Pato38/EDI | /ejercicios python/gestor-tp4.py | 2,076 | 3.6875 | 4 | from io import open
import pickle
#inicializamos la clase personajes con sus atributos
class Personaje:
def __init__(self, nombre={},vida=0, ataque=0, defensa=0, alcance=0):
self.nombre = nombre
self.vida = vida
self.ataque = ataque
self.defensa= defensa
self.alcance = alcance
#esta función imprime
def __str__(self):
return "{} -> {} vida, {} ataque, {} defensa, {} alcance".format(
self.nombre, self.vida, self.ataque, self.defensa, self.alcance)
#inicializamos clase gestor
class Gestor:
personajes = []
def __init__(self):
self.cargar()
#el bucle for recorre los personajes temporales dentro de la clase personajes y si coincide con el nombre del personaje lo agrega y guarda
def agregar(self,p):
for pTemp in self.personajes:
if pTemp.nombre == p.nombre:
return
self.personajes.append(p)
self.guardar()
#el bucle for recorre nuevamente los personajes y si el personaje temporal es igual a nombre lo remueve y guarda los cambios
def borrar(self, nombre):
for pTemp in self.personajes:
if pTemp.nombre == nombre:
self.personajes.remove(pTemp)
self.guardar()
print("\nPersonaje {} borrado".format(nombre))
return
#muestra los personajes
def mostrar(self):
if len(self.personajes)==0:
print("El gestor esta vacio")
return
for p in self.personajes:
print(p)
#pckl almacena cualq objeto en un archivo o cadena
def cargar(self):
fichero= open("personajes.pckl", "ab+") #abrimos el fichero en serie (pickl)
fichero.seek(0)#inicializa en 0
try:
self.personajes = pickle.load(fichero) #lo carga
except:
print("El fichero está vacío")
pass
finally:
fichero.close()
print ("Se han cargado {} personajes".format(
len(self.personajes)))
def guardar(self):
fichero = open("personajes.pckl","wb")
pickle.dump(self.personajes,fichero) #con dump muestra lo q pedimos
fichero.close
G=Gestor()
G.agregar(Personaje("Caballero",4,2,4,2))
G.agregar(Personaje("Guerrero",2,4,2,4))
G.agregar(Personaje("Arquero",2,4,1,8))
G.mostrar()
G.borrar("Arquero")
G.mostrar() |
c29dcf41ae48e6ae08f641eb2ebaaa7c15d63027 | e459621485/leetcode | /generateParenthesis.py | 1,020 | 4 | 4 | '''
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
有效括号组合需满足:左括号必须以正确的顺序闭合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
n = 3
import copy
def generateParenthesis(n):
res = []
if n == 0:
return res
if n == 1:
res.append("()")
return res
for i in generateParenthesis(n - 1):
for j in range(len(i) + 1):
# temp = copy.deepcopy(i)
temp = list(i)
temp.insert(j, "()")
temp = "".join(temp)
if temp not in res:
res.append(temp)
return res
print(generateParenthesis(n))
|
7f7fa454c18f1e2f99e7b29f029eeec50efe9613 | payoj21/Leetcode | /flower_bed.py | 795 | 3.8125 | 4 | def canPlaceFlowers(flowerbed,n):
def consecutivethreezeros(arr):
count = 0
i = 3
if len(arr) < i:
if arr[0] == 0:
count += 1
return count
else:
if arr[0] == 0 and arr[1] == 0:
count = count + 1
if arr[len(arr) - 1] == 0 and arr[len(arr) - 2] == 0:
count = count + 1
while (i < len(arr) - 1):
if arr[i] == 0 and arr[i - 1] == 0 and arr[i - 2] == 0:
count = count + 1
i += 2
else:
i += 1
return count
emptyspots = consecutivethreezeros(flowerbed)
if emptyspots >= n:
return True
return False
print(canPlaceFlowers([0,0],1)) |
5043e51dbab062be2061e2ef34dacae01c4da24b | payoj21/Leetcode | /Nested_list_weight_sum.py | 435 | 3.640625 | 4 | def depthSum(nestedList):
tot_sum = 0
sum_list = []
if len(nestedList) == 0:
return 0
for i in nestedList:
sum_list.append((i,1))
while sum_list:
element,depth = sum_list.pop(0)
if element.isInteger():
tot_sum += depth*element.getInteger()
else:
for index in element.getList():
sum_list.append((index,depth+1))
return tot_sum |
88b2810ad085c37bd9d6077957a6beb452c14ff2 | dburtnja/gomoku_python | /pattern_controller.py | 6,689 | 3.828125 | 4 | from abc import abstractmethod
from board import Board, COLUMNS, ROWS, EMPTY_CELL, FIRST_PLAYER, SECOND_PLAYER
FILLED_CELL = 'X'
EMPTY_CELL_CHAR = '-'
CHECK_DIRECTIONS = [
(-1, -1),
(1, -1),
(-1, 1),
(1, 1),
(0, 1),
(0, -1),
(1, 0),
(-1, 0)
]
class Pattern:
"""
Base Pattern class. All patterns should be inherited from this class.
"""
def __init__(self, pattern_description: str, score: int):
self._pattern = self._parse_pattern(pattern_description)
self._score = score
self._size = len(self._pattern)
self._directions = tuple(
tuple([(number * column_mult, number * row_mult) for number in range(self._size)][::-1])
for column_mult, row_mult in CHECK_DIRECTIONS
)
# print(list(self._directions))
@classmethod
@abstractmethod
def can_parse(cls, pattern_string: str):
pass
@staticmethod
def _check_available_chars_in_string(string, available_chars):
for char in string:
if char not in available_chars:
return False
return True
def _board_size_is_suitable(self, column_size, row_size):
if column_size > self._size or row_size > self._size:
return False
return True
@abstractmethod
def _parse_pattern(self, pattern_description: str):
pass
def check_board(self, board: Board, positive_player):
"""
This method count all scores of current pattern on bord.
:param board: Board object
:param positive_player: player on witch score is adding
:return: score sum
"""
if not isinstance(board, Board):
raise AttributeError(f"board parameter should be instance of Board class. Not: '{type(board)}'.")
return self._check_board(board, positive_player)
def __repr__(self):
return f"{self._pattern} = {self._score}"
@abstractmethod
def _check_board(self, board, positive_player):
pass
class SimplePattern(Pattern):
"""
Simple pattern class. Example: -XXX-
"""
def _check_board(self, board, positive_player):
result = 0
column_size, row_size = board.get_visible_board_size()
for column in range(column_size):
for row in range(row_size):
for list_coordinates in self._directions:
temp_result, player = self._check_coordinates(column, row, list_coordinates, board)
if player == positive_player:
result += temp_result
else:
result -= temp_result
return result
def _check_coordinates(self, start_column, start_row, list_coordinates, board: Board):
"""
This method compare coordinates with pattern, and return player and score for that player
:param start_column: start column index
:param start_row: start row index
:param list_coordinates: list of coordinates to check (starts from zero, this method will add start coordinates)
:param board: board object
:return: score, player_number
"""
player = None
for i, (column_index, row_index) in enumerate(list_coordinates):
cell = board.get_cell_by_index_on_visible_board(
column_index + start_column,
row_index + start_row
)
if cell is None or (cell == EMPTY_CELL and cell != self._pattern[i]): # or not self._pattern[i]
return 0, 0
if cell == EMPTY_CELL:
continue
if player is None:
player = cell
if player != cell:
return 0, 0
return self._score, player
@classmethod
def can_parse(cls, pattern_string: str):
return cls._check_available_chars_in_string(pattern_string, (EMPTY_CELL_CHAR, FILLED_CELL))
def _parse_pattern(self, pattern_description):
return tuple([True if char == FILLED_CELL else EMPTY_CELL for char in pattern_description][::-1])
class PatternFactory:
"""
This class create Patterns based on they description.
"""
def __init__(self, *available_patterns: type(Pattern)):
if len(available_patterns) < 1:
raise ValueError("Should be at least one pattern.")
self._patterns = available_patterns
def get_pattern(self, pattern_description):
pattern_string, score = self._read_pattern(pattern_description)
if score.isdigit():
score = int(score)
else:
raise ValueError(f"Score value should be int type, not: '{score}'.")
for pattern in self._patterns:
if pattern.can_parse(pattern_string):
return pattern(pattern_string, score)
raise RuntimeError(f"Can find appropriate pattern class for such pattern: '{pattern_string}'.")
@staticmethod
def _read_pattern(pattern_description:str):
"""
This method split pattern description string and check if it's valid.
:param pattern_description: string: <pattenr>=<pattern_value> example: XXXXX=10000
:return: pattern_string, score
"""
if pattern_description.startswith("#"):
raise ValueError("Most likely this string is a comment or you should remove '#' symbol.")
if pattern_description == "":
raise ValueError("Empty string can't be pattern.")
pattern_list = pattern_description.split("=")
if len(pattern_list) != 2:
raise ValueError(f"Invalid input string: '{pattern_description}'.")
return pattern_list
class PatternController:
def __init__(self, patterns_path):
pattern_factory = PatternFactory(SimplePattern)
self._patterns = []
with open(patterns_path, "r") as pattern_file:
self._patterns = [pattern_factory.get_pattern(pattern_string.strip())
for pattern_string in pattern_file.readlines()
if pattern_string.strip() and not pattern_string.startswith("#")]
def get_board_value(self, board, positive_player):
"""
This method evaluates value on board.
:param board:
:param positive_player:
:param negative_player:
:return:
"""
result = 0
for pattern in self._patterns:
result += pattern.check_board(board, positive_player)
return result
if __name__ == '__main__':
print("TEST PATTERN CONTROLLER")
try:
PatternController("patterns.txt")
except Exception as e:
print(e)
|
684dba9a9265b5867782ca23dd12e646972bf8b8 | lorinatsumi/lista3 | /ex2.py | 496 | 4.1875 | 4 | #1 Escreva um algoritmo que permita a leitura das notas de uma turma de 5 alunos, armazenando os dados numa lista. Depois calcule a média da turma e conte quantos alunos obtiveram nota acima desta média calculada. Escrever a média da turma e o resultado da contagem.
notas = []
for i in range(5):
nota=int(input("Digite sua nota: "))
notas.append(nota)
print (notas)
soma = 0
for nota in notas:
soma = (soma + nota)
media = soma / 5
print ("A média da turma é: " + str(media))
|
d49c33fc7fbda236f79ec73167610557b8d346f1 | gmacario/learning-python | /lpbook/ch3/multiple.sequences.py | 295 | 3.53125 | 4 | # multiple.sequences.py
# Reference: w_pacb43.pdf, page 81
people = ['Jonas', 'Julio', 'Mike', 'Moz']
ages = [25, 30, 31, 39]
print(type(people))
print(enumerate(people))
for position in range(len(people)):
person = people[position]
age = ages[position]
print(person, age)
# EOF
|
063d011f766e37f3aa5c0fefb37317ebf5420117 | radhalvy/random_game | /main.py | 1,908 | 3.859375 | 4 | import random
import math
def get_first_range():
num_range_1 = int(input("\nEnter the first number of the range: "))
return num_range_1
def get_second_range():
num_range_2 = int(input("\nEnter the second number of the range: "))
return num_range_2
def get_user_guess():
user_guess = int(input("\nEnter your guess: "))
return user_guess
def get_math_log(number):
log = math.log(number)
return log
def main():
try:
first_range = get_first_range()
second_range = get_second_range()
except ValueError:
print("\nInvalid range.")
else:
first_range_log = get_math_log(first_range)
second_range_log = get_math_log(second_range)
random_number = random.randrange(first_range, second_range)
num_guesses = 0
# It's gonna take the 2 numbers that the user inputs for the range and it's gonna calculate them to set the limit of guesses
guess_limit = round(second_range_log - first_range_log + 1)
print(f"\nYou have {guess_limit} tries to guess the number!")
user_guess = ""
while user_guess != random_number:
if num_guesses < guess_limit:
try:
user_guess = get_user_guess()
except ValueError:
print("\nInvalid input.")
return
else:
if user_guess == random_number:
print("\nYou win!")
return
else:
if user_guess < random_number:
print("\nHigher.")
num_guesses += 1
else:
print("\nLower.")
num_guesses += 1
else:
print("\nYou're out of guesses.")
return
main()
|
475ec010d457d16aa1d1a4f446a1d075d69e6d58 | justhonor/python-script | /closure/Closure.py | 1,528 | 3.640625 | 4 | #!/usr/bin/python
# coding:utf-8
##
# Filename: closure.py
# Author : aiapple
# Date : 2017-07-18
# Describe:
##
#############################################
origin = [0,0] # 坐标系统原点
legal_x = [0,50] # x轴方向的合法坐标
legal_y = [0,50] # y轴方向的合法坐标
def create(pos):
def player(direction,step):
# 这里应该首先判断参数direction,step的合法性,比如direction不能斜着走,step不能为负等
# 然后还要对新生成的x,y坐标的合法性进行判断处理
new_x = pos[0] + direction[0]*step
new_y = pos[1] + direction[1]*step
pos[0] = new_x
pos[1] = new_y
# 使用下面语句会报错,因为上面pos[0],已经使用列LEGB中E,默认pos是外部变量
# 此时再想定义内部pos,会报错 UnboundLocalError: local variable 'pos' referenced before assignment
#pos = [new_x,new_y]
return pos
return player
# 注意create(origin)是不行的,origin会和POS使用同一地址
# origin[:] --> copy.copy(origin)
#player1 = create(origin)
player1 = create(origin[:])
print "向x轴正方向移动10步:",player1([1,0],10)
print "向y轴正方向移动20步:",player1([0,1],20)
print "向x轴负方向移动10步:",player1([-1,0],10)
print "origin:",origin
player2 = create(origin[:])
print "向y轴正方向移动10步:",player2([0,1],10)
print "向x轴正方向移动20步:",player2([1,0],20)
print "向x轴负方向移动10步:",player2([-1,0],10)
|
89f11f0c9f388301a43935c2aefacd211c67c6ae | yumy-yumy/topic-model | /src/ioFile.py | 2,850 | 3.703125 | 4 | import csv
import pickle
import json
'''
Output
'''
def dataToFile(item, fname):
"""Function which writes each line to the file"""
with open(fname, 'a') as fileWriter:
fileWriter.write(item)
def abstractsToFile(all_abstract, fname):
"""Writes abstract to the txt file"""
with open(fname, 'w') as fileWriter:
for abstract in all_abstract:
fileWriter.write(abstract)
def dataToCSV(item, fname):
"""Write to the csv file"""
with open(fname, 'a') as csvfile:
fileWriter = csv.writer(csvfile, delimiter=',')
fileWriter.writerow(item)
def statsToFile(item, fname):
"""Function which writes each line to the csv file"""
with open(fname, 'w') as csvfile:
fieldnames = ['year', 'num']
fileWriter = csv.writer(csvfile, delimiter=',')
fileWriter.writerow(fieldnames)
for key, value in item.iteritems():
fileWriter.writerow((key, value))
def statSeqToFile(seq, fname):
'''Write a sequnence of numbers of documents'''
with open(fname, 'w') as fileWriter:
fileWriter.write(str(len(seq)) + '\n')
for num in seq:
fileWriter.write(str(num) + '\n')
def termCountToFile(count, fname):
'''Write data with format [M] [term|index]:[count]'''
with open(fname, 'a') as fileWriter:
N = len(count)
fileWriter.write(str(N) + ' ')
for key, value in count.iteritems():
fileWriter.write(str(key) + ':' + str(value) + ' ')
fileWriter.write('\n')
def termToFile(all_term, fname):
'''Write all terms to a file'''
with open(fname, 'w') as fileWriter:
for term in all_term:
fileWriter.write(term + ' ')
'''
Input
'''
def dataFromFile(fname):
'''Read file and generate a iterator'''
file_iter = open(fname, 'rU')
for line in file_iter:
yield line
def statFromFile(fname):
'''Read the number of documents each year'''
with open(fname, 'rU') as csvfile:
fileReader = csv.reader(csvfile, delimiter=',')
for line in fileReader:
yield line
'''
pickle
'''
def save_object(obj, fname):
print "save object to", fname
with open(fname, 'wb') as fileWriter:
pickle.dump(obj, fileWriter, pickle.HIGHEST_PROTOCOL)
def load_object(fname): #EXAMPLE CODE HOW TO LOAD THE FILES (PICKLES)
with open(fname, 'rb') as fileReader:
return pickle.load(fileReader)
'''
json
'''
def save_json(obj, filename):
print "save object to", filename
with open(filename, 'wb') as fileWriter:
json.dump(obj, fileWriter)
def load_json(filename):
print "load object from", filename
with open(filename, 'rb') as fileReader:
return json.load(fileReader) |
bb0b85fbe5e9fe5c3e05dfb28f35feba48e2d0d7 | jarturomora/learningpython | /ex16bis.py | 834 | 4.28125 | 4 | from sys import argv
script, filename = argv
# Opening the file in "read-write" mode.
my_file = open(filename, "rw+")
# We show the current contents of the file passed in filename.
print "This is the current content of the file %r." % filename
print my_file.read()
print "Do you want to create new content for this file?"
raw_input("(hit CTRL-C if you don't or hit RETURN if you do) >")
# In order to truncate the file we move the pointer to the first line.
my_file.seek(0)
my_file.truncate()
print "\nThe file %r was deleted..." % filename
print "\nWrite three lines to store in the file %r" % filename
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_input("Line 3: ")
my_file.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
my_file.close()
print "The new contents for %r has been saved." % filename
|
8e81b8f7d46c6257d8a6dbabfd677297149148be | jarturomora/learningpython | /ex44e.py | 863 | 4.15625 | 4 | class Other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
class Child(object):
def __init__(self):
self.other = Other() # The composition begins here
# where Child has-a other
def implicit(self):
self.other.implicit() # Call to the implicit() method of
# Child's 'other' instance.
def override(self):
print "CHILD override()"
def altered(self):
print "CHILD BEFORE OTHER altered()"
self.other.altered() # Call to the altered() method of 'other' object.
print "CHILD AFTER OTHER altered()"
son = Child()
son.implicit() # Call to the method "composed" from "Other" class.
son.override()
son.altered() |
b265f84cea66095258b6ff524d080d43ef49aa92 | jarturomora/learningpython | /ex43.py | 6,514 | 4 | 4 | from sys import exit # To allow exit the infinite loop
from random import randint # To generate random integer numbers
class Scene(object):
def enter(self):
"""This method describes each scene"""
print """
This scene is not yet described,
implement enter() on the subclass.
"""
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
"""The main method to start the game"""
current_scene = self.scene_map.opening_scene()
# The game will run until the player is death, wins, or CTRL-D is hit.
while True:
print """
----------------------------------
| Gothons from Planet Percal #25 |
----------------------------------
The most awesome text game coded
in python 2.7
"""
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
class Death(Scene):
death_messages = [
"You died, you planet is doomed due to your clumsiness.",
"WTF! you pissed of!... sorry you're dead!",
"You are simply a luser, you're dead.",
"I have a dog that's better than you at this."
]
def enter(self):
print Death.death_messages[randint(0, len(self.death_messages)-1)]
exit(1)
class CentralCorridor(Scene):
def enter(self):
print """
The Gothons of planet Percal #25 have invaded you ship and killed
your entiere crew. You are the last survivor and your last mission
is to get the neutron destruct bomb from the Weapons Armory,
put it on the bridge, and blow the ship after getting into an
escape pod.
You'are running down the central corridor to the Weapons Armory
when a Gothon jumps out, red scaly skin, dark grimy teeth, and
evil t-shirt of Justin Bieber. He's blocking the door to the Armory
and about to pull a weapon to kill you.
What will you do?
"""
action = raw_input("> ")
if action == "shoot!":
print """
You didn't count that the Justin Bieber's t-shirt is a powerful
armor agains every kind of weapon in the universe, so your
lasser shoot just bounced off the Bieber's face and killed you.
"""
return "death"
elif action == "dodge!":
print """
Ha ha ha! you are so weak in contrast with the Gothon,
your punch was like a feader to him, you are doomed.
The Gothon hit you and smash your face!
"""
return "death"
elif action == "tell a joke":
print """
You hit on the nail, the Gothon has a bad sense of humor
that they even laugh from your bad jokes, the Gothon starts
to laugh until he is dead of happiness.
"""
return "laser_weapon_armory"
else:
print "This is not an option... you have to start over again."
return "central_corridor"
class LaserWeaponArmory(Scene):
def enter(self):
print """
You finally are in front of the neutron bomb, but wait!
there is a keypad with a code you have to enter and you don't
remember it, it's a three numbers code, you have three chances
to guess the code or you are lost!
"""
code = "%d%d%d" % (randint(1, 3), randint(1, 3), randint(1, 3))
print "\n Here's a clue: *%c*" % code[1]
guesses = 1
# print "Code: " + code
guess = raw_input("[Enter Code]> ")
while guesses < 3 and guess != code:
print "\aWrong Code, you have %d more attemps." % (3 - guesses)
guesses += 1
guess = raw_input("[Enter Code]> ")
if guess == code:
print """
Yeah! the container is open and now you can take the netron bomb
hurry up to the bridge and save your life and the galaxy from
the Gothons."
"""
return "the_bridge"
else:
print """
You failed to open the container after %d attemps. Sorry, the
Gothons find you and eat you.
""" % guesses
return "death"
class TheBridge(Scene):
def enter(self):
print """
Finally you are at the bridge, the neutron bomb is very delicate,
there are 100 Gothons at the bridge, you only have one change to
save your life an the galaxy.
What will you do?
"""
action = raw_input("> ")
if action == "slowly place the bomb":
print """
With a ninja movement you place the bomb on the floor and
jump to the espace pod, you are almost save and closer to
become the hero of the galaxy.
"""
return "escape_pod"
else:
return "death"
class EspacePod(Scene):
def enter(self):
print """
Finally you are at the escape pod, but only one pod is ready to
launch and save you life, hurry up! you only have 10 seconds to
pick one of the five pods.
"""
good_pod = randint(1,5)
# print "Pod: " + str(good_pod)
guess = raw_input("[Pod Number]> ")
if int(guess) == good_pod:
print """
Wow! the pod %r was the good one, now you are save, the Gothons
are dead and you just save the entire galaxy, you are going to
become a hero... hurray!!!
""" % good_pod
exit (1)
else:
return "death"
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EspacePod(),
'death': Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
# Game play
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play() |
48181fe62978caf5aedd0a912d8b47bebcb3cbb5 | Yadoloveel/Yadoloveel | /Homework1.py | 812 | 4.09375 | 4 | name1 = input('Enter your name: ')
age1 = input('Enter your age: ')
gender1 = input('Enter your gender: ')
alldata1 = 'Hello! My name is ' + name1 + ". I'm " + age1 + " and I'm a " + gender1
print('1', alldata1)
alldata11 = '%s%s%s%s%s%s' % ('Hello! My name is ', name1, ". I'm ", age1, " and I'm a ", gender1)
print('2', alldata11)
alldata12 = "Hello! My name is {}. I'm {} and I'm a {}".format(name1, age1, gender1)
print('3', alldata12)
about_me_fstring = f"Hello! My name is {name1}. I'm {age1} and I'm a {gender1}"
print('4', about_me_fstring)
list_from_str = about_me_fstring.split(' ')
print('5', list_from_str)
print('6', type(list_from_str))
str_from_list = ' '.join(list_from_str)
print('7', str_from_list)
invert_about_me_fstring = about_me_fstring.swapcase()
print('8', invert_about_me_fstring) |
51004d01f1219a936afbf5e1bca330edbae4079e | abigail-hyde/flood-agh54-bjw68 | /floodsystem/flood.py | 1,319 | 3.546875 | 4 | from .station import MonitoringStation
from .utils import sorted_by_key
def stations_level_over_threshold(stations, tol):
# creates an empty list
flood = []
# iterates through the list and adds a stationif its data is consistent and its above the tolerance
for station in stations:
if station in flood:
pass
elif station.typical_range_consistent() == False or station.relative_water_level() == None:
pass
elif station.relative_water_level() > tol:
data = (station, station.relative_water_level())
flood.append(data)
#sorts the list in decending order
flood_sorted = sorted_by_key(flood,1, reverse=True)
return flood_sorted
def stations_highest_rel_level(stations, N):
# creates an empty list
flood = []
# iterates through the list and adds a stationif its data is consistent and its above the tolerance
for station in stations:
if station in flood:
pass
elif station.typical_range_consistent() == False or station.relative_water_level() == None:
pass
else:
data = (station, station.relative_water_level())
flood.append(data)
flood_sorted = sorted_by_key(flood,1, reverse=True)
return flood_sorted[:N]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.