blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
ea57b522f2bd14f19df61477c8141c238401f1b8 | DavidCasa/tallerTkinter | /Ejercicio4.py | 559 | 4.125 | 4 | ############## EJERCICIOS 4 ################
from tkinter import *
root = Tk()
v = IntVar()
#Es un pequeño menú, en el cual se aplica Radiobuttons para hacer la selección de opciones
Label(root,
text="""Choose a programming language:""",
justify = LEFT,
padx = 20).pack()
Radiobutton(root,
text="Python",
padx = 20,
variable=v,
value=1).pack(anchor=W)
Radiobutton(root,
text="Perl",
padx = 20,
variable=v,
value=2).pack(anchor=W)
mainloop() |
a7baf85ed30fdb9113d105341886e7492a4d91e4 | DavidCasa/tallerTkinter | /Ejercicios - Tkinter (Python)/Ejercicio5.py | 509 | 4.0625 | 4 | from tkinter import *
root = Tk()
v = IntVar()
v.set(1) # initializing the choice, i.e. Python
languages = [ ("Python",1), ("Perl",2), ("Java",3), ("C++",4), ("C",5)]
def ShowChoice():
print (v.get())
Label(root,text="""Choose your favourite programming language:""",
justify = LEFT, padx = 20).pack()
for txt, val in languages:
Radiobutton(root,text=txt, padx = 30,
variable=v,command=ShowChoice,
value=val).pack(anchor=W)
print(txt,": ",val)
mainloop()
|
8efdeef0aa4af75fd19c32ed6eb5b9b2ddcd5d56 | midah18/Hangman_Python | /Hangman_Iterations/Hangman_Iteration-3/hangman.py | 4,350 | 4.21875 | 4 | import random
def read_file(file_name):
file = open(file_name,'r')
return file.readlines()
def get_user_input():
return input('Guess the missing letter: ')
def ask_file_name():
file_name = input("Words file? [leave empty to use short_words.txt] : ")
if not file_name:
return 'short_words.txt'
return file_name
def select_random_word(words):
random_index = random.randint(0, len(words)-1)
word = words[random_index].strip()
return word
def random_fill_word(word):
"""
a word is randomly picked out from thw list
it loops the the word appending most of the letters
replacing the appended letters with an underscore
the new letter with the underscore is joined
"""
x = random.randint(0, len(word)- 2)
new_list = []
letter = word[x]
for i in word:
if i == letter:
new_list.append(i)
else:
new_list.append('_')
j = ''.join(new_list)
return(j)
def is_missing_char(original_word, answer_word, char):
if char in original_word and char not in answer_word:
return True
else:
return False
def fill_in_char(original_word, answer_word, char):
"""
letter inputed by user is compared to the individual letters of the answer word
to check if the letter is present
"""
list_orignal = list(original_word)
list_ans = list(answer_word)
count = 0
for x in list_orignal:
if x == char:
list_ans[count] = x
count += 1
return ''.join(list_ans)
def do_correct_answer(original_word, answer, guess):
"""
function name is equated to a variable named answer
"""
answer = fill_in_char(original_word, answer, guess)
return answer
def do_wrong_answer(answer, number_guesses):
"""
if wrong letter is inputed:
> message is printed
> number of guesses is also printed
> stickman is printed out in stages
"""
print('Wrong! Number of guesses left: '+str(number_guesses))
draw_figure(number_guesses)
def draw_figure(number_guesses):
if number_guesses == 4:
print("/"+"-"*4)
print("|\n"*3+"|")
print("_"*7)
elif number_guesses == 3:
print("/"+"-"*4)
print("|"+" "*3+"0")
print("|\n"*3)
print("_"*7)
elif number_guesses == 2:
print("/"+"-"*4)
print("|"+" "*3+"0")
print("|"+" "*2+"/"+" "+"\\")
print("|\n"*2)
print("_"*7)
elif number_guesses == 1:
print("/"+"-"*4)
print("|"+" "*3+"0")
print("|"+" "*2+"/|" +"\\")
print("|"+" "*3 +"|")
print("|")
print("_"*7)
elif number_guesses == 0:
print("/"+"-"*4)
print("|"+" "*3+"0")
print("|"+" "*2+"/|"+"\\")
print("|"+" "*3 +"|")
print("|"+" "*2+"/ " +"\\")
print("_"*7)
def run_game_loop(word, answer):
"""
user input is asked for
number of guesses is intialized to 5 and decreases per wrong letter
if the words "quit" or "exit" is in user input, game is exited
"""
print("Guess the word:", ''.join(answer))
number_guesses = 5
list_word = list(word)
while answer != list_word and number_guesses > 0:
if word == answer:
return
char_guess = get_user_input()
if char_guess == "exit" or char_guess == "quit":
print("Bye!")
return
if is_missing_char(word, answer, char_guess):
answer = do_correct_answer(word, answer, char_guess)
print(''.join(answer))
else:
number_guesses = number_guesses - 1
do_wrong_answer(answer, number_guesses)
if number_guesses == 0:
print("Sorry, you are out of guesses. The word was: " + word)
else:
print("Winner!!!")
return
print("Guess the word: "+str(answer))
guess = get_user_input()
if is_missing_char(word, answer, guess) is True:
answer = do_correct_answer(word, answer, guess)
else:
do_wrong_answer(answer, 0)
if __name__ == "__main__":
words_file = ask_file_name()
words = read_file(words_file)
selected_word = select_random_word(words)
current_answer = random_fill_word(selected_word)
run_game_loop(selected_word, current_answer)
|
3d999f7baa9c6610b5b93ecf59506fefd421ff86 | Minglaba/Coursera | /Conditions.py | 1,015 | 4.53125 | 5 | # equal: ==
# not equal: !=
# greater than: >
# less than: <
# greater than or equal to: >=
# less than or equal to: <=
# Inequality Sign
i = 2
i != 6
# this will print true
# Use Inequality sign to compare the strings
"ACDC" != "Michael Jackson"
# Compare characters
'B' > 'A'
# If statement example
age = 19
#age = 18
#expression that can be true or false
if age > 18:
#within an indent, we have the expression that is run if the condition is true
print("you can enter" )
#The statements after the if statement will run regardless if the condition is true or false
print("move on")
# Condition statement example
album_year = 1990
if(album_year < 1980) or (album_year > 1989):
print ("Album was not made in the 1980's")
else:
print("The Album was made in the 1980's ")
# Write your code below and press Shift+Enter to execute
album_year = 1991
if album_year < 1980 or album_year == 1991 or album_year == 1993:
print(album_year)
else:
print("no data")
|
a6bf335219d08bfeb6471b9135b530baee1245e2 | tatiana-kim/contest-algorithms | /contest4/C_most_frequent_word.py | 494 | 3.578125 | 4 | # C_most_frequent_word.py
f = open("C/input.txt", "r")
words = f.read().strip().split()
f.close()
count = {}
maxval = -1
tmp = ""
for i in words:
if i not in count:
count[i] = 0
count[i] += 1
if count[i] > maxval:
maxval = count[i]
tmp = i # intermediate result = one of most frequent word
most_frequent_words = []
for i, j in count.items():
if j == maxval:
most_frequent_words.append(i)
if i < tmp:
tmp = i
print(tmp)
|
e013b04bd6afd5dedd83a740a33b0a42115c2baf | tatiana-kim/contest-algorithms | /contest6/H_wires.py | 946 | 3.8125 | 4 | def right_bin_search(left, right, check, checkparams):
while left < right:
middle = (left + right + 1) // 2
if check(middle, checkparams):
left = middle
else:
right = middle - 1
return left
# how many wires with given length from 1 to 10**7 cm
def checklength(x, params):
arr, k = params
summ = 0
for wire in arr:
summ += wire // x
return summ >= k
def main():
n, k = map(int, input().split())
arr = [int(input()) for i in range(n)]
l = 0
r = 10 ** 7 # (макс допустимое значение длины провода)
print(right_bin_search(l, r, checklength, (arr, k)))
def test(algo):
n, k = 4, 11
arr = [802, 743, 457, 539]
l = 0
r = 10 ** 7
assert algo(l, r, checklength, (arr, k)) == 200, "WA :("
print("Test 1: Ok")
if __name__ == "__main__":
main()
# to launch test replace main() call by test(right_bin_search)
|
1ca5aa1330f5d93f60bb335c9e9b097bd30acc0c | tatiana-kim/contest-algorithms | /contest6/B_binary_approximative.py | 3,729 | 3.625 | 4 | """
Приближенный двоичный поиск
Для каждого из чисел второй последовательности найдите ближайшее к нему в первой.
Формат ввода
В первой строке входных данных содержатся числа N и K ().
Во второй строке задаются N чисел первого массива, отсортированного по неубыванию,
а в третьей строке – K чисел второго массива.
Каждое число в обоих массивах по модулю не превосходит 2⋅109.
Формат вывода
Для каждого из K чисел выведите в отдельную строку число из первого массива,
наиболее близкое к данному. Если таких несколько, выведите меньшее из них.
"""
# O(logN)
def find_left_bound(arr, key):
left = 0
right = len(arr)
while right - left > 1:
middle = (left + right) // 2
if arr[middle] <= key:
left = middle
else:
right = middle
return arr[left]
# O(logN)
def find_right_bound(arr, key):
left = -1
right = len(arr) - 1
while right - left > 1:
middle = (left + right) // 2
if arr[middle] >= key:
right = middle
else:
left = middle
return arr[right]
def main():
n, k = list(map(int, input().split()))
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
for i in arr2:
left_bound = find_left_bound(arr1, i)
right_bound = find_right_bound(arr1, i)
distance_from_left_bound = i - left_bound
distance_from_right_bound = right_bound - i
print(left_bound if distance_from_left_bound <= distance_from_right_bound else right_bound)
def test(algoleft, algoright):
arr1 = [1, 3, 5, 7, 9]
arr2 = [2, 4, 8, 1, 6]
answer = []
for i in arr2:
left_bound = find_left_bound(arr1, i)
right_bound = find_right_bound(arr1, i)
distance_from_left_bound = i - left_bound
distance_from_right_bound = right_bound - i
a = left_bound if distance_from_left_bound <= distance_from_right_bound else right_bound
answer.append(a)
assert answer == [1, 3, 7, 1, 5], "Test1: Wrooong :("
print("Test1 : Ok")
arr1 = [1, 1, 4, 4, 8, 120]
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 63, 64, 65]
answer = []
for i in arr2:
left_bound = find_left_bound(arr1, i)
right_bound = find_right_bound(arr1, i)
distance_from_left_bound = i - left_bound
distance_from_right_bound = right_bound - i
a = left_bound if distance_from_left_bound <= distance_from_right_bound else right_bound
answer.append(a)
assert answer == [1, 1, 4, 4, 4, 4, 8, 8, 8, 8, 120], "Test2: Wrooong :("
print("Test2 : Ok")
arr1 = [-5, 1, 1, 3, 5, 5, 8, 12, 13, 16]
arr2 = [0, 3, 7, -17, 23, 11, 0, 11, 15, 7]
answer = []
for i in arr2:
left_bound = find_left_bound(arr1, i)
right_bound = find_right_bound(arr1, i)
distance_from_left_bound = i - left_bound
distance_from_right_bound = right_bound - i
a = left_bound if distance_from_left_bound <= distance_from_right_bound else right_bound
answer.append(a)
assert answer == [1, 3, 8, -5, 16, 12, 1, 12, 16, 8], "Test3: Wrooong :("
print("Test3 : Ok")
if __name__ == "__main__":
main()
# in the last line, replace main() by test(find_left_bound, find_right_bound) in order to start tests
|
fd9803e3c521082db6d967c75dbc21d6b0a56073 | archithyd/some-array-questions | /Arrays/Triplet Sum in Array.py | 833 | 3.515625 | 4 | def binary(arr, val) :
if len (arr) >= 1 :
mid = len (arr) // 2
if arr[mid] == val :
return True
elif val > arr[mid] :
return binary (arr[mid + 1 :len (arr)], val)
else :
return binary (arr[0 :mid], val)
else :
return False
def finder(lis1, k1) :
for i in range (len (lis1)) :
for j in range (1, len (lis1)) :
if binary (lis1, (k1 - lis1[i] - lis1[j])) is True and k1-lis1[i]-lis1[j] != lis1[i] and k1-lis1[i]-lis1[j] != lis1[j] and lis1[i]!=lis[j]:
return 1
return 0
if __name__ == "__main__" :
for _ in range (int (input ( ))) :
n, k = map (int, input ( ).split ( ))
lis = sorted(list (map (int, input ( ).split ( ))))
print (finder (lis, k))
|
ed320d2a8c01915a40b818fe6b030ee8c1e78c7e | pedjasladek/PAZ2-1 | /testmodule.py | 1,124 | 3.921875 | 4 | """Book examples for basic testing"""
from implementmodule import Vertex, breadth_first_search, depth_first_search, print_path
VERTEXR = Vertex('R')
VERTEXV = Vertex('V')
VERTEXS = Vertex('S')
VERTEXW = Vertex('W')
VERTEXT = Vertex('T')
VERTEXU = Vertex('U')
VERTEXY = Vertex('Y')
VERTEXX = Vertex('X')
VERTEXZ = Vertex('Z')
#BFS graph (book)
BFSG = {
VERTEXS: [VERTEXR, VERTEXW],
VERTEXR: [VERTEXS, VERTEXV],
VERTEXV: [VERTEXR],
VERTEXW: [VERTEXS, VERTEXT, VERTEXX],
VERTEXT: [VERTEXW, VERTEXX, VERTEXU],
VERTEXX: [VERTEXT, VERTEXW, VERTEXY],
VERTEXU: [VERTEXT, VERTEXX, VERTEXY],
VERTEXY: [VERTEXT, VERTEXX, VERTEXU]
}
breadth_first_search(BFSG, VERTEXT)
# This calls BFD on BFSG graph
print_path(BFSG, VERTEXS, VERTEXW)
#KDFS graph (book)
DFSG = {
VERTEXU: [VERTEXX, VERTEXV],
VERTEXX: [VERTEXV],
VERTEXV: [VERTEXY],
VERTEXY: [VERTEXX],
VERTEXW: [VERTEXY, VERTEXS],
VERTEXS: [VERTEXS]
}
# This calls DFS on DFSG graph
print_path(DFSG, VERTEXU, VERTEXY, True)
# This calls BFS on DFSG graph
print_path(DFSG, VERTEXU, VERTEXY)
depth_first_search(DFSG, VERTEXU)
|
6d0e36daf1c926b7ee1bf20e4d85359411bccfff | tianti1/covid-seating-optimization | /simulated_annealing.py | 3,830 | 3.53125 | 4 | import math
from copy import deepcopy
import random
import numpy as np
class State:
def __init__(self):
raise NotImplementedError
def mutate(self):
raise NotImplementedError
class MyState(State):
def __init__(self, placing_order):
self.placing_order = placing_order
@staticmethod
def _swap_two(list_, max_attempts=15):
a = random.randint(0, len(list_) - 1)
b = random.randint(0, len(list_) - 1)
# attempts = 0
while b == a or list_[a]["count"] == list_[b]["count"]: # and attempts < max_attempts: # or list_[b]["count"] == list_[a]["count"]
# attempts += 1
b = random.randint(0, len(list_) - 1)
temp_a = list_[a]
list_[a] = list_[b]
list_[b] = temp_a
def _mutate_recursive(self, placing_order, mutations=0, max_mutations=1):
new_placing_order = deepcopy(placing_order)
self._swap_two(new_placing_order)
mutations += 1
if mutations >= max_mutations:
return MyState(new_placing_order)
else:
return self._mutate_recursive(new_placing_order, mutations, max_mutations)
def mutate(self, max_mutations=1):
return self._mutate_recursive(self.placing_order, max_mutations=max_mutations)
class SimulatedAnnealing:
def __init__(self, max_iterations, initial_state, cost_function, *args, p=None, **kwargs):
self._max_iterations = max_iterations # time budget
self._current_iteration = self._max_iterations
self._cost_function = cost_function
self._p = p if p else self._default_p
self._args = args
self._kwargs = kwargs
# initial guess
self._solution_state = initial_state
self._solution_cost = self._cost_function(self._solution_state, *self._args, **self._kwargs)
def _current_temperature(self):
return (self._current_iteration + 1) / self._max_iterations # time budget fraction
@staticmethod
def _default_p(solution_cost, neighbour_cost, current_temperature, maxk, k, *args, **kwargs):
if neighbour_cost < solution_cost:
return 1
return np.exp(-(neighbour_cost - solution_cost) / current_temperature)
def iteration(self):
# select a random neighbour performing a small random mutation to the current state
neighbour_state = self._solution_state.mutate(1)
neighbour_cost = self._cost_function(neighbour_state, *self._args, **self._kwargs)
# accept the mutation according to the p function
if random.uniform(0, 1) <= self._p(self._solution_cost, neighbour_cost, self._current_temperature(), self._max_iterations, self._current_iteration,
*self._args, **self._kwargs):
self._solution_state, self._solution_cost = neighbour_state, neighbour_cost
def run_simulation(self, return_cost_trace=False, return_state_trace=False):
if return_cost_trace:
cost_trace = [self._solution_cost]
if return_cost_trace:
state_trace = [str(self._solution_state)]
while self._current_iteration > 1:
self.iteration()
self._current_iteration -= 1
if return_cost_trace:
cost_trace.append(self._solution_cost)
if return_cost_trace:
state_trace.append(str(self._solution_state))
if return_cost_trace and return_state_trace:
return self._solution_state, self._solution_cost, cost_trace, state_trace
if return_cost_trace:
return self._solution_state, self._solution_cost, cost_trace
if return_state_trace:
return self._solution_state, self._solution_cost, state_trace
return self._solution_state, self._solution_cost
|
eb43ff67cffd4b87e4a59f2f85385abae737ce58 | prashantgupta23/Sort-Employee-by-DOB | /SortEmpbyDOB-Quarter.py | 920 | 3.734375 | 4 | import pandas as pd
# load excel file using pandas and parse date columns
tmpdf = pd.read_excel('employee__1_.xls', parse_dates=['Date of Birth', 'Date of Joining'])
#print(tmpdf)
# sort rows by column 'Date of Birth'
new_tmpdf = tmpdf.sort_values(by='Date of Birth')
# converting pandas dataframe to dictionary format for iteration
tmpdf_records = new_tmpdf.to_dict(orient='records')
# define dict for final required format
tmpoutput = {
'Q1':[],
'Q2':[],
'Q3':[],
'Q4':[]
}
# iterate and parse employee name and add to output dictionary as per respective quarter
for i in range(len(tmpdf_records)):
emp_name = tmpdf_records[i]['First Name'] + ' ' + tmpdf_records[i]['Last Name']
print tmpdf_records[i]['Quarter of Joining'], tmpdf_records[i]['Date of Birth'], emp_name
tmpoutput[ tmpdf_records[i]['Quarter of Joining'] ].append(emp_name)
print("Final Output:")
print(tmpoutput) |
f8964398d3d0772156029cc5179dd80cdf3edd17 | mathman93/SPRI2021_Roomba | /Pastry_Code/Desynch.py | 4,861 | 3.609375 | 4 | ''' RPi_Testing.py
Purpose: Basic code for running Xbee, and illustrating code behavior.
Sets up Xbee;
IMPORTANT: Must be run using Python 3 (python3)
Last Modified: 6/30/2021
By: Jamez White
'''
## Import libraries ##
import serial # For serial port functions (e.g., USB)
import time # For accessing system time
import RPi.GPIO as GPIO # For IO pin access on Raspberry Pi
import math
## Variables and Constants ##
global Xbee # Specifies connection to Xbee
Xbee = serial.Serial('/dev/ttyUSB0', 115200) # Baud rate should be 115200
## Functions and Definitions ##
''' Displays current date and time to the screen
'''
def DisplayDateTime():
# Month day, Year, Hour:Minute:Seconds
date_time = time.strftime("%B %d, %Y, %H:%M:%S", time.gmtime())
print("Program run: ", date_time)
## -- Code Starts Here -- ##
# Setup Code #
GPIO.setmode(GPIO.BCM) # Use BCM pin numbering for GPIO
DisplayDateTime() # Display current date and time
while True:
try:
initial_phase = float(input("Initial oscillator phase? ")) # What are the units of 'phase'?
print("Initial phase value: {0} degrees".format(initial_phase))
coupling_strength = float(input("Enter coupling strength ")) # What percentage of
print("Coupling_strength: {0} %".format(coupling_strength))
break
except ValueError:
print("Not a number. Try again.")
continue
# End while
# Clear out Xbee message buffer.
if Xbee.inWaiting() > 0: # If anything is in the Xbee receive buffer
x = Xbee.read(Xbee.inWaiting()).decode() # Clear out Xbee input buffer
#print(x) # Include for debugging
# End if
N = 3
time_to_take = 2.0 # Length of cycle in seconds
# frequency = 180 # degrees per second
threshold = 360 # "degrees" (could be radians)
frequency = threshold / time_to_take # degrees per second
# time_to_take = threshold/frequency
# frequency * time_to_take = threshold
phase_time = time.time() - (initial_phase/frequency) # Time offset for the oscillator
# (time.time() - phase_time) = phase
# time.time() = phase_time + phase
# time.time() - phase = phase_time
pulse = 'z' # Oscillator pulse character
coupling_strengthP = coupling_strength/100 # this conversts the coupling strength in a percent so we can use it later.
data_time = time.time()
data_step = .1 # seconds
just_fired = False
# Main Code #
while True:
try:
#1. Get current phase value
# How fast is oscillator "spinning"?
# #time_phase = time.time() - phase_time
current_phase = (time.time() - phase_time)*frequency # The current phase of the oscillator (in degrees)
#2. Fire a pulse when phase reaches threshold
# 2a. reset phase value to zero.
if current_phase >= threshold:
print("Phase Reset.")
#phase_time = time.time() # This works, but is slightly variable
phase_time += time_to_take # This is more consistent.
current_phase -= threshold # Technically unnecessary
#current_phase -= (time_to_take*frequency)
# 2b. send pulse to other oscillators (Xbee)
Xbee.write(pulse.encode()) # Send the number over the Xbee
print("You sent stuff.")
just_fired = True
# End if
#3. Check for any received pulses from other oscillators
if Xbee.inWaiting() > 0: # If there is something in the receive buffer
received_pulse = Xbee.read(Xbee.inWaiting()).decode() # Read all data in
# received_pulse = "z" (pulse)
print(received_pulse) # To see what the message is
# Update phase value based on (de)sync algorithm.
# Inverse-MS algorithm - always move backwards
phase_change = -(coupling_strengthP)*current_phase
# alpha is pretty small, probably less than 0.1
current_phase += phase_change # (also update phase_time)
phase_time -= phase_change/frequency
# PRF Desync - Look up value to change in PRF
if current_phase < threshold * (1/N):
QD = -coupling_strengthP*(current_phase-(threshold/N))
current_phase = current_phase + QD #Calculating how much phase to change\
phase_time -= QD/frequency
# move backwards in phase
elif current_phase > threshold * (N-1)/N:
QA = -coupling_strengthP*(current_phase-(threshold-threshold/N))
current_phase = current_phase + QA #Calculating how much phase to change
phase_time -= QA/frequency
#No further changes, your PRF will be zero
# End if
# End if
if (time.time()-data_time) > data_step:
print("Current phase value: {0} degrees".format(current_phase)) # Display phase data to screen
data_time += data_step # Increment data_time
# End if
except KeyboardInterrupt:
break
# End while
## -- Ending Code Starts Here -- ##
# Make sure this code runs to end the program cleanly
Xbee.close()
GPIO.cleanup() # Reset GPIO pins for next program
|
14d07f71f1bbefd436926933bf8d581f94ead74a | GregorySeth/book_database | /main.py | 5,201 | 3.71875 | 4 | from tkinter import *
from back import Database
from tkinter import messagebox
class MainWindow(object):
def __init__(self, window):
#Window
self.window = window
self.window.title("Book database")
self.window.geometry("500x370")
#Labels
lbl_title = Label(self.window, text="Tytuł: ")
lbl_title.grid(column=0, row=0)
lbl_author = Label(self.window, text="Autor: ")
lbl_author.grid(column=2, row=0)
lbl_year = Label(self.window, text="Rok: ")
lbl_year.grid(column=0, row=1)
lbl_isbn = Label(self.window, text="ISBN: ")
lbl_isbn.grid(column=2, row=1)
lbl_info = Label(self.window, text="ID | Tytuł | Autor | Rok | ISBN")
lbl_info.grid(column=0, columnspan=3, row=2)
#Entries
self.en_title_var = StringVar()
self.en_title = Entry(self.window, textvariable=self.en_title_var)
self.en_title.grid(column=1, row=0)
self.en_author_var = StringVar()
self.en_author = Entry(self.window, textvariable=self.en_author_var)
self.en_author.grid(column=3, row=0)
self.en_year_var = StringVar()
self.en_year = Entry(self.window, textvariable=self.en_year_var)
self.en_year.grid(column=1, row=1)
self.en_isbn_var = StringVar()
self.en_isbn = Entry(self.window, textvariable=self.en_isbn_var)
self.en_isbn.grid(column=3, row=1)
#Listbox
self.lbx1 = Listbox(self.window, height=12, width=50)
self.lbx1.grid(column=0, row=3, columnspan=2, rowspan=4, padx=10)
self.lbx1.bind("<<ListboxSelect>>", self.show_selected)
#Scrollbars
scr1 = Scrollbar(self.window)
scr1.grid(column=2, row=3, rowspan=4, sticky="ns")
scr2 = Scrollbar(self.window, orient="horizontal")
scr2.grid(column=0, row=7, columnspan=2, padx=10, sticky="we")
#Scrollbars commands
self.lbx1.configure(yscrollcommand = scr1.set, xscrollcommand= scr2.set)
scr1.configure(command = self.lbx1.yview)
scr2.configure(command = self.lbx1.xview)
#Buttons
bt1 = Button(self.window, text="Pokaż wszystko", width=15, height=2, command=self.view_option)
bt1.grid(column=3, row=2)
bt2 = Button(self.window, text="Wyszukaj wpis", width=15, height=2, command=self.find_option)
bt2.grid(column=3, row=3)
bt3 = Button(self.window, text="Dodaj wpis", width=15, height=2, command=self.add_option)
bt3.grid(column=3, row=4)
bt4 = Button(self.window, text="Edytuj wpis", width=15, height=2, command=self.edit_option)
bt4.grid(column=3, row=5)
bt5 = Button(self.window, text="Usuń wpis", width=15, height=2, command=self.delete_option)
bt5.grid(column=3, row=6)
bt6 = Button(self.window, text="Zamknij", width=15, height=2, command=window.destroy)
bt6.grid(column=3, row=7)
#Listbox showing data on start
self.view_option()
#Window functions
def show_selected(self, event): #shows details of the selected item in entry fields
try:
global selection
index = self.lbx1.curselection()[0]
self.selection = self.lbx1.get(index)
self.en_title.delete(0,END)
self.en_author.delete(0,END)
self.en_year.delete(0,END)
self.en_isbn.delete(0,END)
self.en_title.insert(END, self.selection[1])
self.en_author.insert(END, self.selection[2])
self.en_year.insert(END, self.selection[3])
self.en_isbn.insert(END, self.selection[4])
except IndexError:
pass
def view_option(self): #show all items rom database
self.lbx1.delete(0,END)
for i in database.view():
self.lbx1.insert(END, i)
def find_option(self): #find item in database
self.lbx1.delete(0,END)
for i in database.find(self.en_title_var.get(), self.en_author_var.get(), self.en_year_var.get(), self.en_isbn_var.get()):
self.lbx1.insert(END, i)
def add_option(self): #add new item to database
database.add(self.en_title_var.get(), self.en_author_var.get(), self.en_year_var.get(), self.en_isbn_var.get())
self.view_option()
messagebox.showinfo("Dodano", "Dodano - Tytuł: %s, Autor: %s, Rok: %s, ISBN: %s" %(self.en_title_var.get(), self.en_author_var.get(), self.en_year_var.get(), self.en_isbn_var.get()))
def delete_option(self): #delete selected item from database
database.delete(self.selection[0])
self.view_option()
messagebox.showinfo("Usunięto", "Usunięto - %s, %s, %s, %s" %(self.selection[1], self.selection[2], self.selection[3], self.selection[4]))
def edit_option(self): #edit selected item by changing its values with the new values from entries
database.edit(self.selection[0], self.en_title_var.get(), self.en_author_var.get(), self.en_year_var.get(), self.en_isbn_var.get())
self.view_option()
messagebox.showinfo("Zrobione", "Gotowe")
database = Database("book_base.db")
window = Tk()
MainWindow(window)
window.mainloop()
|
9a12a3be1583dfa72740742706ae0b2d1b73d21c | zvasdfg/GraphPython | /graph.py | 3,328 | 3.765625 | 4 | #Importamos la funcion deque
from collections import deque
#Definimos la clase Grafo y asignamos valor vacio al diccionario de terminos
class Grafo(object):
def __init__(self):
self.relaciones = {}
def __str__(self):
return str(self.relaciones)
#Definimos la funcion agregar(Recibe un grafo y el elemento a agregar)
def agregar(grafo, elemento):
grafo.relaciones.update({elemento:[]})
#Definimos la funcion relacionar(Recibe un grafo, un origen y un destino)
def relacionar(grafo, origen, destino):
#Relacionamos el origen con el destino
grafo.relaciones[origen].append(destino)
"""
def profundidadPrimero(grafo, elementoInicial, elementoFinal, funcion, elementosRecorridos = []):
if elementoInicial==elementoFinal:
print(elementoFinal)
return
if elementoInicial in elementosRecorridos:
return
funcion(elementoInicial)
elementosRecorridos.append(elementoInicial)
for vecino in grafo.relaciones[elementoInicial]:
profundidadPrimero(grafo, vecino, elementoFinal, funcion, elementosRecorridos)
"""
#Funcion De busqueda por Amplitud:
def anchoPrimero(grafo, elementoInicial, elementoFinal, funcion, cola = deque(), elementosRecorridos = []):
#Recibimos el grafo en el que estamos trabajando, un origen, un destino, la instruccion para imprimir,
#La funcion para hacer deque, Y una lista de elementos recorridos
if elementoInicial==elementoFinal:
print(elementoFinal)
return
#Retornamos El Destino cuando es encontrado.
if not elementoInicial in elementosRecorridos:
funcion(elementoInicial)
#Imprimimos cada elemento
elementosRecorridos.append(elementoInicial)
#Agregamos a la lista de Elementos Recorridos.
if(len(grafo.relaciones[elementoInicial]) > 0):
cola.extend(grafo.relaciones[elementoInicial])
#Si el nodo tiene relaciones, las agregamos como lista, no como diccionario.
if len(cola) != 0 :
anchoPrimero(grafo, cola.popleft(), elementoFinal, funcion, cola, elementosRecorridos)
#Mientras haya elementos en el Arreglo, seguiremos sacando elementos de forma FIFO
####################################
#Funcion De busqueda por Profundidad:
def proPrimero(grafo, elementoInicial, elementoFinal, funcion, cola = deque(), elementosRecorridos = []):
#Recibimos el grafo en el que estamos trabajando, un origen, un destino, la instruccion para imprimir,
#La funcion para hacer deque, Y una lista de elementos recorridos
if elementoInicial==elementoFinal:
print(elementoFinal)
return
#Retornamos El Destino cuando es encontrado.
if not elementoInicial in elementosRecorridos:
funcion(elementoInicial)
#Imprimimos cada elemento
elementosRecorridos.append(elementoInicial)
#Agregamos a la lista de Elementos Recorridos.
if(len(grafo.relaciones[elementoInicial]) > 0):
cola.extend(grafo.relaciones[elementoInicial])
#Si el nodo tiene relaciones, las agregamos como lista, no como diccionario.
if len(cola) != 0 :
proPrimero(grafo, cola.pop(), elementoFinal, funcion, cola, elementosRecorridos)
#Mientras haya elementos en el Arreglo, seguiremos sacando elementos de forma FILO
|
813838aabd9e345dfbef4efe9c80436d6dfa304d | aksiwme/PythonLecture | /python300.py | 3,406 | 3.75 | 4 | # 사용자로부터 값을 입력 받은 후 해당 값에 20을 더한 값을 출력하라.
# 단 사용자가 입력한 값과 20을 더한 값이 255를 초과하는 경우 255를 출력해야 한다.
num = int(input())
if num + 20 > 255:
num = 255
else:
num = num + 20
print(num)
# 사용자로부터 값을 입력 받은 후 해당 값에 20을 뺀 값을 출력하라.
# 단, 출력 값의 범위는 0 ~ 255이다.
# (결과값이 0보다 작을 경우 0, 255 보다 클 경우 255를 출력해야 한다.)
num = int(input())
if num - 20 < 0:
num = 0
elif num - 20 > 255:
num = 255
else:
num = num - 20
print(num)
# 년도를 입력하면 윤년인지 아닌지를 출력하는 프로그램을 작성하라.
year = int(input())
if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0):
print("{0}년은 윤년입니다.".format(year))
else:
print("{0}년은 윤년이 아닙니다.".format(year))
# 리스트에 4개의 정수 [3, -20, -3, 44] 가 저장되어 있다.
# For 문을 사용하여 리스트의 음수만을 출력하는 프로그램을 작성하라.
givenList = [3, -20, -3, 44]
for i in givenList:
if i < 0:
print(i)
# 리스트에 4개의 정수 [3, 100, 23, 44] 가 저장되어 있다.
# For 문을 사용하여 3의 배수만을 출력하는 프로그램을 작성하라.
givenList = [3, 100, 23, 44]
for i in givenList:
if i % 3 == 0:
print(i)
# 다음 리스트 [13, 21, 12, 14, 30, 18]에서
# 20보다 작은 3의 배수를 출력하는 프로그램을 for문을 사용하여 작성하라.
givenList = [13, 21, 12, 14, 30, 18]
for i in givenList:
if (i < 20) and (i % 3 == 0):
print(i)
# while 문을 사용하여 ‘hello world’를 10번 출력하는 프로그램을 작성하라.
# 단, 반복 횟수도 같이 출력되어야 함.
i = 1
while i <= 10:
print("hello world - {0}".format(i))
i = i + 1
# 위 프로그램에서 반복 횟수가 10부터 거꾸로 출력되도록 변경하라
i = 10
while i >= 1:
print("hello world - {0}".format(i))
i = i - 1
# while 문을 사용하여 1 부터 10까지의 숫자 중 홀수만을 출력하는 프로그램을 작성하라
i = 1
while i <= 10:
if i % 2 == 1:
print(i)
i = i+1
# 초항 A1 = 1 이고, 공차 d = 4인 등차수열 An 에 대하여
# 100을 넘지 않는 최대 An의 값과 그 때의 n 을 구하라.
d = 4
n = 1
An = d * n - 3 # A1
while An < 100:
n = n + 1
An = An + d
# 100 이상일 때 루프를 빠져나오기 때문에 이전 항이 정답
n = n - 1
An = An - d
print("100을 넘지않는 최대 An은 {0}항이고, 값은 {1}이다.".format(n, An))
# 커피 자판기
quantity = 10
coffeePrice = 300
while quantity > 0:
# 돈 입력을 기다림
money = int(input("금액을 입력해 주세요: "))
if money >= coffeePrice:
print("커피를 판매 합니다.")
print("거스름 돈은 {0}원 입니다.".format(money - coffeePrice))
quantity = quantity - 1 # 팔았으니까 한 잔 뺌
else:
print("{0}원 이상의 금액을 입력해주세요.".format(coffeePrice))
print("남은 수량은 {0}잔 입니다.".format(quantity))
print("남은 커피가 없습니다. 판매를 종료합니다.")
|
7bbdd543e8340a3c1429e44121de6ef9cb2c5835 | mohammadsh97/Prework_1 | /workers/person.py | 3,198 | 3.59375 | 4 | import abc
import re
class Person:
__id = 0
list_phone = []
address = []
@staticmethod
def generatId(self):
self.__id += 1
@staticmethod
def validEmail(email):
fields = email.split("@")
if len(fields) != 2:
return False
else:
regex = '[a-z0-9]+'
if re.search(regex, fields[0]):
if fields[1].endswith(".hwltd.com"):
return True
return False
def __init__(self, last_name, first_name, year_of_birth, email, phones, address):
# Generating id
self.generatId(self)
# First and last name must not be empty
if len(first_name) != 0 and len(last_name) != 0:
self.__name = first_name
self.__lastName = last_name
else:
print("the first or last name is empty")
exit(1)
self.yearOfBirth = year_of_birth
if self.validEmail(email):
self.__email = email
else:
print("Invalid Email")
return Exception("Invalid Email")
self.list_phone = phones
self.address = address
def removePhone(self, phone_number):
if phone_number in self.list_phone:
self.list_phone.remove(phone_number)
else:
print("Not present")
exit(1)
def addPhone(self, phone_number):
if phone_number in self.list_phone:
print("The number is exists")
exit(1)
else:
self.list_phone.append(phone_number)
def editAddress(self, address):
self.address = address
class Phone:
def __init__(self, phone_number):
# regex = '[+]?[[0-9]+[-]?[0-9]+]*'
if len(phone_number) > 0:
for index in range(len(phone_number)):
if (index != 0 and phone_number[0] == "+") or (
"0" > phone_number[index] > "9"):
print("The phone number is illegal")
break
self.phone_number = phone_number
else:
print("The phone number is illegal")
class Address:
def __init__(self, country, city):
if len(country) != 0 and len(city) != 0:
self._country = country
self._city = city
def getAddress(self):
return "Country: " + self._country + ",City: " + self._city + "."
class StreetAddress(Address):
def __init__(self, country, city, street_name, house_number):
super().__init__(country, city)
self.street_name = street_name
self.house_number = house_number
@abc.abstractmethod
def getAddress(self):
try:
return "Street Number: " + self.street_name + ",Street Number: " + self.house_number + "."
except:
raise NotImplementedError()
class PobAddrees(Address):
def __init__(self, country, city, box_number):
super().__init__(country, city)
self.box_number = box_number
@abc.abstractmethod
def getAddress(self):
try:
return "Post Office Box Number: " + self.box_number + "."
except:
raise NotImplementedError()
|
8fce380bffd2b7baf5f804bad1fd96ce87dbb4be | bartnic2/Python-Guides | /Games/cave_game.py | 1,060 | 3.84375 | 4 | import shelve
with shelve.open("cave data") as data:
loc = 1
while True:
availableExits = ", ".join(data["locations"][loc]["exits"].keys())
print(data["locations"][loc]["desc"])
if loc == 0:
break
else:
allExits = data["locations"][loc]["exits"].copy()
allExits.update(data["locations"][loc]["namedExits"])
direction = input("Available exits are " + availableExits + ". Where do you wish to go? ").upper()
print()
# Parse the user input, using our vocabulary dictionary if necessary
if len(direction) > 1: # more than 1 letter, so check vocab
words = direction.split()
for word in words:
if word in data["vocabulary"]: # does it contain a word we know?
direction = data["vocabulary"][word]
break
if direction in allExits:
loc = allExits[direction]
else:
print("You cannot go in that direction") |
bcd4278ea6f15697b4baa017521468f8c5d69c9a | artemiocabelin/pythonfundamentals | /draw_stars.py | 396 | 3.828125 | 4 | def draw_stars(numList):
for num in numList:
if isinstance(num,int):
star = ""
for i in range(num):
star += "*"
print star
elif isinstance(num,str):
word = ""
for letter in num:
word += num[0]
print word.lower()
x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
draw_stars(x)
|
90a03657ec4eee4a278237e2358c8fa094df5a0b | artemiocabelin/pythonfundamentals | /making_dictionaries.py | 1,159 | 3.796875 | 4 | name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar","papoy"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
def make_dict(arr1,arr2):
new_dict ={}
for item1, item2 in zip(arr1,arr2):
new_dict[item1] = item2
print new_dict
# Hacker challenge
def make_dict_hack(arr1,arr2):
new_dict ={}
if len(arr1) != len(arr2):
if len(arr1) > len(arr2):
i = 0
while i < len(arr1):
new_dict[arr1[i]] = ''
i+=1
j=0
while j < len(arr2):
new_dict[arr1[j]] = arr2[j]
j+=1
print new_dict
elif len(arr1) < len(arr2):
i = 0
while i < len(arr2):
new_dict[arr2[i]] = ''
i+=1
j=0
while j < len(arr1):
new_dict[arr2[j]] = arr1[j]
j+=1
print new_dict
else:
for item1, item2 in zip(arr1,arr2):
new_dict[item1] = item2
print new_dict
# make_dict(name,favorite_animal)
make_dict_hack(name,favorite_animal)
|
36c764b200f9d956fa1552fb970a5a8a76fd073d | cindylebron/leetcode | /20200611/101symmetricTree.py | 559 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# O(n)
def isSymmetric(self, root) -> bool:
if not root:
return True
return self.isMirror(root.left, root.right)
def isMirror(self, t1, t2) -> bool:
if t1 and t2:
return t1.val == t2.val and self.isMirror(t1.right, t2.left) and self.isMirror(t1.left, t2.right)
return t1==t2 |
4b9cc18a95ab96ffba85bcdc3e31fd3032464d4a | juliushamilton/match_loc | /fasta.py | 2,215 | 3.75 | 4 | def is_fasta(name):
# is_fasta determines whether a filename is fasta or not.
if not isinstance(name, str):
raise TypeError('ERROR: is_fasta requires string inpute.')
elif len(name) <= 10:
return False
elif name[-10:] == '.fasta.txt':
return True
else:
return False
def open_fasta(file_name):
# open_fasta returns a string of the dna sequences
# contained in a fasta file by opening the file, reading the lines, and
# eliminating the first line.
if not isinstance(file_name, str):
raise TypeError('ERROR: filename must be a string.')
elif not is_fasta(file_name):
raise ValueError('ERROR: open_fasta requires a fasta file.')
else:
f = open(file_name)
lines = f.readlines()
f.close()
lines = lines[1:]
for index, line in enumerate(lines):
lines[index] = line.rstrip()
text = "".join(lines)
return text
def make_sample_fasta(file_name, text):
# make_sample_fasta make a model fasta file for texting,
# saved under the name file_name, containing text as the body
if not isinstance(file_name, str):
raise TypeError('ERROR: filename must be a string.')
elif not isinstance(text, str):
raise TypeError('ERROR: text must be a string.')
elif not is_fasta(file_name):
raise ValueError('ERROR: filename but be a fasta file.')
else:
f = open(file_name, 'w')
f.write('xxxxxxxxx\n' + text)
f.close()
def convert_to_text(i):
# convert_to_text converts a fasta file into its text,
# or a list of fasta files and strings
# into a list of texts.
if not (isinstance(i, list) or isinstance(i, str)):
raise TypeError('ERROR: convert_to_text requires a list or a string.')
elif isinstance(i, str):
if is_fasta(i):
return open_fasta(i)
else:
return i
elif isinstance(i, list):
for index, item in enumerate(i):
i[index] = convert_to_text(item)
return i
def is_gen(gen):
for sym in gen:
if sym not in ('A', 'C', 'G', 'T'):
return False
else:
return True
|
f490fff601ddab9e47adcb2a8602051a605585f6 | Kjosev/aoc2020 | /09/script.py | 1,748 | 3.734375 | 4 | def read_input():
with open('input.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
return lines
def check_sum(arr, num):
# print(arr)
# print(num)
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] + arr[j] == num:
return True
return False
def find_wrong_num(numbers, preamble_lenght):
current_idx = preamble_lenght
while current_idx < len(numbers):
if not check_sum(numbers[current_idx-preamble_lenght:current_idx], numbers[current_idx]):
print("Wrong number: {} at {}".format(numbers[current_idx], current_idx))
return numbers[current_idx]
current_idx += 1
def find_weakness(numbers, wrong_number):
forward_sum = [0 for n in numbers]
for idx in range(len(numbers)):
previous_sum = forward_sum[idx - 1] if idx > 0 else 0
forward_sum[idx] = numbers[idx] + previous_sum
for i in range(len(numbers)):
for j in range(i + 1, (len(numbers))):
current_sum = forward_sum[j]
previous_sum = forward_sum[i - 1] if i > 0 else 0
# print("{} to {}: {} sum to {}".format(i, j, str(numbers[i:j+1]), current_sum - previous_sum))
if current_sum - previous_sum == wrong_number:
print(numbers[i:j+1])
print("Result {}".format(max(numbers[i:j+1]) + min(numbers[i:j+1])))
break
def main():
lines = read_input()
numbers = [int(x) for x in lines]
preamble_lenght = 25
wrong_number = find_wrong_num(numbers, preamble_lenght)
find_weakness(numbers, wrong_number)
if __name__ == "__main__":
main()
|
2cc886e5bb11a8ed0fa37089601809d5bef77b56 | Kjosev/aoc2020 | /08/script.py | 1,489 | 3.546875 | 4 | def read_input():
with open('input.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
return lines
def run_program(lines, op_to_switch=None):
visited = set()
accumulator = 0
current_idx = 0
finished_normally = False
while current_idx not in visited:
if current_idx >= len(lines):
finished_normally = True
break
(op, num) = lines[current_idx]
num = int(num)
if op_to_switch == current_idx:
op = 'jmp' if op == 'nop' else 'nop'
if op == 'nop':
next_idx = current_idx + 1
elif op == 'acc':
accumulator += num
next_idx = current_idx + 1
elif op == 'jmp':
next_idx = current_idx + num
visited.add(current_idx)
current_idx = next_idx
return {
"result": accumulator,
"finished_normally": finished_normally
}
def find_and_fix_wrong_op(lines):
for idx, (op, num) in enumerate(lines):
if op == 'nop' or op == 'jmp':
output = run_program(lines, op_to_switch=idx)
if output["finished_normally"]:
return output["result"]
def main():
lines = read_input()
parsed_lines = [line.split() for line in lines]
result_1 = run_program(parsed_lines)
print(result_1)
result_2 = find_and_fix_wrong_op(parsed_lines)
print(result_2)
if __name__ == "__main__":
main() |
0e3a78b306e6fa1fa01314feb32dc9210c5d38ea | jjmaturino/LinearRegression_MarkovChains2020 | /Python/ProbabilityCode.py | 3,256 | 3.703125 | 4 | def computeProb(counterWon, counterWS, counterGame):
pb = counterWS / counterGame
paib = counterWon / counterGame
if pb == 0:
pab = 0
else:
pab = paib / pb
return pab
import pandas as pd
df = pd.read_csv("modifiedWinStreaks - good.csv")
streaks = df["Numeric Win Streak"]
# nextOutcome = df['Next game']
# Calculate the maximum (win) and minimum (lose) streaks
maxStreak = 0
minStreak = 0
for i in range(len(streaks)):
if streaks[i] > maxStreak:
maxStreak = streaks[i]
elif streaks[i] < minStreak:
minStreak = streaks[i]
print("The maximum win streak is: %d" % maxStreak)
print("The minimum win streak is %d" % minStreak)
probabilities = pd.Series([])
# This isn't complete, but I started to try to go by win streak instead of team
for i in range(minStreak, maxStreak):
positionCounter = 0
seriesCounter = 0
winCounter = 0
totalGames = 0
if i != 0:
while positionCounter > len(df):
if df[positionCounter] == i:
winCounter += 1
totalGames += 1
else:
totalGames += 1
# This part would use the computeProbability function.
# Later it will add to our probability table
# probabilities[seriesCounter] = computeProb(winCounter, totalGames, )
# This is Maria's code
teamNumberS = pd.Series([])
teamNameS = pd.Series([])
counterWonS = pd.Series([])
counterWSS = pd.Series([])
pabS = pd.Series([])
# no_integer = True
# while no_integer:
# try:
# wsValue = int(input("Enter the # of consecutive wins to be used as minimum Win Streak "))
# no_integer = False
# except:
# print ("Enter an integer value")
# determine who won Game
teamNumber = df["Team Number"]
teamName = df["Team Name"]
winStreak = df["Numeric Win Streak"]
# Initialize counters for next team
team = -1
counterWS = 0
counterWon = 0
counterGame = 0
j = 0
wsValue = minStreak
for i in range(len(df)):
if teamNumber[i] != team:
if team != -1:
print("Checking probability of %d games" % wsValue)
# Calculate probabilities
pab = computeProb(counterWon, counterWS, counterGame)
# Stores figures for this team
teamNumberS[j] = team
teamNameS[j] = teamName[i - 1]
counterWonS[j] = counterWon
counterWSS[j] = counterWS
pabS[j] = pab
j += 1
# Initialize counters for next team
counterWS = 0
counterWon = 0
counterGame = 0
team = teamNumber[i]
if winStreak[i] >= wsValue:
counterWS += 1
if winStreak[i] > wsValue:
counterWon += 1
counterGame += 1
# Stores figures for last team
pab = computeProb(counterWon, counterWS, counterGame)
teamNumberS[j] = team
teamNameS[j] = teamName[i - 1]
counterWonS[j] = counterWon
counterWSS[j] = counterWS
pabS[j] = pab
# Creates the table with statistics per team
dft = pd.DataFrame(
{
"Team Number": teamNumberS,
"Team Name": teamNameS,
"#Wins WS": counterWonS,
"#Win Streak": counterWSS,
"Probability": pabS,
}
)
print(dft)
dft.to_csv("big10Probability.csv")
print("done")
|
f256746a37c0a050e56aafca1315a517686f96c8 | luxorv/statistics | /days_old.py | 1,975 | 4.3125 | 4 | # Define a daysBetweenDates procedure that would produce the
# correct output if there was a correct nextDay procedure.
#
# Note that this will NOT produce correct outputs yet, since
# our nextDay procedure assumes all months have 30 days
# (hence a year is 360 days, instead of 365).
#
def isLeapYear(year):
if year%4 != 0:
return False
elif year%100 !=0:
return True
elif year%400 !=0:
return False
else:
return True
def daysInMonth(month, year):
daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month == 2 and isLeapYear(year):
daysOfMonths[month-1] += 1
return daysOfMonths[month-1]
def nextDay(year, month, day):
"""Simple version: assume every month has 30 days"""
if day < daysInMonth(month, year):
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
# YOUR CODE HERE!
days = 0
second_date = (year2, month2, day2)
first_date = (year1, month1, day1)
assert not first_date > second_date
while first_date < second_date:
days += 1
first_date = nextDay(*first_date)
return days
def test():
test_cases = [((2012,1,1,2012,2,28), 58),
((2012,1,1,2012,3,1), 60),
((2011,6,30,2012,6,30), 366),
((2011,1,1,2012,8,8), 585 ),
((1900,1,1,1999,12,31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
else:
print "Test case passed!"
test()
|
885f286dede01bb151f8a9145219fee8a1544905 | DjElad/PycharmProjects | /pythonProject/encode.py | 288 | 3.59375 | 4 | def duplicate_encode(word):
word = word.lower()
lst = [str(i) for i in word]
res = []
for x in range(0, len(lst)):
if word.count(lst[x]) > 1:
res.append(")")
else:
res.append("(")
print("".join(res))
duplicate_encode("(( @")
|
9bca67af509859de71d49928ae773d8acbf5a14c | SravanthiSinha/holbertonschool-webstack_basics | /0x01-python_basics/4-add.py | 280 | 3.828125 | 4 | #!/usr/bin/python3
add = __import__("add_4").add
def addition():
"""calls the add function passing with the value of a and b"""
a = 1
b = 2
print("{} + {} = {}".format(a, b, add(a, b)))
"""not executed when imported"""
if __name__ == "__main__":
addition()
|
e9ec010604334aa592a34eb31d6c6221f876804f | SuhwanJang/Code_History | /Python/CSVFileSorting/main.py | 773 | 3.671875 | 4 | import csv
from algorithm.sort import *
from algorithm.search import *
# ---- 패키지 안의 모듈을 import ----#
# ----------------------------------#
result = []
key = []
with open("unsorted.csv", 'r') as p_file:
csv_data = csv.reader(p_file) # Open한 파일을 csv 객체를 사용해서 읽기
for row in csv_data:
row = [int(i) for i in row]
key.append(row[len(row)-1])
row.pop()
row = insertion_sort(row)
result.append(row)
print(result)
key = binary_search(result, key)
for i in range(0, len(key)):
result[i].append(key[i])
with open("sorted.csv", 'w') as i_p_file:
writer = csv.writer(i_p_file, delimiter=',', lineterminator='\n')
for data in result:
writer.writerow(data) |
d57e951c0f2e1d179734e548b05b541662b589a2 | khshim/lemontree | /lemontree/generators/image.py | 11,133 | 3.734375 | 4 | """
This code includes image generators to make minibatch and shuffle.
Generator make data to feed into training function for every mini-batch.
Each generator can hold multiple data, such as data and label.
Image Generator preprocess image before training and during training.
"""
import numpy as np
from lemontree.generators.generator import SimpleGenerator
class ImageGenerator(SimpleGenerator):
"""
This class get image data 4D tensor and generate mini-batch.
Only one of the input data can be an image.
YUV, GCN, LCN, ZCA - preprocessing. done through all data.
flip, padding, crop - done during making mini-batch.
"""
def __init__(self, data_list, batch_size=128,
flip_lr=False, flip_ud=False, padding=None, crop_size=None,
image_index=0, name=None, seed=334):
"""
This function initializes the class.
Preprocessing is different to random generation.
Preprocessing is done before training, while random generation is done for each mini-batch during training.
Parameters
----------
data_list: list
a list of data, each include equal number of data.
batch_size: int
an integer value, which is the number of data in mini-batch.
flip_lr: bool, default: False
an bool value, whether randomly flip image left-right with probability 0.5 or not.
flip_ud: bool, default: False
an bool vaue, whether randomly flip image up-down with probability 0.5 or not.
padding: tuple, default: None
a tuple of (padding up, padding down, padding left, padding right).
crop_size: tuple, default: None
a tuple of (crop width, crop height).
randomly crop the image of given size.
image_index: int, default: 0
an integer which indicates which of the given data is an image.
usually first one is image.
name: string
a string name of the class.
seed: int
an integer value of numpy random generator.
Returns
-------
None.
"""
super(ImageGenerator, self).__init__(data_list, batch_size, name, seed)
# check asserts
assert isinstance(flip_lr, bool), '"flip_lr" should be a bool value.'
assert isinstance(flip_ud, bool), '"flip_ud" should be a bool value.'
if padding is not None:
assert isinstance(padding, tuple) and len(padding) == 4, '"padding" should be a tuple of length 4.'
if crop_size is not None:
assert isinstance(crop_size, tuple) and len(crop_size) == 2, '"crop_size" should be a tuple of length 2.'
assert isinstance(image_index, int) and image_index < self.max_data, '"image_index" should be an integer under total data in "data_list".'
assert len(self.data_list[image_index].shape) == 4, 'A data of "image_index" should be an image of 4D tensor.'
# set members
self.flip_lr = flip_lr
self.flip_ud = flip_ud
self.padding = padding
self.crop_size = crop_size
self.image_index = image_index
def rgb_to_yuv(self):
"""
This function converts RGB channel to YUV channel.
Assume r, g, b order in channel
Parameters
----------
None.
Returns
-------
None.
"""
image = self.data_list[self.image_index]
new_data = np.zeros_like(image, image.dtype)
new_data[:, 0, :, :] = 0.299 * image[:, 0, :, :] + 0.587 * image[:, 1, :, :] + 0.114 * image[:, 2, :, :]
new_data[:, 1, :, :] = 0.5 - 0.168736 * image[:, 0, :, :] - 0.331364 * image[:, 1, :, :] + 0.5 * image[:, 2, :, :]
new_data[:, 2, :, :] = 0.5 + 0.5 * image[:, 0, :, :] - 0.418688 * image[:, 1, :, :] - 0.081312 * image[:, 2, :, :]
self.data_list[self.image_index] = new_data
def yuv_to_rgb(self):
"""
This function converts RGB channel to YUV channel.
Assume y, u, v order (or y, cb, cr) in channel
Parameters
----------
None.
Returns
-------
None.
"""
image = self.data_list[self.image_index]
new_data = np.zeros_like(image, image.dtype)
new_data[:, 0, :, :] = image[:, 0, :, :] + 1.402 * (image[:, 2, :, :] - 0.5)
new_data[:, 1, :, :] = image[:, 0, :, :] - 0.34414 * (image[:, 1, :, :] - 0.5) - 0.71414 * (image[:, 2, :, :] - 0.5)
new_data[:, 2, :, :] = image[:, 0, :, :] + 1.772 * (image[:, 1, :, :] - 0.5)
self.data_list[self.image_index] = new_data
def global_mean_sub(self, mean=None):
"""
This function substract mean through all batch per pixel.
Parameters
----------
mean: ndarray, default: None
an 3D numpy array which contains global mean of pixels.
if none, compute mean and return.
Returns
-------
ndarray
an 3D numpy array which contains global mean of pixels.
"""
image = self.data_list[self.image_index]
if mean is None:
mean = np.mean(image, axis = 0) # compute mean through batch dimension
result = image - mean
self.data_list[self.image_index] = result
return mean
def global_std_div(self, std=None):
"""
This function divide std through all batch per pixel.
Parameters
----------
std: ndarray, default: None
an 3D numpy array which contains global std of pixels.
if none, compute mean and return.
Returns
-------
ndarray
an 3D numpy array which contains global std of pixels.
"""
image = self.data_list[self.image_index]
if std is None:
std = np.std(image, axis = 0) # compute std through batch dimension
result = image / (std + 1e-7)
self.data_list[self.image_index] = result
return std
def gcn(self, mean=None, std=None):
"""
This function is combination of "global_mean_sub" and "global_std_div".
Parameters
----------
mean: ndarray, default: None
an 3D numpy array which contains global mean of pixels.
if none, compute mean and return.
std: ndarray, default: None
an 3D numpy array which contains global std of pixels.
if none, compute mean and return.
Returns
-------
tuple
two 3D numpy array which contains global mean and std of pixels.
"""
mean = self.global_mean_sub(mean)
std = self.global_std_div(std)
return mean, std
def local_mean_sub(self):
"""
This function substract mean through all pixel per data.
Parameters
----------
None.
Returns
-------
None.
"""
image = self.data_list[self.image_index]
flat = np.reshape(image, (image.shape[0], np.prod(image.shape[1:])))
mean = np.mean(flat, axis=-1)
flat = flat - mean[:, np.newaxis]
result = np.reshape(flat, image.shape)
self.data_list[self.image_index] = result
def local_std_div(self):
"""
This function divide std through all pixel per data.
Parameters
----------
None.
Returns
-------
None.
"""
image = self.data_list[self.image_index]
flat = np.reshape(image, (image.shape[0], np.prod(image.shape[1:])))
std = np.std(flat, axis=-1)
flat = flat / (std[:, np.newaxis] + 1e-7)
result = np.reshape(flat, image.shape)
self.data_list[self.image_index] = result
def lcn(self):
"""
This function is combination of "local_mean_sub" and "local_std_div".
Parameters
----------
None.
Returns
-------
None.
"""
self.local_mean_sub()
self.local_std_div()
def zca(self, pc_matrix=None):
"""
This function performs ZCA transform of input data.
All channels are flattened and used for convariance matrix computation.
Parameters
----------
pc_matrix: ndarray, default: None
an 2D numpy array which contains ZCA whitening matrix.
if none, compute pc_matrix.
Returns
-------
ndarray
an 2D numpy array of ZCA whitening matrix.
"""
image = self.data_list[self.image_index]
flat = np.reshape(image, (image.shape[0], np.prod(image.shape[1:])))
if pc_matrix is None:
sigma = np.dot(flat.T, flat) / flat.shape[0]
U, S, V = np.linalg.svd(sigma)
newS = np.diag(1.0 / (np.sqrt(S) + 1e-7))
pc_matrix = np.dot(np.dot(U, newS), np.transpose(U))
white = np.dot(flat, pc_matrix)
result = np.reshape(white, image.shape)
self.data_list[self.image_index] = result
return pc_matrix
def get_minibatch(self, index):
"""
This function overrides parents' ones.
Generates the mini batch data.
If preprocessing exist, do preprocessing for cropped mini-batch first.
Parameters
----------
index: int
an integer value that indicates which mini batch will be returned.
Returns
-------
tuple
a tuple of partial data in data list.
"""
# check asserts
assert index <= self.max_index, '"index" should be below maximum index.'
# make returns
data = ()
data_index = 0
for dd in self.data_list:
if data_index == self.image_index:
image = dd[self.order[self.batch_size * index: self.batch_size * (index+1)]]
if self.flip_lr:
random_choice = self.rng.permutation(self.batch_size)[:self.batch_size//2]
image[random_choice] = image[random_choice, :, :, ::-1]
if self.flip_ud:
random_choice = self.rng.permutation(self.batch_size)[:self.batch_size//2]
image[random_choice] = image[random_choice, :, ::-1]
if self.padding is not None:
image = np.pad(image, ((0,0),(0,0),(self.padding[0], self.padding[1]),(self.padding[2], self.padding[3])), mode='edge')
if self.crop_size is not None:
random_row = self.rng.randint(0, image.shape[2] - self.crop_size[0] + 1)
random_col = self.rng.randint(0, image.shape[3] - self.crop_size[1] + 1)
image = image[:,:,random_row:random_row + self.crop_size[0], random_col:random_col + self.crop_size[1]]
data = data + (image,)
else:
data = data + (dd[self.order[self.batch_size * index: self.batch_size * (index+1)]],)
data_index += 1
assert data_index == self.max_data
return data
|
4f4e34e6e44eaeab6b1abf3da474b1c41aca289f | khshim/lemontree | /lemontree/data/gutenberg.py | 3,396 | 3.671875 | 4 | """
This code includes functions to preprocess text in gutenberg dataset.
Especially, for certain book.
Download
--------
Project Gutenberg.
https://www.gutenberg.org/ebooks/
Base datapath: '~~~/data/'
Additional folder structure: '~~~/data/gutenberg/alice_in_wonderland.txt'
SAVE THE TEXT TO ANSI FORMAT.
"""
import time
import numpy as np
class GutenbergWordCorpus(object):
"""
This class use gutenberg book text to make better tensor form.
Word level sequence pre-processing.
"""
def __init__(self, base_datapath, mode='alice_in_wonderland', eos=True, sos=False, lower=True):
"""
This function initializes the class.
Currently, only one book per class is implemented.
Reading multiple books at one time is for future implementation.
For initialization, split text into sentences.
Parameters
----------
base_datapath: string
a string path where textbook is saved.
mode: string, default: 'alice_in_wonderland'
a string which will be target book.
i.e., 'alice_in_wonderland.txt'
eos: bool, default: True.
a bool value to determine whether to put <eos> at the end of sentences.
sos: bool, default: False.
a bool value to determine wheter to put <sos> at the front of sentences.
lower: bool, default: True.
a bool value, whether we should lower all cases or not (for english).
Returns
-------
None.
"""
# check asserts
assert isinstance(base_datapath, str), '"base_datapath" should be a string path.'
assert isinstance(mode, str), '"mode" should be a string name for textbook.'
assert isinstance(eos, bool), '"eos" should be a bool value to determine <eos> insert or not.'
assert isinstance(sos, bool), '"eos" should be a bool value to determine <sos> insert or not.'
# load
book_file = base_datapath + 'gutenberg/' + mode + '.txt'
print('Gutenberg load book:', book_file)
start_time = time.clock()
import nltk
with open(book_file, 'r') as f:
if lower:
corpus = f.read().lower().replace('\n', ' ')
else:
corpus = f.read().replace('\n', ' ')
# nltk.download() # download model -> punkt if you get an error
self.sentences = nltk.tokenize.sent_tokenize(corpus) # a list of sentences, each sentence is string
for i in range(len(self.sentences)):
words_from_string = nltk.tokenize.word_tokenize(self.sentences[i])
if eos:
words_from_string = words_from_string + ['<EOS>']
if sos:
words_from_string = ['<SOS>'] + words_from_string
self.sentences[i] = words_from_string # string to word, now sentence is list of list of words
print('Gutenberg number of sentences:', len(self.sentences))
end_time = time.clock()
print('Gutenberg load time:', end_time - start_time)
if __name__ == '__main__':
base_datapath = 'C:/Users/skhu2/Dropbox/Project/data/'
guten = GutenbergWordData(base_datapath, 'alice_in_wonderland',
eos=True, sos=False)
for i in range(10):
seq = guten.sentences[i]
print(len(seq))
|
d3c023cedac286f682bf242bf66211e413b0e0fd | reveriess/TarungLabDDP1 | /lab/05/lab05_b_d.py | 2,219 | 3.6875 | 4 | '''
Program Mini-Kuis DDP1
Program untuk mengerjakan kuis yang berisi 4 buah pertanyaan yang meminta
user untuk mengkonversi bilangan biner ke bilangan desimal.
'''
def cetak_pertanyaan(urutan, angka_biner):
'''
Mencetak pertanyaan
'''
print("Soal {}: Berapakah angka desimal dari bilangan biner {}?"
.format(urutan, angka_biner))
def cek_jawaban(jawaban, angka_biner):
'''
Mengecek kebenaran jawaban
'''
return jawaban == int(angka_biner, 2)
def main():
'''
Program utama
'''
print("Selamat datang di Mini Kuis DDP-1: Sistem Bilangan!")
# Menyimpan soal
soal1 = "11111100001"
soal2 = "11111001111"
soal3 = "10001100"
soal4 = "100011101"
counter_soal = 1
skor = 0
while counter_soal <= 4:
# Menyesuaikan counter_soal dengan soal yang digunakan
if counter_soal == 1:
angka_biner = soal1
elif counter_soal == 2:
angka_biner = soal2
elif counter_soal == 3:
angka_biner = soal3
else:
angka_biner = soal4
# Mencetak pertanyaan sesuai dengan counter soal
# dan angka biner untuk counter tersebut
cetak_pertanyaan(counter_soal, angka_biner)
# Meminta input jawaban, format output: “Jawab: <input_di_sini>”
jawaban = int(input("Jawab: "))
# Mengecek apakah jawabannya benar
if cek_jawaban(jawaban, angka_biner):
skor += 25
# Menambahkan counter soal
counter_soal += 1
# Mencetak skor akhir, format output: “Skor akhir: <skor>""
print("Skor akhir: {}".format(skor))
def main_bonus():
'''
Program bonus
'''
print("\nSelamat datang di Mini Kuis DDP-1: Sistem Bilangan!")
# Meminta input soal
list_soal = input("Masukkan 4 soal: ").split()
skor = 0
for i, soal in enumerate(list_soal):
cetak_pertanyaan(i + 1, soal)
jawaban = int(input("Jawab: "))
if cek_jawaban(jawaban, soal):
skor += 25
print("Skor akhir: {}".format(skor))
if __name__ == '__main__':
main()
main_bonus()
|
eb2f50317c0a20a34da8283953118fa386a2b2a5 | reveriess/TarungLabDDP1 | /lab/01/lab01_b_d_s1.py | 1,622 | 4 | 4 | '''
Program gambar bentuk anak tangga
Menggambar 3 buah anak tangga dengan panjang anak tangga berdasarkan input dari
user. Penggambaran dilakukan menggunakan Turtle Graphics.
'''
# Inisialisasi
# Mengimpor modul turtle
import turtle
# Menginstansiasi objek turtle "kura"
kura = turtle.Turtle()
# Meminta input untuk menentukan
# panjang sisi anak tangga
sisi = int(input("Masukkan panjang sisi anak tangga: "))
# Mengaktifkan pena
kura.pendown()
# Penggambaran
# Menggunakan tinta kuning
kura.color('yellow')
# Memutar pena ke kiri sebesar 90 derajat
# sehingga pena menghadap ke atas
kura.left(90)
# Bergerak maju sebesar panjang sisi
# yang telah ditentukan
kura.forward(sisi)
# Memutar pena ke kanan sebesar 90 derajat
# sehingga pena menghadap ke kanan
kura.right(90)
# Bergerak maju sebesar panjang sisi
kura.forward(sisi)
# Mengulang langkah-langkah di atas
# untuk kedua anak tangga yang lain
kura.color('blue')
kura.left(90)
kura.forward(sisi)
kura.right(90)
kura.forward(sisi)
kura.color('red')
kura.left(90)
kura.forward(sisi)
kura.right(90)
kura.forward(sisi)
# Menutup anak tangga
# Menggunakan tinta hijau
kura.color('green')
# Memutar pena ke kanan sebesar 90 derajat
# sehingga pena menghadap ke bawah
kura.right(90)
# Bergerak maju sebesar tiga kali
# panjang sisi yang telah ditentukan
kura.forward(3 * sisi)
# Memutar pena ke kanan sebesar 90 derajat
# sehingga pena menghadap ke kiri
kura.right(90)
# Bergerak maju sebesar tiga kali
# panjang sisi yang telah ditentukan
kura.forward(3 * sisi)
# Menonaktifkan pena
kura.pendown()
# Menutup turtle setelah diklik
turtle.exitonclick()
|
bf6d09ae3d5803425cf95dd4e53fe62dad41fda0 | reveriess/TarungLabDDP1 | /lab/01/lab01_f.py | 618 | 4.6875 | 5 | '''
Using Turtle Graphics to draw a blue polygon with customizable number and
length of sides according to user's input.
'''
import turtle
sides = int(input("Number of sides: "))
distance = int(input("Side's length: "))
turtle.color('blue') # Set the pen's color to blue
turtle.pendown() # Start drawing
deg = 360 / sides # Calculate the turn
for i in range(sides):
turtle.forward(distance) # By using loop, turn and
turtle.left(deg) # move the turtle forward
turtle.hideturtle() # Hide the turtle/arrow
turtle.exitonclick() # Close the window on click event
|
4c1a5fb48e01821922bd7f3da9775d394caa8b0d | Datos-1-TEC/Circuit-Designer | /src/Dijkstra2.py | 4,262 | 4.3125 | 4 | import math
class Dijkstra2:
"""
Class used to get the shortest path or the largest path of two given nodes
Attributes------------------------
unvisited_nodes : graph, graph given by parameter
shortest_distance : dictionary, stores the shortest distance
route : list, gives the route of the nodes
predecessor : dictionary, stores the predecessor nodes of a graph
source : node, source node to start the algorithm
target : node, final node that indicates that the algorithm should end once it reaches it
Methods----------------------------
1. get_path()
gets the path between two nodes, this method works for the shortest path or largest path
"""
def __init__(self,graph,source,target, shortestpath):
self.unvisited_nodes = graph
self.shortest_distance = {}
self.route = []
self.predecessor = {}
self.shortestpath = shortestpath
self.source = source
self.target = target
def get_path(self):
# Iterating through all the unvisited nodes
for nodes in self.unvisited_nodes:
# Setting the shortest_distance of all the nodes as infinty
self.shortest_distance[nodes]=math.inf
# The distance of a point to itself is 0.
self.shortest_distance[self.source]=0
# Running the loop while all the nodes have been visited
while(self.unvisited_nodes):
# setting the value of min_node as None
min_Node=None
# iterating through all the unvisited node
for current_node in self.unvisited_nodes:
if min_Node is None:
min_Node=current_node
elif self.shortest_distance[min_Node] > self.shortest_distance[current_node]:
min_Node = current_node
for child_node,value in self.unvisited_nodes[min_Node].items():
if self.shortestpath:
if value + self.shortest_distance[min_Node] < self.shortest_distance[child_node]:
self.shortest_distance[child_node] = value + self.shortest_distance[min_Node]
self.predecessor[child_node] = min_Node
else:
self.shortest_distance[child_node] = value + self.shortest_distance[min_Node]
self.predecessor[child_node] = min_Node
self.unvisited_nodes.pop(min_Node)
# Till now the shortest distance between the source node and target node
# has been found. Set the current node as the target node
node = self.target
# Starting from the goal node, we will go back to the source node and
# see what path we followed to get the smallest distance
while node != self.source:
# As it is not necessary that the target node can be reached from # the source node, we must enclose it in a try block
try:
self.route.insert(0,node)
node = self.predecessor[node]
except Exception:
print('Path not reachable')
break
# Including the ssource in the path
self.route.insert(0,self.source)
# If the node has been visited,
if self.shortest_distance[self.target] != math.inf:
# print the shortest distance and the path taken
print('Shortest distance is ' + str(self.shortest_distance[self.target]))
print('And the path is ' + str(self.route))
# Remove the below comment if you want to show the the shortest distance
#from source to every other node
# print(shortest_distance)
def get_route(self):
return self.route
# graph = {'C1': {'C2': 1}, 'C7': {'C0': 10}, 'C5': {'C6': 4}, 'C2': {'C3': 5}, 'C4': {'C5': 1}, 'C0': {'C1': 4, 'C4': 4}, 'C3': {'C6': 4}, 'C6': {'C7': 0}}
# dj = Dijkstra2(graph, 'C0', 'C7', False)
# dj.get_path()
|
67744e56f329d3236393a0bbeed33f78335c814b | burakozdemir/CSE321---Introduction-to-Algorithm-Design | /hw5/CSE321_HW5_141044027/CSE321_HW5_141044027/theft_StudentID.py | 1,423 | 3.5625 | 4 | #Algoritmada listenin icindeki ilk listenin her elemanına baslangıc oldgu ıcın bakıyor
#Daha sonra alttakı elemanlara duruma gore secım yapıyor.
#WorstCase:O(n'2) . Ic ice donguler oldgu ıcın n^2
def theft(amountOfMoneyInLand):
x = list(zip(*amountOfMoneyInLand))
currentIndex=0
result=0
for i in range(0,len(x[0])):
currentIndex=i
genelIndis = 1
resultTemp=x[0][i]
for m in range(genelIndis,len(x)):
t1 = currentIndex-1
t2 = currentIndex
t3 = currentIndex+1
max1 = 0
max2 = 0
max3 = 0
if( t1>=0 and t1<len(x[0]) ):
max1 = x[m][t1]
if(t2 >= 0 and t2 < len(x[0]) ):
max2 = x[m][t2]
if(t3 >= 0 and t3 < len(x[0]) ):
max3 = x[m][t3]
t=max(max1,max2,max3)
resultTemp+=t
if(t==max1):
currentIndex = t1
if (t == max2):
currentIndex = t2
if (t == max3):
currentIndex = t3
if(resultTemp>result):
result=resultTemp
return result
amountOfMoneyInLand= [[1,3,1,5], [2,2,4,1], [5,0,2,3], [0,6,1,2]]
res = theft(amountOfMoneyInLand)
print(res)
#Output: 16
amountOfMoneyInLand= [[10,33,13,15], [22,21,4,1], [5,0,2,3], [0,6,14,2]]
res = theft(amountOfMoneyInLand)
print(res)
#Output: 83 |
b43338373cdecf46e7f7b499a4fd77e6b2524552 | Saifullahshaikh/1st-detail-assignment | /problem 3.24.py | 195 | 4 | 4 | print('Saifullah, 18B-092-CS, A')
print('1st Detailed Assignment, Problem 3.24')
words = eval(input('Enter list of word: '))
for word in words:
if word != 'secret':
print(word)
|
33bc99d392cda0bea8b46e39be54390519422b87 | Saifullahshaikh/1st-detail-assignment | /Problem 3.31.py | 191 | 4 | 4 | print('Saifullah, 18B-092-CS, A')
print('1st Detailed Assignment, Problem 3.31')
x = eval(input('Enter x: '))
y = eval(input('Enter y: '))
r = 5
if x<r and x<r:
print('It is in!')
|
5795eb31750f0fd17609649455c9224636766976 | Saifullahshaikh/1st-detail-assignment | /Ex. 3.23.py | 478 | 3.734375 | 4 | print('Saifullah, 18B-092-CS, A')
print('1st Detailed Assignment, Ex. 3.23')
#(a)
print('\nEx. 3.23(a)')
for i in range(0,2):
print(i)
#(b)
print('\nEx. 3.23(b)')
for x in range(0,1):
print(x)
#(c)
print('\nEx. 3.23(c)')
for y in range(3,7):
print(y)
#(d)
print('\nEx. 3.23(d)')
for m in range(1,2):
print(m)
#(e)
print('\nEx. 3.23(e)')
for n in range(0,4):
print(n)
#(f)
print('\nEx. 3.23(d)')
for a in range(5,25,4):
print(a)
|
3b25b8e94fdd18cc667ef5587a17715e4a5f4d36 | driverxb/xb | /spider.py | 1,577 | 3.515625 | 4 | import sys
import nmap
scan_row = []
input_data = input('Please input hosts and port: ')
#scan_row以空格分隔
scan_row = input_data.split(' ')
if len(scan_row) != 2:
print("Input errors, example \"192.168.209.0/24 80,443,22 \"")
sys.exit(0)
#接收用户输入的主机
hosts = scan_row[0]
#接收用户收入的端口
port = scan_row[1]
try:
#创建端口扫描对象
nm = nmap.PortScanner()
except nmap.PortScannerError:
print('Nmap not found', sys.exc_info()[0])
sys.exit(0)
except Exception as e:
print("Unexpected error:", sys.exc_info()[0])
print(str(e))
sys.exit(0)
try:
#调用扫描方法,参数指定扫描主机hosts,nmap扫描命令行参数arguments
nm.scan(hosts=hosts, arguments=' -v -sS -p ' + port)
except Exception as e:
print("Scan error:" + str(e))
for host in nm.all_hosts():
print('---------------------------------------------------------------------')
#输出主机及主机名
print('Host : %s (%s)' % (host, nm[host].hostname()))
#输出主机状态,如up、down
print('State : %s' % nm[host].state())
#遍历扫描协议,tcp、udp
for proto in nm[host].all_protocols():
print('--------------')
#输出协议名
print('Protocol : %s' % proto)
#获取协议的所有扫描端口
lport = list(nm[host][proto].keys())
#端口列表排序
lport.sort()
#遍历端口输出端口与状态
for port in lport:
print('port %s\tstate : %s' % (port, nm[host][proto][port]['state']))
|
57ca71ae3723dacbcbcde871453e81a6e060e7eb | pdeesawat4887/python_daily | /SAT_2019_02_23/leap_year.py | 1,100 | 3.890625 | 4 | class LeapYear:
def __init__(self):
while True:
self.option = int(input("Enter option 1:[A.D.] or 2:[B.E.]: "))
self.statement = {
1: self.calculator_leap_year,
2: self.buddhist_era
}
try:
self.statement[self.option](int(input("Enter a year: ")))
except KeyError as error:
print("Please insert 1:[A.D.] or 2:[B.E.]: only.")
def buddhist_era(self, input_year):
self.calculator_leap_year(input_year - 543)
def calculator_leap_year(self, input_year):
if (input_year % 4) == 0:
if (input_year % 100) == 0:
if (input_year % 400) == 0:
print("{yrs} is a leap year".format(yrs=input_year))
else:
print("{yrs} is not a leap year".format(yrs=input_year))
else:
print("{yrs} is a leap year".format(yrs=input_year))
else:
print("{yrs} is not a leap year".format(yrs=input_year))
exit()
year = LeapYear()
|
35c3c4396ba98cd17a7b71bb42820557aceb1799 | pdeesawat4887/python_daily | /tue_2019_04_01/replace_word.py | 157 | 3.84375 | 4 | def replaceWord(string, old_word, new_word):
return string.replace(old_word, new_word)
print(replaceWord('Hello world 123 world 123', 'world', 'bug'))
|
a537096f9bbbb14068f63403ca94593874b22796 | eamritadutta/PythonSolutions | /MergeKSortedLists.py | 1,386 | 3.796875 | 4 | import sys
# merge K sorted lists where the lists are as follows:
# 3 4 10 12
# 1 5
# 7 11
def mergeKSortedLists(heads):
pMinNode = None
newHead = None
# scan values at pHeads of each list
while True:
minV = sys.maxint
minNode = None
for h in heads: # n3, n1, n7
if h is not None:
if h.val < minV:
minV = h.val
minNode = h
if minNode == None: # all lists have reached end
break
# for the selected minNode
if pMinNode is None:
pMinNode = minNode
newHead = minNode
else:
pMinNode.next = minNode
pMinNode = minNode
heads.remove(minNode)
heads.append(minNode.next)
# once you come out of the while loop
return newHead
class Node:
def __init__(self, n, v):
self.next = n
self.val = v
def test():
n12 = Node(None, 12)
n10 = Node(n12, 10)
n4 = Node(n10, 4)
n3 = Node(n4, 3)
n5 = Node(None, 5)
n1 = Node(n5, 1)
n11 = Node(None, 11)
n7 = Node(n11, 7)
newHead = mergeKSortedLists([n3, n1, n7])
printList(newHead)
def printList(head):
vals = []
while head is not None:
vals.append(head.val)
head = head.next
print " ".join(str(v) for v in vals)
# call test code
test()
|
e89e3ac1c03ad1d3ee103df8b81fc76d16f2912a | eamritadutta/PythonSolutions | /RemDupsFromList.py | 872 | 3.921875 | 4 | # class for node
class Node:
def __init__(self, val, next):
self.val = val
self.next = next
# create the following list inside a method
# 1->1->2->3->3
def create_list():
three_one = Node(3, None)
three_two = Node(3, three_one)
two = Node(2, three_two)
one_one = Node(1, two)
head = Node(1, one_one)
return head
def rem_dups(head):
# base case; head == None
if head == None:
return None
n = head
while n != None and n.val == head.val:
n = n.next
head.next = n
rem_dups(head.next)
return head
def print_list(head):
while head != None:
print str(head.val) + "->"
head = head.next
head = create_list()
print "Input list with duplicates: "
print_list(head)
new_head = rem_dups(head)
# new_head = rem_dups(None)
print
print "De-duped list: "
print_list(new_head)
|
09b89bfbe5eb2b5ab29ab8cef9e979e29897f172 | eamritadutta/PythonSolutions | /mergeSortedList.py | 957 | 3.96875 | 4 | def mergeSortedLists(l1, l2):
p1 = 0
p2 = 0
sortedl = []
while p1 < len(l1) and p2 < len(l2):
if l1[p1] > l2[p2]:
sortedl.append(l2[p2])
p2 += 1
else:
sortedl.append(l1[p1])
p1 += 1
# print sortedl
# print p1
# print p2
if p1 == len(l1):
# print "p2: " + str(p2)
# print "val: " + str(len(l2) - 1)
while p2 <= (len(l2) - 1):
#print "inc p2"
sortedl.append(l2[p2])
p2 += 1
if p2 == len(l2):
# print "p1: " + str(p1)
# print "val: " + str(len(l1) - 1)
while p1 <= (len(l1) - 1):
#print "inc p1"
sortedl.append(l1[p1])
p1 += 1
print sortedl
return sortedl
mergeSortedLists([1], [3,4])
mergeSortedLists([1,2], [3])
mergeSortedLists([1,2], [])
mergeSortedLists([], [3,4])
mergeSortedLists([], [])
mergeSortedLists([1,2], [3,4])
|
7657e0aa494bb651a05632b1a32ea0c0a80b0abb | eamritadutta/PythonSolutions | /LongestIncSequence.py | 2,741 | 4.03125 | 4 | # The following algorithm returns the length of longest increasing sequence in a input array in O(N log N) time
# first I am trying to reason about the problem on lines similar to the explanation at GeeksForGeeks
# lets start with the input array:
# A = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
# to solve the problem in O(N log N) time, we need another array to keep
# track of the end indices of increasing sequences (of unique length)
# In the end, the length of B is the length of the longest increasing sequence in A
# for the sake of clarity in explanation, I will have more than one array below
# scan A[0] and put it in B[0]
# now scan A[1] = 8
# search for 8 in B. the index 1 will be returned since 8 > 0
# B[1] = 8
# B = [0, 8]
# now scan A[2] = 4
# search for 4 in B
# the index 1 will be returned
# B[1] = 4
# B = [0, 4]
# now scan A[3] = 12
# search for 12 in B
# the index 2 will be returned
# B[2] = 12
# B = [0, 4, 12]
# now scan A[4] = 2
# search for 2 in B
# the index 1 will be returned
# B[1] = 2
# B = [0, 2, 12]
# now scan A[5] = 10
# search for 10 in B
# the index 2 will be returned
# B[2] = 10
# B = [0, 2, 10]
# A = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
# now scan A[6] = 6
# search for 6 in B
# the index 2 will be returned
# B[2] = 6
# B = [0, 2, 6]
# now scan A[7] = 14
# search for 14 in B
# the index 3 will be returned
# B[3] = 14
# B = [0, 2, 6, 14]
def findElementInArray(s, B, st, end): # 0 2 B=[0, 4, 12] s=2
# stop when end < st
# at this point we have to return an index which will be the appropriate
# position for 's' in B
if end < st:
return st
mid = st + ((end - st + 1) / 2) # 0
# this should never happen in this problem, if all the elements in the
# input array are unique
if s == B[mid]: # B[mid] = 4
return mid
elif s > B[mid]:
return findElementInArray(s, B, mid + 1, end) # 1 0
else:
return findElementInArray(s, B, st, mid - 1) # 0 0
def printLenOfLis(A):
# sanity check
if len(A) == 0 or A is None:
print "Invalid input array"
return
# scan A[0] and put it as the first element of B
B = [A[0]]
# scan A starting from the index 1
for i in xrange(1, len(A)):
# search for A[i] in B by calling a recursive method
ins = findElementInArray(A[i], B, 0, len(B) - 1)
if ins == len(B):
B.append(A[i])
else: # ins < len(B). Note: ins can never be > len(B)
# overwrite
B[ins] = A[i]
print "The length of the LIS in " + str(A) + " is: " + str(len(B))
# test code - Example is from wikipedia
printLenOfLis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])
|
a85557a0977048f499e4e594e493dba49396f780 | zellstrife/Python | /Ex005.py | 159 | 4.125 | 4 | n1 = int(input('Digite um numero: '))
print('O numro escolhido foi: {}'
'\n Seu antecessor é: {}'
'\nSeu sucessor é: {}'.format(n1,n1-1,n1+1)) |
fab57e2099f63f2113edf1075432a2375981009f | zellstrife/Python | /Ex040.py | 956 | 3.84375 | 4 | aluno = str(input('Digite o nome do aluno: '))
p1 = float(input('Digite a nota da P1 do aluno {}: '.format(aluno)))
p2 = float(input('Digite a nota da P2 do aluno {}: '.format(aluno)))
p3 = float(input('Digite a nota da P3 do aluno {}: '.format(aluno)))
p4 = float(input('Digite a nota da P4 do aluno {}: '.format(aluno)))
media = (p1+p2+p3+p4)/4
if media >= 0 and media < 5:
print('Aluno: {}'
'\n Você esta REPROVADO com a média final de: {}'.format(aluno, media))
elif media >= 5 and media < 7:
print('Aluno: {}'
'\n Você esta RECUPERAÇÃO com a média final de: {}'
'\nEstude mais e você conseguirá !!!'.format(aluno, media))
elif media >= 7 and media <= 10:
print('Aluno: {}'
'\n Você esta APROVADO com a média final de: {}'
'\n Parabens, vejo você no proximo ano'.format(aluno, media))
else:
print('Analise novamente as notas, os valores estão errados') |
a448f0328cb4544480726b8b821e68a13d6a47c7 | zellstrife/Python | /Ex030.py | 216 | 3.75 | 4 | import random
n = random.randint(0,1000)
m = n%2
if(m == 0):
print('Numero: {}'
'\n Este numero é PAR'.format(n))
else:
print('Numero: {}'
'\n Este numero é IMPAR'.format(n)) |
0e9a26ead6f13a4301f7741c72d700fa6c4a3ca2 | zellstrife/Python | /Ex043.py | 1,207 | 3.890625 | 4 | nome = str(input('Digite o nome da pessoa a ser analisada: '))
peso = float(input('Digite o peso em Kg de {}: '.format(nome)))
altura = float(input('Digite a altura de {}: '.format(nome)))
imc = peso / (altura * altura)
if imc < 18.5:
print('Nome: {}'
'\nPeso: {}Kg'
'\nAltura: {}M'
'\nVocê esta abaixo do peso ideal'.format(nome, peso, altura))
elif imc <= 25:
print('Nome: {}'
'\nPeso: {}Kg'
'\nAltura: {}M'
'\nVocê esta no seu peso ideal'.format(nome, peso, altura))
elif imc <= 30:
print('Nome: {}'
'\nPeso: {}Kg'
'\nAltura: {}M'
'\nVocê esta com sobrepeso'.format(nome, peso, altura))
elif imc <= 40:
print('Nome: {}'
'\nPeso: {}Kg'
'\nAltura: {}M'
'\nVocê esta obeso'.format(nome, peso, altura))
elif imc < 0:
print('Nome: {}'
'\nPeso: {}Kg'
'\nAltura: {}M'
'\nAlgo esta errado com as informações'.format(nome, peso, altura))
else:
print('Nome: {}'
'\nPeso: {}Kg'
'\nAltura: {}M'
'\nVocê esta com obesidade morbita, se cuide'.format(nome, peso, altura)) |
3e91723032ccc985d8e5518fdb66cbc27f73e90c | zellstrife/Python | /Ex020.py | 310 | 3.640625 | 4 | import random
al1 = str(input('Digite o nome do aluno: '))
al2 = str(input('Digite o nome do aluno: '))
al3 = str(input('Digite o nome do aluno: '))
al4 = str(input('Digite o nome do aluno: '))
list = [al1,al2,al3,al4]
random.shuffle(list)
print('A ordem de apresentação será: {}'.format(list)) |
7dfa59fdc67172ceca72a859cc73de72027d0e08 | mdrummond1/euler | /multiples_3_and_5.py | 531 | 4.09375 | 4 | def listMulThree():
for num in range(1000):
if (num % 3 == 0):
print(num)
def listMulFive():
for num in range(1000):
if (num % 5 == 0):
print(num)
def addMuls():
sum = 0
for num in range(1000):
if (num % 3) == 0:
sum += num
if (num % 3) == 0 and (num % 5) == 0:
continue
if (num % 5) == 0:
sum += num
return sum
listMulThree()
listMulFive()
print("Sum of all multiples of three or five is %i" % (addMuls())) |
ef031629d2e3ac0da8e5052078cc710f549fb4ed | boristsarkov/Project | /tsak_1_2.py | 1,970 | 3.671875 | 4 | cubes = [x**3 for x in range(1000) if x % 2 != 0]
my_numbers_sum = 0
my_numbers_sum_list = []
total_7 = 0 # Переменна суммы чисел делящихся на 7
total_17 = 0 # Переменная суммы чисел делящихся на 7 после прибавки 17
# проход по списку
for i in range(len(cubes)):
my_str = str(cubes[i])
my_list = list(my_str)
for i in range(len(my_list)):
my_list[i] = int(my_list[i])
# Вычисление суммы чисел
for i in range(len(my_list)):
my_numbers_sum = my_numbers_sum + my_list[i]
# Условие деления на 7 без остатка
if my_numbers_sum % 7 == 0:
my_numbers_sum_list.append(my_numbers_sum)
# сумма чисел кубов делящихся без остатка на 7
for i in range(len(my_numbers_sum_list)):
total_7 = total_7 + my_numbers_sum_list[i]
print('Сумма кубов чисел делящихся на 7 =', total_7)
# Список кубов + 17
cubes = [(x**3)+17 for x in range(100) if x % 2 == 0]
my_numbers_sum = 0
my_numbers_sum_list_even_numbers = []
# проход по списку
for i in range(len(cubes)):
my_str = str(cubes[i])
my_list = list(my_str)
for i in range(len(my_list)):
my_list[i] = int(my_list[i])
# Вычисление суммы чисел
for i in range(len(my_list)):
my_numbers_sum = my_numbers_sum + my_list[i]
# Условие деления на 7 без остатка
if my_numbers_sum % 7 == 0:
my_numbers_sum_list_even_numbers.append(my_numbers_sum)
# сумма чисел кубов делящихся без остатка на 7
for i in range(len(my_numbers_sum_list_even_numbers)):
total_17 = total_17 + my_numbers_sum_list_even_numbers[i]
print('Сумма кубов чисел делящихся на 7 после прибавки числа 17 =', total_17)
|
aa6bbf6c626ebb5a060e6d3c2dcf7f860e9232a7 | yywecanwin/PythonLearning | /day04/13.列表的嵌套.py | 605 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/10/4
# 如果列表中的元素还是列表,你的列表就是嵌套的列表
name_list = [["孙俪", "谢娜", "贾玲"], ["蓉蓉", "百合", "露露"]]
print(name_list[0]) #['孙俪', '谢娜', '贾玲']
print(name_list[0][0]) # 孙俪
print(type(name_list[0])) # <class 'list'>
print(type(name_list[0][0])) # <class 'str'>
print(name_list[0][1]) # 谢娜
#遍历列表
for i in name_list:
print(i) # ['孙俪', '谢娜', '贾玲'] ['蓉蓉', '百合', '露露']
# 遍历每一个列表中的元素
for e in i:
print(e)
|
80c8b7551375a6c99acf300893897af119d5d6b7 | yywecanwin/PythonLearning | /day10/05.异常语句中else语句的使用.py | 484 | 3.75 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2020/2/9
"""
else 语句的格式:
try:
可能会出现异常的代码块
except(异常类1,异常2,。。。。) as 异常对象名:
处理异常的代码块
使用场景:
通常用来检测是否出现异常了
"""
list1 = [10,20]
try:
print(list1[1])
print(list1[2])
pass
except:
print("索引越界")
pass
else:
print("没有异常,说明索引没有越界")
|
8d6d1fc3f3d63ac15d819943203721f0fbc256d8 | yywecanwin/PythonLearning | /day06/11.可变类型和不可变类型.py | 995 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/12/28
"""
不可变类型
如果改变了类型的数据的值,地址 也发生了变化,这种类型的数据,是不可变类型的数据
常见类型
int float bool str tuple
可变类型
如果改变了该类型的数据的值,地址,没有 发生了变化,这种类型的数据,是可变类型的数据
常见类型
列表,字典,set集合
"""
a = 10
print(id(a)) # 140729720616048
a = 20
print(id(a)) # 140729720616368
print("*" * 50)
str1 = "hello"
print(id(str1)) # 2759820335400
str1 = "python"
print(id(str1)) # 2759938968632
print("*" * 50)
list1 = [10,20]
print(id(list1)) # 2327360791048
list1.append(30)
print(list1) # [10, 20, 30]
print(id(list1)) # 2327360791048
print("*" * 50)
dict1 = {"name":"爽儿","age":18}
print(id(dict1)) # 2327364323152
dict1['gender'] = "女"
print(dict1) # {'name': '爽儿', 'age': 18, 'gender': '女'}
print(id(dict1)) # 2327364323152
|
c4d6a7f80e4014f6e1bb56ed59065d0844bf0119 | yywecanwin/PythonLearning | /day09/04.子类中重写父类的方法.py | 1,018 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2020/2/2
"""
重写父类中的方法的原因:
父类中的方法不能满足子类的需要,但是子类又想保留这个方法名
重写父类中的方法
这就需要子类中定义一个同名的方法,这叫重写父类中的方法
如何重写:
1.把父类中的方法复制粘贴到子类中
2.在子类中秀修改方法体
特点:
子类重写了父类的方法后,当通过子类对象调用这个方法时,调用的是子类中的这个方法
"""
class Father: # class Father(object)
def __init__(self,money,house):
self.money = money
self.house = house
pass
def run_company(self):
print("父亲经营公司。。。。。")
pass
pass
# 子类继承父类
class Son(Father):
def run_company(self):
print("儿子经营公司。。。。")
pass
pass
s = Son(200000,"江苏省淮安市")
print(s.house)
print(s.money)
s.run_company()
|
7ebc2621de57aba29a68be3d6dacaa16ebf4c4dc | yywecanwin/PythonLearning | /day03/13.猜拳游戏.py | 657 | 4.125 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/9/28
import random
# 写一个死循环
while True:
# 1.从键盘录入一个1-3之间的数字表示自己出的拳
self = int(input("请出拳"))
# 2.定义一个变量赋值为1,表示电脑出的拳
computer = random.randint(1,3)
print(computer)
if((self == 1 and computer == 2) or (self == 2 and computer == 3) or (self == 3 and computer == 1)):
print("我又赢了,我妈喊我 回家吃饭了")
break
elif self == computer:
print("平局,我们在杀一盘")
else:
print("不行了,我要和你杀到天亮")
break
|
3d6608651b62ae8ed96025323afa81aa1943ae28 | yywecanwin/PythonLearning | /day01/06.字符串格式化操作符.py | 661 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/9/26
#如果输出的字符串中包含某一个变量的值,就需要使用字符串的格式操作符
"""
格式化操作:
%d 整数
%s 字符串
%f 小数
"""
age = 50
print("我的年龄是%d岁" % age) # 我的年龄是50岁
print("我的年龄是%d岁" % 50) # 我的年龄是50岁
username = "小庄"
print("用户的姓名是%s" % username)
pi = 3.1415
#如果是保留n位小数,在%的后面f的前面添加 .n
print("圆周率是%.2f" % pi)
num = 5
print("数字是%06d" % num)# 000005
age1 = 30
user_name = "铁娃"
print("我的姓名是%s,年龄是%d岁" % (user_name, age1))
|
b87055f8f74ad82c0568858cdf51d6e5e91b26a1 | yywecanwin/PythonLearning | /day02/11.逻辑运算符.py | 1,037 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/9/27
"""
and x and y 布尔"与": 并且的意思
如果 x 为 False,x and y 返回 False,否则它返回 y 的值。
True and False, 返回 False。
or x or y 布尔"或":
如果 x 是 True,它返回 True,否则它返回 y 的值。
False or True, 返回 True。
not not x 布尔"非":
如果 x 为 True,返回 False 。
如果 x 为 False,它返回 True。
not True 返回 False, not False 返回 True
"""
a = 10
b = 20
c = 30
# and
# 如果 x 为 False,x and y 返回 False,否则它返回 y 的值。
print((a > b) and (b > c)) # False and (b > c)->False
print((a < b) and (b > c)) # True and False->False
print((a < b) and (b < c)) # True and True->True
# or
print((a > b) or (b > c)) # False or False->False
print((a < b) or (b > c)) # True or (b > c)->True
print((a < b) or (b < c)) # True or True->True
# not 非,取相反的意思
print(not (a > b)) # not False -> True
print(not (a < b)) # not True -> False
|
d397ac5d24de87a8796eaa2e13deb5767bf58347 | yywecanwin/PythonLearning | /day08/02.__init__方法基本使用.py | 1,002 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2020/1/28
class Student:
"""
是一个魔法方法
比较特殊,Python解释器会自动在对象刚刚创建出来之后,立即调用这个方法
初始化对象:给对象添加属性并赋值
通过self给对象添加属性:
self.属性值 = 属性值
属性是存储在对象里面的
属性是属于对象的
访问属性:
对象名.属性名
"""
def __init__(self):
# 添加姓名
self.name = "姚嵇"
# 添加年龄
self.age = 20
# 添加性别
self.genderc = "man"
pass
def study(self,course):
print(f"学习{course}")
pass
pass
s1 = Student()
s1.study("python")
# 访问属性:对象名.属性名
print(s1.name) # 姚嵇
print(s1.age) # 20
print(s1.genderc) # man
# 修改属性的值
s1.genderc = "female"
print(s1.genderc) # female
|
53b4367b887dfd841dacd1814173058c374c5900 | yywecanwin/PythonLearning | /day07/06.set-list-tuple三者之间的类型转换.py | 535 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2020/1/11
"""
数据类型转换的格式:
目标数据类型(数据)
"""
# set->list
set1 = {10,20,30}
list2 = list(set1)
print(list2) # [10, 20, 30]
set2 = set(list2)
print(set2) #{10, 20, 30}
list3 = {10,20,30,40,10}
set3 = set(list3)
print(set3) # {40, 10, 20, 30}
list4 = list(set3)
print(list4) # [40, 10, 20, 30]
d = [1,2,3,4,15]
e = tuple(d)
print(e) # (1, 2, 3, 4, 15)
f = list(e)
print(f) # [1, 2, 3, 4, 15]
h = set(e)
print(h) # {1, 2, 3, 4, 15}
|
1f4e012554b7f319f279c89fa3c20eaf93fda517 | yywecanwin/PythonLearning | /day05/17.函数的嵌套调用.py | 228 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/12/18
def func1(a,b):
s = a + b
print(f"func1中的s:{s}")
def func2():
print("开始调用func2......")
func1(12,12)
print("func2结束了.....")
func2() |
857d4ee6a870d6633d23ca6a9dd3b58b2b4ca542 | yywecanwin/PythonLearning | /day07/03.递归函数.py | 460 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2020/1/10
"""
递归函数:
在函数的里面自己调用自己
定义递归函数的条件:
1.自己调用自己
2.必须设置一个终止递归条件
使用递归函数求1-5的累加和
"""
def sum(n):
# 条件2,设置终止递归的条件
if n == 1:
return 1
else:
# 条件1:自己调用自己
return n + sum(n-1)
print(sum(5))
|
eb42aaa882346528732e069a8cde5e7ad92155d0 | yywecanwin/PythonLearning | /day04/07.字符串常见的方法-查找-统计-分割.py | 885 | 4.25 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/9/28
s1 = "hello python"
# 1.查找"o"在s1中第一次出现的位置:s1.find()
print(s1.find("aa")) # -1
print(s1.find("o",6,11)) # 10
print(s1.find("pyt")) # 6
print(s1.rfind("pyt")) # 6
"""
index()方法,找不到将会报错
"""
# print(s1.index("o", 6, 11))
# print(s1.index("aa"))
#统计"o"出现的次数
print(s1.count("o"))
print(s1.count("o",6,12))
#分割的方法:s.split(str)
s2 = "hello python android"
# 分割的结果是一个列表,把分割出来的几部分字符串作为元素放到列表中了
list1 = s2.split(" ")
print(list1) # ['hello', 'python', 'android']
print(type(list1)) # <class 'list'>
# 这个方法只能分割出三部分:左边部分,自己,右边部分
list2 = s2.partition(" ")
print(list2) # ('hello', ' ', 'python android')
print(type(list2)) # <class 'tuple'>
|
95ce77d9c77b94715837162ed9e85dac67f64053 | yywecanwin/PythonLearning | /day04/15.元组.py | 922 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/10/5
"""
元组:
也是一个容器,可以存储多个元素,每一个元素可以是任何类型
元组是一个不可需改的列表,不能用于 增删改查操作,只能用于查询
定义格式:
定义非空元组
元组名 = (元素1,元素2,,,,,)
元组空元组
元组名 = ()
定义只有一个元素的元组
元组名 = (元素1,)
什么时候使用元组村粗一组数据?
当那一组数据不允许修改时,需要使用元组存储
"""
tuple1 = ("冬冬", "柳岩", "美娜")
print(tuple1) # ('冬冬', '柳岩', '美娜')
print(type(tuple1)) # <class 'tuple'>
# 根据索引得到元组中的元素: 元组名[索引]
print(tuple1[0])
print(tuple1[1])
print(tuple1[2])
# 定义只有一个元素的元组
tuple2 = (10,)
print(tuple2)
print(type(tuple2))
|
59b5e3d7675d3b0e2322cd958800fa71e3a2f090 | yywecanwin/PythonLearning | /day04/01.字符串.py | 817 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/9/28
name = "yaoyao"
age = 18
print("姓名是%s,年龄%d" % (name,age))
# f-strings
"""
f-strings
提供一种简洁易读的方式, 可以在字符串中包含 Python 表达式.
f-strings 以字母 'f' 或 'F' 为前缀, 格式化字符串使用一对单引号、双引号、三单引号、三双引号. 格式化字符串中
"""
f_string1 = f"姓名是{name},年龄是{age}"
print(f_string1)
f_string2 = f"3 + 5 = {3 + 5}"
print(f_string2)
print(type(f_string2))
a = 10
b = 20
f_string3 = f"a + b的和是:{a + b}"
print(f_string3)
# 两个花括号会被替换为一个花括号, 注意{{}} 不表示表达式
format_string7 = F'我的名字是 {{name}}, 我的年龄是 {{age}}'
print(format_string7) # 我的名字是 {name}, 我的年龄是 {age}
|
da05f4a044900727f15b01d2760e92660c4be5a3 | yywecanwin/PythonLearning | /day03/01.使用if语句实现三目运算符.py | 357 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/9/27
"""
if语句实现三目运算符(三元运算符)
a if a > b else b
向判断 a > b是否成立,如果成立计算的结果是a的值,否则就是b的值
"""
a = 20
b = 10
result = a if a > b else b
print(result) # 20
result2 = a + 10 if a < b else b + 200
print(result2) # 210
|
7229a9c285b03df22f176624c5e0f5b54b27a88d | yywecanwin/PythonLearning | /day04/03.字符串的遍历.py | 628 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2019/9/28
"""
字符串的遍历:
一个一个的得到里面的元素
"""
s = "hello python"
"""
# 遍历的方式1:
# 1.定义一个变量i 表示元素的索引,赋值为0,因为元素的索引是从0开始的
i = 0
# 2.while循环遍历字符串
while i <= len(s)-1:
#3.在循环中, 根据索引得到元素, 把元素打印出来
print(s[i])
# 4.在循环中,让i加1,是为了让索引加1,便于下次循环时得到下一个元素
i += 1
"""
"""
for 变量 in range()函数或者容器
"""
# 遍历方式2:for循环
for c in s:
print(c)
|
453e2b84ad87ba17af80dcd0761b8d06302a0b42 | DemonChaak/Final | /main.py | 2,207 | 3.640625 | 4 | import pygame
import random
###inicializando la libreria###
pygame.init()
####configurar pantalla####
size=(500,500)
pantalla=pygame.display.set_mode(size)
####Configuración del Reloj####
reloj=pygame.time.Clock()
#####configuración de Colores####
#r= Red, g=Green, b=Blue
negro=(0,0,0)
rojo=(255,0,0)
azul=(0,0,255)
verde=(0,255,0)
blanco=(255,255,255)
gris=(60,60,60)
color=(0,0,255)
####variable para controlar el juego#####
juego=True
#####VARIABLES DE CONTROL#####
x=100
y=100
velocidadX=10
velocidadY=10
puntos=0
nivel=1
tiempo=80
contador=tiempo
#####configurando los tipos de letras####
letra=pygame.font.Font(None,60)
#######configurar el fondo#########
#fondo=pygame.image.load("fondo.jpg")
####Para mantener la ventana abierta#####
while juego:
##### Para controlar los eventos#####
for event in pygame.event.get():
if event.type==pygame.QUIT:
juego=False
######control del mouse######
if event.type==pygame.MOUSEBUTTONDOWN:
if x-50<=event.pos[0]<=x+50:
if y-50<=event.pos[1]<=y+50:
x=random.randrange(50,750)
y=random.randrange(50,550)
contador=tiempo
nivel=nivel+1
color=(random.randrange(0,250), random.randrange(0,250) ,random.randrange(0,250))
#######controles del tiempo#####
contador=contador-1
if contador==0:
juego=False
#####Desliegue de la pantalla#####
pantalla.fill(color)
#pantalla.blit(fondo,(0,0))
pygame.draw.circle(pantalla,blanco,(x,y),50)
x=x+velocidadX
if x>=800:
velocidadX=-10
if x<=0:
velocidadX=+10
y=y+velocidadY
if y>=600:
velocidadY=-10
if y<=0:
velocidadY=+10
#######DESPLEGAR EL TEXTO DENTRO DEL JUEGO########
mensaje=letra.render("Nivel: "+str(nivel),1,blanco) ##texto se convirtio en una imagen
pantalla.blit(mensaje,(10,20)) #mostrar una imagen
mensaje=letra.render("Tiempo: "+str(contador),1,blanco)
pantalla.blit(mensaje,(500,20))
#################FIN DE TEXTO########################
pygame.display.update()
reloj.tick(30)
pygame.quit() |
f5a7f2c67206b679d03684202eff3afe35c81e23 | Gao-pw/PythonDemo | /EditFileName.py | 704 | 3.671875 | 4 | # coding:utf8
import os
def rename():
path = "D:\\work\\nzpt\\new\\1"
file_list = os.listdir(path)
for files in file_list:
print("原来文件名字是是:", files)
old_name = os.path.join(path, files)
if os.path.isdir(old_name):
continue
file_name = os.path.splitext(files)[0]
file_type = os.path.splitext(files)[1]
print(file_name, ":", file_type)
if file_type == ".jfif":
file_type_new = ".jpg"
new_dir = os.path.join(path, file_name+file_type_new)
print("新文件目录为", new_dir)
if __name__ == '__main__':
rename()
print("重命名结束")
|
8e95be25db4c8f25ca8a47df804e32b1e8e842cb | sylwiakulesza/kurs_taps_SK | /scripts/operatory.py | 680 | 3.90625 | 4 |
number = 1
number1 = 2
print(number + number1)
list = ['Ala', 'ma', 'kota']
print(list[0])
print(list[0:3])
text = 'test'
text1 = 'czesc, jestem "Sylwia"'
print(text1)
cities = {'city': ['Warszawa', 'Gdańsk', 'Bratysława']}
print(cities['city'])
print(cities['city'][2])
suma = 1 + 2
print(suma)
roznica = 1 - 2
print(roznica)
reszta = 11 % 3
print(reszta)
kwadrat = 10 ** 2
print(kwadrat)
szescian = 10 ** 3
print(szescian)
print('zmienna ' + 'jest ' + 'super')
zmienna = 'no siema ' * 10
print(zmienna)
parzyste = [2, 4, 6, 8]
nieparzyste = [1, 3, 5, 7]
naturalne = parzyste + nieparzyste
print(naturalne)
print(1 > 1)
print(1 < 1)
print(1 == 2)
print(1 != 2)
|
a5e38356ed1974b0290ceae4989e031720ca92d1 | rupert-adams/Fizz-Buzz-in-Python | /fizzBuzz.py | 585 | 3.703125 | 4 | class FizzBuzz(object):
def __init__(self, number):
if FizzBuzz.is_valid_number(number):
self.number = number
@property
def result(self):
if self.number % 3 == 0 and self.number % 5 == 0:
return "FizzBuzz"
elif self.number % 3 == 0:
return "Fizz"
elif self.number % 5 == 0:
return "Buzz"
return self.number
@staticmethod
def is_valid_number(number):
if number <= 0 or number > 100:
raise ValueError("Number must be between 0 and 101")
return True
|
a8206a6838f8a9d801dcac175988e0fd857edb4c | Gyeol0/TIL | /Algorithm/List/Gravity.py | 549 | 3.671875 | 4 | def gravity(N, lst):
max_height = 0
for i in range(N-1):
count = 0
# 밑에 있는 상자들 중에서 자신보다 높은 상자 count
for j in range(i+1, N):
if lst[i] <= lst[j]:
count += 1
# 오른쪽으로 회전하였을 때 현재 높이 - 자신보다 높거나 같은 상자 count
if max_height < N - (i+1) - count:
max_height = N - (i+1) - count
return max_height
N = int(input())
height = list(map(int, input().split()))
print(gravity(N, height))
|
f0c0488de2f340e22a7e5ba81456157386a85ce6 | Gyeol0/TIL | /Algorithm/Stack_practice/4866. 괄호검사.py | 605 | 3.78125 | 4 | def Parentheses(arr):
stack = []
P = {'(': ')', '{': '}', '[': ']'}
for i in arr:
# 여는 괄호인지 확인, 괄호면 스택에 추가
if i in P:
stack.append(i)
# 닫는 괄호인지 확인, top과 비교
elif i in P.values():
if stack:
s = stack.pop()
if P[s] != i:
return 0
else:
return 0
if stack:
return 0
else:
return 1
T = int(input())
for test in range(1, T+1):
arr = input()
print(f'#{test}', Parentheses(arr))
|
0bdb2a259ae6a04e72b10855fdd1878bf15a77a8 | Gyeol0/TIL | /Algorithm/List_practice/1289. 원재의 메모리 복구하기.py | 289 | 3.59375 | 4 | def Memory(bit):
count = 0
current = '0'
other = '1'
for i in bit:
if i != current:
current, other = other, current
count += 1
return count
T = int(input())
for test in range(1, T+1):
bit = input()
print(f'#{test}', Memory(bit)) |
5e4b5f1d3fa006c1530cccf6a121f157a3935db5 | Gyeol0/TIL | /Algorithm/List_practice/Factorization.py | 402 | 3.703125 | 4 | def Factorization(N):
F = [2, 3, 5, 7, 11]
answer = []
for i in F:
count = 0
while N % i == 0:
count += 1
N //= i
answer.append(count)
return answer
T = int(input())
for test in range(1, T+1):
N = int(input())
result = Factorization(N)
print(f'#{test}', end = ' ')
for i in result:
print(i, end = ' ')
print() |
1d60149c79a8ef1655923f0824ebfd1a279d81b5 | Gyeol0/TIL | /Algorithm/Stack_practice/4875. 미로.py | 703 | 3.5 | 4 | dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
def DFS(x, y):
global answer
# 도착하면 1
if arr[x][y] == '3':
answer = 1
# 아니면 방문
else:
arr[x][y] = '1'
for k in range(4):
ax = x + dx[k]
ay = y + dy[k]
# 벽이나 방문 한 곳이 아닐 때
if 0 <= ax < N and 0 <= ay < N and arr[ax][ay] != '1':
DFS(ax, ay)
T = int(input())
for test in range(1, T+1):
N = int(input())
answer = 0
arr = [list(input()) for _ in range(N)]
for i in range(N):
for j in range(N):
# 출발지에서 dfs 시작
if arr[i][j] == '2':
DFS(i, j)
print(f'#{test}', answer) |
8dec23cfd1bca66e7ce5744f915519a9f04cd061 | pavansw/anzPython | /switch1.py | 611 | 4.0625 | 4 | def my_circle(r):
return 3.14*r*r
def my_square(s):
return s**2
def my_rectange(b,h):
return b*h/2
choice = int(input("enter 1. Area of circle \n 2. Area of square \n 3. Area of rectangle \n 0. To exit"))
if choice==1:
var = eval(input("What is r? "))
print ("Area of Circle is : ",my_circle(var))
elif choice==2:
var1 = eval(input("What is s? "))
print ("Area of Square is : ",my_square(var1))
elif choice==3:
var2 = eval(input("What is b? "))
var3 = eval(input("What is h? "))
print ("Area of rectangle is : ",my_rectange(var2,var3))
elif choice ==0:
exit()
else:
print ("We need Tea")
|
2c2b4f56fc3f3c0c76ba69866da852edcfbf8186 | Anshikaverma24/to-do-app | /to do app/app.py | 1,500 | 4.125 | 4 | print(" -📋YOU HAVE TO DO✅- ")
options=["edit - add" , "delete"]
tasks_for_today=input("enter the asks you want to do today - ")
to_do=[]
to_do.append(tasks_for_today)
print("would you like to do modifications with your tasks? ")
edit=input("say yes if you would like edit your tasks - ")
if edit=="yes":
add=input("say yes if you would like add some more tasks - ")
if add=="yes":
added=input("enter the task you would like to add - ")
to_do.append(added)
delete=input('say yes if you would like delete your tasks - ')
for i in range(len(to_do)):
print(to_do[i])
if delete=="yes":
delte=input("enter the task you want to delete - ")
to_do.remove(delte)
for i in range(len(to_do)):
print(to_do[i])
print("NUMBER OF TASKS YOU HAVE TO DO TODAY")
i=0
tasks=0
while i<len(to_do):
tasks=tasks+1
i+=1
print(tasks)
done_tasks=int(input("enter the total number of tasks that you have completed : "))
in_progress=int(input("enter the number of tasks which are in progress : "))
not_done=int(input("enter the number of tasks which you haven't done : "))
status=[done_tasks , in_progress , not_done]
i=0
sum=0
while i<len(status):
sum=sum+status[i]
print(sum)
i+=1
if sum>len(to_do):
print("your tasks is more than total number of tasks, please check the tasks once")
elif sum<len(to_do):
print("your tasks is less than the total number of tasks,please check the tasks once")
else:
print("your schedule have been set")
|
55d8b0d431c7202c7afe1181d87501fa8291ec7c | prometeyqwe/leetcode_problems | /easy/Remove Duplicates from Sorted Array/main.py | 645 | 3.796875 | 4 | """
Given a sorted array nums, remove the duplicates in-place such that each element
appear only once and return the new length. Do not allocate extra space for
another array, you must do this by modifying the input array in-place with O(1)
extra memory
"""
class Solution:
def removeDuplicates(self, nums):
i = 1
while i < len(nums):
if nums[i] == nums[i - 1]:
nums.pop(i)
else:
i += 1
return len(nums)
if __name__ == '__main__':
s1 = Solution()
print(s1.removeDuplicates([1, 1, 2]))
print(s1.removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))
|
0345861b092d7030b58df46955ff2900b89f470b | Zmolik/smart_calculator | /calculator.py | 9,735 | 4.09375 | 4 | from string import ascii_letters, digits
from collections import deque
stack = deque()
main_postfix = deque()
dic = {}
def is_of_letters_only(string):
"""returns True if the input string consists only of ascii_letters"""
for char in string:
if char not in ascii_letters:
return False
return True
def is_of_digits_only(string):
"""returns True if the input string consists only of digits"""
for char in string:
if char not in digits:
return False
return True
def is_of_digits_and_one_plusminus(string):
"""returns True if string consists od digits and one operator plus or minus"""
for char in string:
if char in digits or char in ('+', '-'):
continue
else:
return False
if string.count('+') == 1 and string.startswith('+'):
return True
elif string.count('-') == 1 and string.startswith('-'):
return True
else:
return False
def is_digits_or_letters_only(string):
"""returns True if the strin input consists only of digits or only of ascii_letters"""
if is_of_letters_only(string) and not is_of_digits_only(string):
return True
elif not is_of_letters_only(string) and is_of_digits_only(string):
return True
return False
def find_var_in_dict(dic, key):
"""returns value from dictionary if key exits, if not returns False"""
try:
return dic[key]
except KeyError:
return False
def peek_at_top(stack):
"""returns top value of stack, but doesn't change the stack"""
try:
top = stack.pop()
except IndexError:
return False
stack.append(top)
return top
def stack_operator_is_lower(new_operator, stack_operator):
"""returns True if stack operator has lower precendence"""
if stack_operator in {'+', '-'} and new_operator in {'/', '*'}:
return True
else:
return False
def change_between_stack_postfix(stack, postfix, exp):
"""subpart of conversion from infix to postfix notation when stack operator has higher or even precendence"""
postfix.append(stack.pop())
while True:
if not stack or peek_at_top(stack) == '(':
stack.append(exp)
break
top = stack.pop()
if stack_operator_is_lower(exp, top):
stack.append(top)
stack.append(exp)
break
else:
postfix.append(top)
def from_string_to_list(string):
"""Converts the expression given by user from string into list.
Takes into consideration number or variable of multiple elements e.g number(896), variable('distance')"""
number = ''
variable = ''
lis = []
for char in string:
if char in ('*', '/', '+', '-', '(', ')', ' '):
if number:
lis.append(number)
number = ''
elif variable:
lis.append(variable)
variable = ''
if char == ' ':
continue
else:
lis.append(char)
elif char in digits:
number += char
elif char in ascii_letters:
variable += char
else:
if char == ' ':
continue
elif char == '*' or char == '/':
lis.append()
elif char == '(' or char == ')':
pass
if number:
lis.append(number)
elif variable:
lis.append(variable)
return lis
def check_for_invalid(string):
"""Checks for the most common typos in user input"""
if string.count('(') != string.count(')'):
return False
if string.count('**') or string.count('//') or string.count('/*') or string.count('*/'):
return False
if string.count('+*') or string.count('*+') or string.count('+/') or string.count('/+'):
return False
if string.count('-*') or string.count('*-') or string.count('-/') or string.count('/-'):
return False
return True
def reduce_plus_minus(string):
"""The user can input multiple neighbouring pluses/minuses. This function converts these signs to one."""
while string.count('++'):
string = string.replace('++', '+')
while string.count('--'):
string = string.replace('--', '+')
while string.count('+-'):
string = string.replace('+-', '-')
while string.count('-+'):
string = string.replace('-+', '-')
return string
def infix_to_postfix(lis):
"""Input: list()
Output: deque()
Converts infix to postfix notation."""
stack = deque()
postfix = deque()
for exp in lis:
if is_of_digits_only(exp) or is_of_letters_only(exp):
postfix.append(exp)
elif not stack or peek_at_top(stack) == '(':
stack.append(exp)
elif exp == '(':
stack.append(exp)
elif exp == ')':
while peek_at_top(stack) != '(':
postfix.append(stack.pop())
stack.pop()
else:
top = peek_at_top(stack)
if exp == '*':
if stack_operator_is_lower(exp, top):
stack.append(exp)
else:
change_between_stack_postfix(stack, postfix, exp)
elif exp == '/':
if stack_operator_is_lower(exp, top):
stack.append(exp)
else:
change_between_stack_postfix(stack, postfix, exp)
elif exp == '+' or exp == '-':
change_between_stack_postfix(stack, postfix, exp)
while stack:
postfix.append(stack.pop())
return postfix
def postfix_to_result(postfix, dic):
"""Input: deque(), dic()
Output: int
Calculates result out of the expression in postfix notation."""
stack = deque()
while postfix:
bottom = postfix.popleft()
if bottom[0] in digits:
stack.append(bottom)
elif bottom[0] in ascii_letters:
value = find_var_in_dict(dic, bottom)
stack.append(value)
else:
n2 = stack.pop()
n1 = stack.pop()
if bottom[0] == '+':
result = int(n1) + int(n2)
elif bottom[0] == '-':
result = int(n1) - int(n2)
elif bottom[0] == '*':
result = int(n1) * int(n2)
else:
result = int(n1) / int(n2)
stack.append(result)
return result
# MAIN LOOP, quit the program by entering '/exit'
while True:
user_input = input().strip()
if not user_input:
pass
# controls command input
elif user_input.startswith('/'):
if user_input == '/exit':
print('Bye!')
break
elif user_input == '/help':
print('Smart calculator build as part of hyperskill project: https://hyperskill.org/projects/74')
print('1)You can use following operators: "+", "-", "*", "/", "(", ")"\n2)You can assign values e.g. a = 5')
print('3)You can calculate with these values e.g. a + 5\nWrite /exit to quit the program')
else:
print('Unknown command')
# controls assignment input
elif '=' in user_input:
if user_input.count('=') == 1:
action = user_input.split('=')
identifier = action[0].strip()
assignment = action[1].strip()
if is_of_letters_only(identifier):
if is_digits_or_letters_only(assignment):
if is_of_letters_only(assignment):
value = find_var_in_dict(dic, assignment)
if value:
dic[identifier] = value
else:
print('Unknown variable')
else:
dic[identifier] = assignment
else:
print('Invalid assignment')
else:
print('Invalid identifier')
else:
print('Invalid assignment')
# next 4 elif statements control the correctness of one variable/number input
# if user inputs one variable or number the program will print it
elif is_of_digits_only(user_input):
print(user_input)
elif is_of_digits_and_one_plusminus(user_input):
print(user_input)
elif is_of_letters_only(user_input):
value = find_var_in_dict(dic, user_input)
if value:
print(value)
else:
print('Unknown variable')
elif user_input.endswith('-') or user_input.endswith('+') or user_input.endswith('*') or user_input.endswith('/'):
print('Invalid expression')
else:
# the expressions that got here are not: commands, assignments, single variable or number
# 1. check for invalid input
# 2. reduce number of neighbouring pluses/minuses to one
# 3. convert the modified string to list
# 4. convert from infix(list) to postfix(deque)
# 5. calculate and print the result
if not check_for_invalid(user_input):
print('Invalid expression')
continue
modified_input_as_list = from_string_to_list(reduce_plus_minus(user_input))
main_postfix = infix_to_postfix(modified_input_as_list)
main_result = postfix_to_result(main_postfix, dic)
print(main_result) |
1ee3b5d9b5c4fe2e769c6b4920cdefd9f8a71e9d | cpscofield/Tools | /src/main/python/rosalind/utils.py | 1,586 | 3.859375 | 4 | """
A class to hold a bunch of simple, commonly-used utility functions.
"""
class Utils(object):
def __init__(self):
pass
def revcomp( self, seq ):
"""
Produce a reverse complement of the sequence.
"""
if 'U' in seq and not 'T' in seq:
return self.reverse( self.complement_rna( seq ) )
elif 'T' in seq and not 'U' in seq:
return self.reverse( self.complement_dna( seq ) )
def complement_dna( self, dna ):
"""
Produce a complement of the DNA sequence.
"""
comp = ''
for i in range(len(dna)):
if dna[i] == 'T': comp += 'A'
elif dna[i] == 'A': comp += 'T'
elif dna[i] == 'C': comp += 'G'
elif dna[i] == 'G': comp += 'C'
return comp
def complement_rna( self, rna ):
"""
Produce a complement of the RNA sequence.
"""
comp = ''
for i in range(len(rna)):
if rna[i] == 'U': comp += 'A'
elif rna[i] == 'A': comp += 'U'
elif rna[i] == 'C': comp += 'G'
elif rna[i] == 'G': comp += 'C'
return comp
def list2string( self, l, sep=' ' ):
"""
Convert a list to a string.
"""
s = ''
for i in range(len(l)):
if i>0: s += sep
s += str(l[i])
return s
def reverse( self, seq ):
"""
Produce a reversal of the sequence.
"""
return seq[::-1]
|
ebcda70f8266e9795efc8713b4f93de03aeea94a | cpscofield/Tools | /src/main/python/rosalind/mrna.py | 1,477 | 3.640625 | 4 | """
Solution to Rosalind challenge "MRNA: Inferring mRNA from Protein"
See http://rosalind.info/problems/mrna for details.
Attention ROSALIND competitor: if you have not solved this particular
problem yet, it would be unfair to all the other competitoris if you
peruse this code, so please refrain from doing so.
Given:
A protein string of length at most 1000 aa.
Return:
The total number of different RNA strings from which
the protein could have been translated, modulo 1,000,000.
(Don't neglect the importance of the stop codon in protein translation.)
Author:
Cary Scofield
carys689 <at> gmail <dot> com
"""
from rna_codon_table import RNA_codon_table
def get_sequence( f ):
"""
Get amino acid sequence from text file f.
"""
sequence = ''
line = f.readline().rstrip()
while line:
sequence += line
line = f.readline().rstrip()
return sequence
def execute():
datafile = open( "rosalind_mrna.txt", "r")
sequence = get_sequence( datafile )
datafile.close()
aa_table = RNA_codon_table()
print( sequence )
tallies = aa_table.get_tallies()
print(tallies)
p = 1
for s in sequence:
try:
p *= tallies[s]
except KeyError:
print( "Unable to find amino acid " + s + " in tally table" )
print( ( p * tallies['-'] ) % 1000000 )
if __name__ == '__main__':
execute()
|
4a310956f38a49ab7976cc8e01455acbec07ef45 | kprashant94/Codes | /BinaryTree/bst_predeccessor.py | 1,267 | 3.828125 | 4 |
########################################################################
# Title: Binary Search Tree
# Algrithm: Predeccessor
# Project: codewarm.in
#
# Description:
# To find the prdecessor of the key k:
# 1. Fnd the node storing key k, let it be x.
# 2. If the x has left subtree then the node having maximum element
# in the left subtree is the predecessor of the node x.
# 3. If left subtree of the node x is empty, then the lowest ancestor
# of the node x, say node y, such that x lies in the right subtree
# of the node y, is the predecessor of node x.
# Time complexity : O(logn))
#
########################################################################
class Node:
def __init__(self,key,left=None,right=None,parent=None):
self.key = key
self.left = left
self.right = right
self.parent = parent
class BinarySearchTree:
def __init__(self):
self.root = None
def predecessor(self,key):
temp = self._predecessor(self._search(self.root,key))
if temp:
return temp.key
else:
return None
def _predecessor(self,node):
if node:
if node.left:
return self._max(node.left)
temp = node.parent
while temp != None and node == temp.left:
node = temp
temp = temp.parent
return temp
else:
return None
|
c92f38897943131c0240bc6c9518edee6a070240 | kprashant94/Codes | /Stack/stack_push.py | 502 | 3.859375 | 4 |
#####################################################################
# Title: Stacks
# Algorithm: push
# Project: codewarm.in
#
# Description:
# In the this code the method 'push' takes the 'stack' and the key
# (to be inserted in stack) as its aruguments and inserts it at the
# top of the stack by appending the key in the list.
#
#####################################################################
class Stack:
def __init__(self):
self.S = []
def push(self, a):
self.S.append(a)
|
951e3d89f407b49534dc9e4ca9bd8e0617520c6f | kprashant94/Codes | /Heaps/MaxPriorityQueue/mpq_insert.py | 640 | 4.09375 | 4 |
##################################################################
# Title: Max Heaps
# Sub-Title: Max Priority Queue
# Algorithm: Insert
#
# Description:
# max_heap_insert(S,x) method inserts key x in the set S.
# time complexity : O()
#
##################################################################
class MaxPriorityQueue:
def __init__(self):
self.heap = []
def parent(self,i):
return i/2
def left(self,i):
return 2*i
def right(self,i):
return 2*i+1
def heap_size(self):
return len(self.heap)
def max_heap_insert(self,key):
self.heap.append(-9999999999)
self.heap_increase_key(self.heap_size()-1,key)
|
5b756d1d82866109e23334c7c7c2ae6d52d96187 | kprashant94/Codes | /Queue/queue_isempty.py | 461 | 3.75 | 4 |
#####################################################################
# Title: Queue
# Algorithm: isEmpty
# Project: codewarm.in
#
# Description:
# In the this code the method 'isEmpty' takes the 'queue' as its
# arugument and returns 'True' if 'queue' is empty else returns
# 'False'.
#
#####################################################################
class Queue:
def __init__(self):
self.Q = []
def isEmpty(self):
return self.Q == []
|
8fd287d71484bf0365d14ac9fccdd0e9a023e2af | kprashant94/Codes | /Stack/stack_top.py | 492 | 3.84375 | 4 | #####################################################################
# Title: Stacks
# Algorithm: top element
# Project: codewarm.in
#
# Description:
# In the this code the method 'top' takes the 'stack' as its arugument
# and returns the top element of the stack.
#
#####################################################################
class Stack:
def __init__(self):
self.S = []
def top(self):
if (self.S != []):
return self.S[len(self.S)-1]
else:
print 'Stack is empty' |
fc73c7c52dcbe9e85c5639d7a40fe7453bb69a8e | kprashant94/Codes | /Fibonacci/fib_rec.py | 223 | 3.546875 | 4 |
def fib_rec(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fib_rec(n-1)+fib_rec(n-2)
print fib_rec(0)
print fib_rec(1)
print fib_rec(2)
print fib_rec(3)
print fib_rec(4)
print fib_rec(5)
print fib_rec(30) |
6fd57771b4a4fdbd130e6d408cd84e02f89f48a4 | Jayasuriya007/Sum-of-three-Digits | /addition.py | 264 | 4.25 | 4 | print ("Program To Find Sum of Three Digits")
def addition (a,b,c):
result=(a+b+c)
return result
a= int(input("Enter num one: "))
b= int(input("Enter num one: "))
c= int(input("Enter num one: "))
add_result= addition(a,b,c)
print(add_result)
|
2da2d69eb8580ba378fac6dd9eff065e2112c778 | sk24085/Interview-Questions | /easy/maximum-subarray.py | 898 | 4.15625 | 4 | '''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
'''
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
# sliding window
len_nums = len(nums)
if len_nums == 1:
return nums[0]
cur_sum, max_so_far, i, j = 0, -99999999, 0, 1
while(i<len_nums):
cur_sum += nums[i]
if cur_sum > max_so_far:
max_so_far = cur_sum
if cur_sum <= 0:
cur_sum = 0
i += 1
return max_so_far |
daa21099590ab6c4817de8135937e9872d2eb816 | sk24085/Interview-Questions | /easy/detect-capital.py | 1,464 | 4.34375 | 4 | '''
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Given a string word, return true if the usage of capitals in it is right.
Example 1:
Input: word = "USA"
Output: true
Example 2:
Input: word = "FlaG"
Output: false
'''
class Solution:
def allUpper(self,str):
for char in str:
ascii_code = ord(char)
if ascii_code <65 or ascii_code >90:
return False
print('returning true')
return True
def allLower(self,str):
for char in str:
ascii_code = ord(char)
if ascii_code <97 or ascii_code >122:
return False
return True
def detectCapitalUse(self, word: str) -> bool:
# case when only one letter exists
if len(word) == 1:
return True
# get the first capital letter
firstCapital = word[0].isupper()
# get the second caspital letter
secondCapital = word[1].isupper()
# conditions
if firstCapital and secondCapital:
# all others should be upper
return self.allUpper(word[1:])
elif firstCapital:
return self.allLower(word[1:])
else:
return self.allLower(word[1:]) |
9ad73537eaff31b96e6b5cb98718c578e93555c7 | shimulhawladar/python3 | /hangManGame.py | 1,253 | 3.90625 | 4 | from getpass import getpass
print("Welcome to Hang Man Game!")
word = ""
while word == "": word = getpass("Guess a word: ").lower()
word = list(word); word_pop = word.copy()
targeted = []
hint = input("later you want thow show : ").lower()
if hint != "":
for w in word:
if hint[0] == w: targeted.append(hint[0]); word_pop.remove(hint[0])
else: targeted.append("_")
else:
print("No Hint")
targeted = list("-"*len(word))
print(" ".join(targeted))
sign = list("HangMan")
gameStaatus = ""
while len(sign) > 0 and gameStaatus != "HangMan" and word_pop != []:
try:
char = input("Guess char : ").lower()[0]
if word.count(char) == 1:
i = word.index(char) ; targeted[i] = char; word_pop.remove(char)
print(" ".join(targeted))
elif word.count(char) > 1:
for w in enumerate(word):
if w[1] == char: targeted[w[0]] = char ; word_pop.remove(char)
print(" ".join(targeted))
else:
print("Wrong!")
gameStaatus += sign.pop(0)
print(gameStaatus)
except:
print("Try Again")
if gameStaatus == "HangMan":
print(f"Loser..!! {''.join(word).upper()}")
else:
print("*** Winner ***")
|
7791b08606ad91a802309940263da56784d67efd | Hyacinth-OR/415Project2 | /Project2.py | 1,951 | 3.53125 | 4 | def karatsuba_mult2(x,y):
if x < 10 or y < 10:
return x * y
else:
# Calculate the number of digits of the numbers
sx, sy = str(x), str(y)
m2 = max(len(sx), len(sy)) // 2
# Split the digit sequences about the middle
ix = len(sx) - m2
iy = len(sy) - m2
a, b = int(sx[:ix]), int(sx[ix:])
c, d = int(sy[:iy]), int(sy[iy:])
# 3 products of numbers with half the size
c0 = karatsuba_mult2(a, c)
c2 = karatsuba_mult2(b, d)
c1 = karatsuba_mult2(a + b, c + d) - c0 - c2
return c0 * 10 ** (2 * m2) + (c1 * 10 ** m2) + c2
def karatsuba_mult(x, y):
if len(str(x)) == 1 or len(str(y)) == 1:
return x * y
else:
n = max(len(str(x)), len(str(y)))
nby2 = n // 2
a = x // 10 ** nby2
b = x % 10 ** nby2
c = y // 10 ** nby2
d = y % 10 ** nby2
ac = karatsuba_mult(a, c)
bd = karatsuba_mult(b, d)
ad_plus_bc = karatsuba_mult(a + b, c + d) - ac - bd
prod = ac * 10 ** (2 * nby2) + (ad_plus_bc * 10 ** nby2) + bd
return prod
def exponentiation(a,n):
if n == 0:
return 1
elif n % 2 == 0:
temp = exponentiation(a,n//2)
return karatsuba_mult(temp,temp)
else:
temp = exponentiation(a, (n - 1) // 2)
print("doing",temp,"and",a)
return karatsuba_mult2(karatsuba_mult2(temp,temp),a)
def main():
task = input("Select task:\n1. Karatsuba Multiplication.\n2. Exponentiation Utilizing Karatsuba Multiplication.")
if task == "2":
x = int(input("Input A:"))
y = int(input("Input N:"))
sol = exponentiation(x, y)
print(x, "**", y, "=", sol)
else:
x = int(input("Input X:"))
y = int(input("Input Y:"))
sol = karatsuba_mult2(x, y)
print(x, "*", y, "=", sol)
main() |
ed64a53350a9bf30fe5e7f9dca79d2f23611ec44 | saurabhshrivastava/expression | /parser.py | 3,220 | 3.6875 | 4 |
# stmt = [ expr ]
# expr = expr OR term | term
# term = term AND factor | factor
# factor = NOT factor | atom
# atom = ( expr ) | NUM
# stmt = [ expr ]
# expr = term expr_
# expr_ = OR term expr_ | eps
# term = factor term_
# term_ = AND factor term_ | eps
# factor = NOT factor | atom
# atom = ( expr ) | NUM
input = None
lookahead = None
line = 10
def eat () :
global lookahead
global input
if len (input) :
lookahead = input.pop(0)
else :
lookahead = None
def stmt () :
global lookahead
if lookahead == '[' :
eat ()
e = expr ()
if lookahead == ']' :
eat ()
return e
else :
print "parse error, ']' expected"
else :
print "parse error, unexpected token"
def expr () :
l = term ()
n = expr_ (l)
return n
def expr_ (l) :
global lookahead
if lookahead == 'OR' :
eat ()
r = term ()
l2 = ('OR', l, r)
n = expr_ (l2)
return n
else :
return l
def term () :
l = factor ()
n = term_ (l)
return n
def term_ (l) :
global lookahead
if lookahead == 'AND' :
eat ()
r = factor ()
l2 = ('AND', l, r)
n = term_ (l2)
return n
else :
return l
def factor () :
global lookahead
if lookahead == 'NOT' :
eat ()
f = factor ()
return ('NOT', f, None)
else :
f = atom ()
return f
def atom () :
global lookahead
if lookahead == '(' :
eat ()
a = expr ()
if lookahead == ')' :
eat ()
return a
else :
print "parse error, ')' expected"
elif isinstance (lookahead, int) == True :
a = lookahead
eat ()
return ('NUM', a, None)
else :
print "parse error, unexpected token"
def code (e, true_line, false_line) :
global line
type = e[0]
left = e[1]
right = e[2]
if type == 'NOT' :
left_line = code (left, false_line, true_line)
my_line = left_line
elif type == 'OR' :
right_line = code (right, true_line, false_line)
left_line = code (left, true_line, right_line)
my_line = left_line
elif type == 'AND' :
right_line = code (right, true_line, false_line)
left_line = code (left, right_line, false_line)
my_line = left_line
elif type == 'NUM' :
line += 10
my_line = line
print "%d %s T %d F %d" % (my_line, left, true_line, false_line)
else :
print "bad code"
return my_line
def main () :
global input
input = ['[', '(', '(', '(', 10, 'AND', 20, ')', 'AND', 30, ')', 'AND', '(', 40, 'OR', 50, ')',')', 'OR', '(', 60, 'AND', 70, ')', ']' ]
# input = ['[', 'NOT', '(', 123, 'OR', 234, ')', 'AND', 456, 'AND', 'NOT', 890, 'OR', 777, ']']
# input = ['[', '(', 123, 'OR', 234, ')', 'AND', 456, 'AND', 890, 'OR', 777, ']']
print input
eat ()
s = stmt ()
if lookahead != None :
print "junk at the end, starting %s" % lookahead
print s
st = code (s, 1000, 2000)
print "start %d" % st
if __name__ == "__main__":
main()
|
63509453c08fd578d146b270a3b32a02285544fb | BagiJ/Algorithms | /vezba05/bst.py | 4,530 | 4.34375 | 4 | class Node:
"""
Tree node: left child, right child and data
"""
def __init__(self, p = None, l = None, r = None, d = None):
"""
Node constructor
@param A node data object
"""
self.parent = p
self.left = l
self.right = r
self.data = d
class Data:
"""
Tree data: Any object which is used as a tree node data
"""
def __init__(self, key, val1):
"""
Data constructor
@param A list of values assigned to object's attributes
@param key / value
"""
self.key = key
self.a1 = val1
def MakeTNode(p, node1, node2):
node1.parent = p
node2.parent = p
if node1.data.key > p.data.key:
p.right = node1
else:
p.left = node1
if node2.data.key > p.data.key:
p.right = node2
else:
p.left = node2
def printTNode(node):
print("Current node:\t", node.data.key, \
"\nParent node:\t", node.parent.data.key if(node.parent is not None) else "No parent node" \
"\nLeft child:\t", node.left.data.key if(node.left is not None) else "No left node", \
"\nRight child:\t", node.right.data.key if(node.right is not None) else "No right child" )
class TBST:
"""
@param The root of the tree and the size
"""
def __init__(self, r = None, s = None):
self.root = r
self.size = s
def tree_insert(T, z):
y = None
x = T.root
while x is not None:
y = x
if z.data.key < x.data.key:
x = x.left
else:
x = x.right
z.parent = y
if y is None:
T.root = z
elif z.data.key < y.data.key:
y.left = z
else:
y.right = z
def transplant(T, u, v):
if u.parent is None:
T.root = v
elif u is u.parent.left:
u.parent.left = v
else:
u.parent.right = v
if v is not None:
v.parent = u.parent
def tree_delete(T, z):
if z.left is None:
transplant(T, z, z.right)
elif z.right is None:
transplant(T, z, z.left)
else:
y = tree_minimum(z.right)
if y.parent is not z:
transplant(T, y, y.right)
y.right = z.right
y.right.parent = y
transplant(T, z, y)
y.left = z.left
y.left.parent = y
def tree_minimum(x):
while x.left is not None:
x = x.left
return x
def inorder_tree_walk(x):
if x is not None:
inorder_tree_walk(x.left)
print(x.data.key)
inorder_tree_walk(x.right)
def tree_search(x, k):
if x is None or k == x.data.key:
return x
if k < x.data.key:
return tree_search(x.left, k)
else:
return tree_search(x.right, k)
def tree_max(x):
while x.right is not None:
x = x.right
return x
def tree_successor(x):
if x.right is not None:
return tree_successor(x.right)
y = x.parent
while (y is not None) and (x is y.right):
x = y
y = y.parent
return y
def iterative_tree_search(x, k):
while (x is not None) and (k is not x.data.key):
if k < x.data.key:
x = x.left
else:
x = x.right
return x
if __name__ == "__main__":
d1 = Data(1, 2)
d2 = Data(4, 11)
d3 = Data(6, 23)
d4 = Data(11, 6)
print("Key values: ", d1.key, d2.key, d3.key, d4.key , "\n")
#print(d.a1, d.a2)
n4 = Node(None, None, None, d4)
n3 = Node(None, None, None, d3)
n2 = Node(None, None, None, d1)
n1 = Node(None, None, None, d2)
# MakeTNode(n1, n2, n3)
T = TBST()
#inserting nodes in tree
tree_insert(T, n1)
tree_insert(T, n2)
tree_insert(T, n3)
tree_insert(T, n4)
tree_insert(T, Node(None, None, None, Data(0, 2)))
tree_insert(T, Node(None, None, None, Data(5, 11)))
tree_insert(T, Node(None, None, None, Data(7, 23)))
tree_insert(T, Node(None, None, None, Data(12, 6)))
# printTNode(n1)
inorder_tree_walk(T.root)
# tree_delete(T, n2)
print("\n")
inorder_tree_walk(T.root)
index = tree_search(T.root, 4)
# print("The key is: ", index.data.a1)
# printTNode(n1)
print("Tree max: ", tree_max(T.root).data.key)
print("Tree min: ", tree_minimum(T.root).data.key)
#findSuccessor = n2
#print("Successor of ", findSuccessor.data.key , " is : ", tree_successor(findSuccessor).data.key if(tree_successor(findSuccessor) is not None) else "No successor" )
|
86d1aabf783754c982baf6e08ca50fb6304f48ee | ryrimnd/basic-python-d | /b-list.py | 199 | 3.53125 | 4 | wishlist = ["Microphone", "Monitor", "Camera", "Camera Lens"]
#print(wishlist)
#print(wishlist[1])
#print(wishlist[0][2])
wishlist.append("Keyboard")
print(wishlist)
for x in wishlist:
print(x) |
997899682fd6b3da055864d1e339640e4d049f67 | 0xti4n/holbertonschool-higher_level_programming | /0x0A-python-inheritance/101-add_attribute.py | 273 | 3.921875 | 4 | #!/usr/bin/python3
""" function that adds a new attribute
to an object if it’s possible
"""
def add_attribute(self, name, new):
"""adds a new attribute to an object"""
try:
self.name = new
except:
raise TypeError('can\'t add new attribute')
|
88b9801928aff74686aebd58e31776f2e063d6eb | SkqLiao/Project-Euler | /code/51-100/65.py | 237 | 3.515625 | 4 | if __name__ == '__main__':
f = [2]
for i in range(33):
f += [1, 2 * i + 2, 1]
up, down = 1, 1
for i in range(len(f) - 2, -1, -1):
newup = up + down * f[i]
up = down
down = newup
print(sum(map(int, list(str(down))))) |
ddc0722d92fdb0e09b77a943ef9c2ff4f1614f18 | timsamson/Python-Challange | /PyBank/Main.Py | 1,778 | 3.71875 | 4 | #import Modules
import os
import csv
#Define Variables
month_count = 0
net_revenue = 0
profit = 0
max_rev = 0
min_rev = 0
monthly_change = 0
#create lists
dates = []
revenue = []
#location of resources
data_csv = os.path.join( "Resources", "budget_data.csv")
with open(data_csv) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
#Read headers
csv_header = next(csv_reader)
#Read First Row
firstrow = next(csv_reader)
month_count += 1
net_revenue += int(firstrow[1])
profit = int(firstrow[1])
#Create for loop to loop through data
for row in csv_reader:
#add date to list
dates.append(row[0])
#Add count for row to represent month
month_count += 1
# Calc Profit/loss and add to list
monthly_change = int(row[1]) - profit
revenue.append(monthly_change)
profit = (int(row[1]))
# Total Net Profit/Loss
net_revenue = net_revenue + int(row[1])
#Greatest Profit
max_rev = max(revenue)
max_index = revenue.index(max_rev)
max_date = dates[max_index]
#Greatest Loss
min_rev = min(revenue)
min_index = revenue.index(min_rev)
min_date = dates[min_index]
#Average Profti/Loss
avg_profit = sum(revenue)/len(revenue)
#Setup output strings
report= (
f"Financial Analysis\n"
f"---------------------------\n"
f"Total Months: {str(month_count)}\n"
f"Total Funds: ${str(net_revenue)}\n"
f"Average Change: ${str(round(avg_profit,2))}\n"
f"Greatest Increase in Profits: {max_date} (${str(max_rev)})\n"
f"Greatest Decrease in Profits: {min_date} (${str(min_rev)})\n"
)
print(report)
#Set output path
output_txt = os.path.join('output.txt')
#output file
with open(output_txt, 'w') as txtfile:
txtwriter = txtfile.write(report)
txtfile.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.