blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3b633fb9d6b644e254c2334ec53fd8dba8c68fef | daniel-reich/ubiquitous-fiesta | /oCe79PHB7yoqkbNYb_5.py | 168 | 3.546875 | 4 |
def break_point(num):
nums = [int(num) for num in str(num)]
for i in range(1, len(nums)):
if sum(nums[:i]) == sum(nums[i:]):
return True
return False
|
885c94edb21c3597df8e550d0f2bf29d97319336 | NisaSource/python-algorithm-and-data-structure | /dataStructure/BinaryHeap.py | 1,523 | 3.90625 | 4 | class Heap:
def __init__(self, sz):
self.list = (sz + 1) * [None]
self.heapSz = 0
self.maxSz = sz + 1
def heap_peek(root):
if not root:
return
else:
return root.list[1]
def heap_size(root):
if not root:
return
else:
return root.heapSz
def level_order_traversal(root):
if not root:
return
else:
for i in range(1, root.heapSz+1):
print(root.list[i])
def insert_heap_tree(root, idx, type):
parent_idx = int(idx/2)
if idx <= 1:
return
if type == "Min":
if root.list[idx] < root.list[parent_idx]:
temp = root.list[idx]
root.list[idx] = root.list[parent_idx]
root.list[parent_idx] = temp
insert_heap_tree(root, parent_idx, type)
elif type == "Max":
if root.list[idx] > root.list[parent_idx]:
temp = root.list[idx]
root.list[idx] = root.list[parent_idx]
root.list[parent_idx] = temp
insert_heap_tree(root, parent_idx, type)
def insert_node(root, val, type):
if root.heapSz + 1 == root.maxSz:
return "FULL"
root.list[root.heapSz + 1] = val
root.heapSz += 1
insert_heap_tree(root, root.heapSz, type)
return "SUCCESSFULLY INSERTED"
new_binary_heap = Heap(5)
insert_node(new_binary_heap, 6, "Max")
insert_node(new_binary_heap, 7, "Max")
insert_node(new_binary_heap, 5, "Max")
insert_node(new_binary_heap, 4, "Max")
level_order_traversal(new_binary_heap)
|
950c60c32ccbe5ca50191be5502c8ff9cbed992a | Dharanikanna/Python | /FIND FIRST AND LAST NUMBER IN A DIGIT.PY | 208 | 3.703125 | 4 | def fdigit(A):
while (A>=10):
A=A//10
print(A)
#--------------------
def ldigit(A):
A=A%10
print(A)
#--------------------
A=int(input())
count=0
fdigit(A)
ldigit(A)
|
c10ab96915c6b68e4cc3f139befbda31486f1a48 | luismvargasg/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 474 | 4.34375 | 4 | #!/usr/bin/python3
"""Module to read n lines text file"""
def read_lines(filename="", nb_lines=0):
"""function that reads n lines of a text file (UTF8)
and prints it to stdout.
Args:
filename: text file to read.
nb_lines:
"""
with open(filename) as myFile:
lines = myFile.readlines()
if nb_lines <= 0 or nb_lines >= len(lines):
nb_lines = len(lines)
for i in range(nb_lines):
print(lines[i], end="")
|
b2652bdd386f12d07d8d186299f1a9473e10fa8a | Brunocfelix/Exercicios_Guanabara_Python | /Desafio 011.py | 559 | 4.0625 | 4 | # Desafio 011: Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a
# quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m^2;
L = float(input('Digita a Largura da parede, em metros: '))
A = float(input('Digite a Altura da parede, em metros: '))
S = L * A
s1 = S / 2
print('Sua parede tem a dimensão de: {:.2f} x {:.2f}, e sua área é de: {:.2f}m²' .format(L, A, S))
print('Para pintar essa parede, a quantidade de tinta necessária será de: {:.2}l' .format(s1))
|
e5852f031ba1f1d5667a08f34eba59abd06e6545 | linoor/Euler | /Python/PentagonNumbers44.py | 1,117 | 3.78125 | 4 | import unittest
import math
import time
def isPentagonal(n):
return ((math.sqrt(24*n+1)+1) / 6).is_integer()
def pentagonal(n):
return (n*(3*n-1))/2
start_time = time.time()
i = 1
found = False
while not found:
second = pentagonal(i)
for j in range(i-1, 1, -1):
first = pentagonal(j)
if isPentagonal(second - first) and isPentagonal(first + second):
result = (first, second)
found = True
break
i += 1
print(result[1] - result[0])
print(time.time() - start_time)
class PentagonTests(unittest.TestCase):
def test_pentagon_test(self):
self.assertTrue(isPentagonal(1))
self.assertTrue(isPentagonal(5))
self.assertTrue(isPentagonal(12))
self.assertTrue(isPentagonal(22))
self.assertTrue(isPentagonal(35))
self.assertFalse(isPentagonal(0))
self.assertFalse(isPentagonal(2))
self.assertFalse(isPentagonal(3))
self.assertFalse(isPentagonal(7))
self.assertFalse(isPentagonal(118))
self.assertFalse(isPentagonal(9))
if __name__ == "__main__":
unittest.main()
|
280efdf97721da73b2234a5f66329b7d140b800f | mikiotada/LeeCode_exercises | /palindrome.py | 575 | 3.984375 | 4 | """
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
"""
def isPalindrome(s):
"""
0(n)
"""
store = []
s = s.lower()
for char in s:
if char.isalnum():
store.append(char)
if len(store) == 0:
return True
for i in range((len(store)//2)+1):
if store[i] != store[-i-1]:
return False
return True
def test_isPalindrome():
assert isPalindrome("race a car") == False
assert isPalindrome("") == True
test_isPalindrome()
|
38c2ff423aaaee904cb25efbc7c78bb2c3d2965f | finlayg/colloidsoncones | /checkoverlaps.py | 915 | 3.625 | 4 | #checks if any particles in coords file are overlapping
inputfile = input('Coords Input Filename: ')
from math import sqrt
#generating particle coordinate list
particlelist = []
with open(inputfile, 'r') as stream1:
for line in stream1:
values = line.split(' ')
splitline = line.rstrip().split(' ')
new = [item for item in splitline if item!='']
#print(new)
particlelist.append([float(new[0]),float(new[1]),float(new[2])])
#testing distances between particles in list
for p1index in range(0, len(particlelist)):
for p2index in range((p1index+1), len(particlelist)):
distance = sqrt((particlelist[p1index][0]-particlelist[p2index][0])**2 + (particlelist[p1index][1]-particlelist[p2index][1])**2 + (particlelist[p1index][2]-particlelist[p2index][2])**2)
#print(distance)
if distance < 2:
print("Warning: Overlap!")
|
f3c187d9234d48ebaa1b6607af5f1d82c083ef54 | TPALMER92/HWFin5350 | /main.py | 589 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 4 17:15:56 2017
@author: courtenaenielson
"""
from nuggets import is_nugget_number
def main():
small, medium, large = 6, 9, 20
count = 0
largest = small - 1
candidate = small
while count != small:
if(is_nugget_number(candidate)):
count += 1
else:
largest = candidate
count = 0
candidate += 1
print("The largest number of nuggets you cannot buy is: " + str(largest))
if __name__ == "__main__":
main()
|
373b8ca41aa840298d488649d5e545ad5b6a589f | FukurouMakoto/GBF-SparkCalculator | /SparkCalculator.py | 1,285 | 3.765625 | 4 | def totalDraws(crystals, tix, tenrolls):
totalDraws = ((int(tix)*300) + (int(tenrolls)*3000) + int(crystals)) / 300
return totalDraws
def how_many_rolls(total):
if total == 300:
return "You can spark a character!"
elif total > 300:
leftover = total - 300
return f"You can spark a character and have {str(int(leftover))} draws leftover to draw for whomever you want!"
elif total < 300:
untilCanSpark = 300 - int(total)
return f"Sorry, you need {str(int(untilCanSpark))} draws until you can spark a character..."
def sparkCalculator(crystals, tix, tenrolls):
return f"You can make a total of {str(int(totalDraws(crystals, tix, tenrolls)))} draws."
def test_for_negative(num):
if num < 0:
return True
else:
return False
def main():
print('Welcome to Spark Calculator')
crystals = input('How many crystals do you have? ')
tix = input('How many single roll tickets do you have? ')
tenrolls = input('Finally, how many 10 roll tickets do you have? ')
for item in [crystals, tix, tenrolls]:
if test_for_negative(int(item)):
print("Invalid input. Please don't use negative numbers.")
main()
total = totalDraws(crystals, tix, tenrolls)
print(sparkCalculator(crystals, tix, tenrolls))
print(how_many_rolls(total))
if __name__ == "__main__":
main()
|
5c720c9a9a2622590177f603a20c260c25f1f0a1 | WALL-EEEEEEE/interview | /design_pattern/singleton_1.py | 679 | 3.71875 | 4 | #
# Singleton
# Based by shared properties
#
#
#
class singleton(object):
_state = {}
def __new__(cls,*args, **kwargs):
ob = super(singleton,cls).__new__(cls,*args,**kwargs)
ob.__dict__ = cls._state
return ob
class MyClass(singleton):
name = "MyClass"
myclass = MyClass()
myclass.name = "myclass"
myclass1 = MyClass()
myclass1.name = "myclass1"
myclass2 = MyClass()
myclass2.name = "myclass2"
myclass3 = MyClass()
myclass3.name = "myclass3"
print(myclass1.name)
print(myclass2.name)
print(myclass3.name)
print("myclass1's id:"+str(id(myclass1)))
print("myclass2's id:"+str(id(myclass2)))
print("myclass3's id:"+str(id(myclass3)))
|
399a30313581f0067145e93c129e4e8ff38ed937 | fd-facu/termodinamica | /radiobutton.py | 1,141 | 3.5 | 4 | import sys
if sys.version_info[0] < 3:
import Tkinter as tk
import tkFont as tkfont
else:
import tkinter as tk
from tkinter import font as tkfont
def sel():
print("entro")
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = tk.Tk()
var = tk.IntVar()
label = tk.Label(root)
R1 = tk.Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = tk.W )
R2 = tk.Radiobutton(root, text="Option 2", variable=var, value=2,
command=sel)
R2.pack( anchor = tk.W )
R3 = tk.Radiobutton(root, text="Option 3", variable=var, value=3,
command=sel)
R3.pack( anchor = tk.W)
varb = tk.IntVar()
R1b = tk.Radiobutton(root, text="Option 1", variable=varb, value=1,
command=sel)
R1b.pack( anchor = tk.W )
R2b = tk.Radiobutton(root, text="Option 2", variable=varb, value=2,
command=sel())
R2b.pack( anchor = tk.W )
R3b = tk.Radiobutton(root, text="Option 3", variable=varb, value=3,
command=sel)
R3b.pack( anchor = tk.W)
label.pack()
root.mainloop() |
8e1ea7800a2275cc4a066878cf836ac54d07fe8d | IhsanE/Algorithms | /bfs.py | 336 | 3.640625 | 4 | G={"A":["B","C","D"],"B":["A","E","F"],"C":["A","F"],"D":["A"],"E":["B"],"F":["B","C"]}
def bfs(G,v):
node=0
parent={v:None}
q=[v]
for v in q:
for i in G[v]:
if i not in parent.values():
parent[i]=v
q.append(i)
return parent
print (bfs(G,"A"))
|
441f257c43d758a2b3b30a58126dd73c88b47219 | idanSoudry/pinkFloyd | /data.py | 7,205 | 3.890625 | 4 | import collections
import datetime
PATH = r"Pink_Floyd_DB.txt"
def dbase():
"""
This function organise the data base to a difficult build
:return: the difficult build
"""
albums_data = {}
song_dict = {}
songs_list = []
with open(PATH, 'r') as f:
data = f.read()
temp = data.split("#")
for album in temp[1:]:
index = album.find("::")
albums_data[album[:index]] = ""
for album in temp[1:]:
album = album.split("*")
album_name = album[0][:-7]
release_Date = album[0][-5:]
del album[0]
for song in album:
info = song.split("::")
song_name = info[0]
del info[0]
songs_list = info
song_dict[song_name] = songs_list
albums_data[album_name] = (song_dict.copy(), release_Date)
song_dict.clear()
return albums_data
def simple_songs_list(name_of_album):
"""
this func is from using insde the data file
:param name_of_album: the name of album
:return: the songs in this album
:rtype: str
"""
songs = []
data1 = dbase()
data1 = data1[name_of_album][0]
for song in data1.keys():
songs += [song]
return songs
def simple_album_list():
"""
this func is from using insde the data file
:return: list of all albums
:rtype: list
"""
album_list = []
data = dbase()
for album in data.keys():
album_list += [album]
return album_list
def album_list_for_user():
"""
this func makes a list of all the album
:return: list of all albums
:rtype: str
"""
answer = ""
data = dbase()
for album in data.keys():
answer += album + ", "
return answer[:-2]
def songs_list(name_of_album):
"""
This function makes a list of all the songs in album
:param name_of_album: the album
:return: all the songs in the album
:rtype: str
"""
songs = ""
data = dbase()
data = data[name_of_album][0]
for song in data.keys():
songs += song
songs += ", "
return songs[:-2]
def get_len(song, album):
"""
This func calc the number of words in one song
:param song: the song
:param album: in what album the song is
:return: the length
:rtype: str
"""
length = 0
words = dbase()[album][0][song]
words = words[2]
words = words.split()
for word in words:
length += 1
return str(length)
def song_length(ans):
"""
This func calc how many words there is in all of the songs, albums. using "get_len" function
:param ans: the answer from the user
:return: the length of all the songs
:rtype: str
"""
length = 0
flag = 1
albums = simple_album_list()
for album in albums:
songs = simple_songs_list(album)
for song in songs:
if ans == song:
words = dbase()[album][0][song]
words = words[2]
words = words.split()
for word in words:
length += 1
flag = 1
return str(length)
elif ans != song and flag == 0:
return "song not found!"
def song_lyrics(ans):
"""
This function returns the lyrics of specific song
:param ans: the answer from the user
:return: the lyrics of the song
:rtype: str
"""
albums = simple_album_list()
for album in albums:
songs = simple_songs_list(album)
for song in songs:
if ans == song:
words = dbase()[album][0][song]
words = words[2]
return words
def song_album(ans):
"""
This function finds what album the song in
:param ans: the song
:return: the album
:rtype: str
"""
albums = simple_album_list()
for album in albums:
songs = simple_songs_list(album)
for song in songs:
if ans == song:
return album
def song_by_word(ans):
"""
This func finds a song by a string from the user(by name)
:param ans: the string from the user
:return: list of the songs
:rtype: str
"""
songs_list = ""
ans = ans.lower()
albums = simple_album_list()
for album in albums:
songs = simple_songs_list(album)
for song in songs:
song = str(song)
if ans in song.lower():
songs_list += song + ", "
return songs_list[:-2]
def lyrics_by_word(ans):
"""
This func finds a song by a string from the user(by lyrics)
:param ans: the string from the user
:return: list of the songs
:rtype: str
"""
songs_list = ""
ans = ans.lower()
albums = simple_album_list()
for album in albums:
songs = simple_songs_list(album)
for song in songs:
x = song_lyrics(song)
song = str(song)
if ans in x:
songs_list += song + ", "
return songs_list[:-2]
def common():
"""
This function makes list of the top 50 commonest words of all songs
:return: the stats
:rtype: str
"""
full_song = ""
albums = simple_album_list()
for album in albums:
songs = simple_songs_list(album)
for song in songs:
full_song += str(song_lyrics(song))
split_lyrics = full_song.lower().split()
counter = collections.Counter(split_lyrics)
most_words = counter.most_common(50)
return most_words
def stats():
"""
This function makes list of the top 50 commonest words of all songs
:return: list with the sorted length values
:rtype: str
"""
times_lst = []
time_dict = {}
for album, details in dbase().items():
time_m = 0
time_s = 0
for songs, details_s in details[0].items():
time = details_s[1].split(":")
min = int(time[0])
sec = int(time[1])
time_m += min
time_s += sec
time_s = datetime.timedelta(seconds=time_s)
time_m = datetime.timedelta(seconds=time_m)
time = time_m + time_s
time = str(time)
times_lst.append(time)
time_dict[album] = time
time_dict = sorted(time_dict.items(), key=lambda x: x[1], reverse=True)
return time_dict
def organise(times, words):
"""
This function organise the two answer to one answers
:param times: list with the sorted length values
:param words: list of all of the commonest words of all songs
:return: one organise answer
:rtype: str
"""
length_lst = ""
comm_lst = ""
for item in times:
length_lst += str(item[0]) + " - " + str(item[1]) + "\n"
for item in words:
comm_lst += str(item[0]) + " - " + str(item[1]) + "\n"
return length_lst, comm_lst
|
146a2598d42742a1a86c662e42413e6a8a1b6021 | xintao0202/Gatech_Machine-Learning-for-Trading | /m3p3/mc2_p2/marketsim.py | 6,418 | 3.53125 | 4 | """MC2-P1: Market simulator."""
import pandas as pd
import numpy as np
import os
from util import get_data, plot_data
from portfolio.analysis import get_portfolio_value, get_portfolio_stats, plot_normalized_data
def compute_portvals(start_date, end_date, orders_file, start_val):
"""Compute daily portfolio value given a sequence of orders in a CSV file.
Parameters
----------
start_date: first date to track
end_date: last date to track
orders_file: CSV file to read orders from
start_val: total starting cash available
Returns
-------
portvals: portfolio value for each trading day from start_date to end_date (inclusive)
"""
# TODO: Your code here
df_orders = pd.read_csv(orders_file) # read csv file
df_orders = df_orders.sort(columns='Date') # sort orders by date
df_orders = df_orders.reset_index()
symbols = list(set(df_orders['Symbol'])) # get symbols in orders, remove duplicate
df_prices = get_data(symbols, pd.date_range(start_date, end_date)) # get prices of the symbols
df_prices = df_prices.drop('SPY', axis=1) # drop 'SPY'
index_trade = pd.date_range(start_date, end_date)
df_trade = pd.DataFrame(index=index_trade, columns=[symbols]) # construct a df_trade to record orders by date
df_trade = df_trade.fillna(0)
cash = start_val
df_position = np.cumsum(df_trade) # construct a df_position to record the stock holdings everyday
for order_no in range (0, len(df_orders)): # read each order
order = df_orders.ix[order_no, ] # read the current order
df_trade, df_position, cash = execute_order(order, df_prices, df_trade, df_position, cash)
# get the result of order execution (depending on leverage check)
df_stockValue = df_prices * df_position # construct a df_stockValue to record the value of stock holdings
df_stockValue = df_stockValue.dropna()
df_stockValue['Value'] = np.sum(df_stockValue, axis=1)
df_trade['OrderValue'] = np.sum(df_prices * df_trade, axis=1)
df_trade = df_trade.dropna(subset=['OrderValue'])
df_trade['Cash'] = 0
df_trade.ix[0, 'Cash'] = start_val - df_trade.ix[0, 'OrderValue']
# calculate cash remaining everyday
for row in range(1, len(df_trade)):
df_trade.ix[row, 'Cash'] = df_trade.ix[row-1, 'Cash'] - df_trade.ix[row, 'OrderValue']
df_trade['StockValue'] = df_stockValue['Value']
df_trade['Portvals'] = df_trade['Cash'] + df_trade['StockValue'] # calculate portfolio value everyday
portvals = df_trade[['Portvals']]
return portvals
def execute_order(order, df_prices, df_trade, df_position, cash):
df_trade_before = df_trade.copy() # store old df_trade
df_position_before = df_position.copy() # store old df_position
cash_before = cash # store old cash
date = order['Date']
symbol = order['Symbol']
current_leverage = get_leverage(date, df_trade, df_prices, cash) # get old leverage
# fill df_trade according to 'BUY' or 'SELL', calculate order value
if order['Order'] == 'BUY':
df_trade.ix[date, symbol] = df_trade.ix[date, symbol] + order['Shares']
order_value = np.sum(df_prices.ix[date, symbol] * order['Shares'])
if order['Order'] == 'SELL':
df_trade.ix[date, symbol] = df_trade.ix[date, symbol] + order['Shares'] * (-1)
order_value = np.sum(df_prices.ix[date, symbol] * order['Shares'] * (-1))
df_position = np.cumsum(df_trade) # calculate new df_position
cash = cash - order_value # calculate new cash amount
new_leverage = get_leverage(date, df_trade, df_prices, cash) # get new leverage
# check leverage, if safisfied, return new df_trade, df_position, cash; otherwise, return old ones
if new_leverage <= 2:
return df_trade, df_position, cash
elif new_leverage > 2 and new_leverage < current_leverage:
return df_trade, df_position, cash
else:
return df_trade_before, df_position_before, cash_before
def get_leverage(date, df_trade, df_prices, cash):
df_position = np.cumsum(df_trade)
stock_value = df_prices.ix[date, ] * df_position.ix[date, ] # calculate current stock values
# get sum of long position and short position
sum_long = np.sum(stock_value[stock_value>0])
sum_short = np.sum(stock_value[stock_value<0])
# get leverage
leverage = (sum_long + (-1)*sum_short) / ((sum_long - (-1)*sum_short) + cash)
return leverage
def test_run():
"""Driver function."""
# Define input parameters
start_date = '2007-12-31'
end_date = '2009-12-31'
orders_file = os.path.join("orders", "orders_test.csv")
start_val = 10000
# Process orders
portvals = compute_portvals(start_date, end_date, orders_file, start_val)
if isinstance(portvals, pd.DataFrame):
portvals = portvals[portvals.columns[0]] # if a DataFrame is returned select the first column to get a Series
# Get portfolio stats
cum_ret, avg_daily_ret, std_daily_ret, sharpe_ratio = get_portfolio_stats(portvals)
# Simulate a $SPX-only reference portfolio to get stats
prices_SPX = get_data(['$SPX'], pd.date_range(start_date, end_date))
prices_SPX = prices_SPX[['$SPX']] # remove SPY
portvals_SPX = get_portfolio_value(prices_SPX, [1.0])
cum_ret_SPX, avg_daily_ret_SPX, std_daily_ret_SPX, sharpe_ratio_SPX = get_portfolio_stats(portvals_SPX)
# Compare portfolio against $SPX
print "Data Range: {} to {}".format(start_date, end_date)
print
print "Sharpe Ratio of Fund: {}".format(sharpe_ratio)
print "Sharpe Ratio of $SPX: {}".format(sharpe_ratio_SPX)
print
print "Cumulative Return of Fund: {}".format(cum_ret)
print "Cumulative Return of $SPX: {}".format(cum_ret_SPX)
print
print "Standard Deviation of Fund: {}".format(std_daily_ret)
print "Standard Deviation of $SPX: {}".format(std_daily_ret_SPX)
print
print "Average Daily Return of Fund: {}".format(avg_daily_ret)
print "Average Daily Return of $SPX: {}".format(avg_daily_ret_SPX)
print
print "Final Portfolio Value: {}".format(portvals[-1])
# Plot computed daily portfolio value
df_temp = pd.concat([portvals, prices_SPX['$SPX']], keys=['Portfolio', '$SPX'], axis=1)
plot_normalized_data(df_temp, title="Daily portfolio value and $SPX")
if __name__ == "__main__":
test_run()
|
0f662d24569e16f7b59220235dd21e243733d2d7 | krivacic/homework1 | /example/algs.py | 2,499 | 4.25 | 4 | import numpy as np
import time
def pointless_sort(x):
"""
This function always returns the same values to show how testing
works, check out the `test/test_alg.py` file to see.
"""
return np.array([1,2,3])
def bubblesort(x):
"""
Describe how you are sorting `x`
"""
#Bubble sort for integers
#Pre-condition is in run file (only integers or floats)
#Outer loop: make as many passes through array as there are members
for i in range(len(x)):
#Inner for loop goes through the array and swaps adjacent items if they are out of order.
for j in range(len(x)-1):
# If adjacent items are out of order, swap them
if( x[j] > x[j+1] ):
t = x[j+1]
x[j+1] = x[j]
x[j] = t
return x
def quicksort(x):
"""
Describe how you are sorting `x`
"""
con = 0
asn = 0
# Quicksort input function to tell initial values of p and r. Initial pivot point is in the middle of the array.
def quicksortinput(x):
quicksort(x,0,len(x)-1)
# Recursive quicksort function, partitions the array and then quicksorts each partition.
def quicksort(x,p,r):
if p < r:
con = con + 1
pivot = partition(x,p,r)
asn = asn + 1
quicksort(x,p,pivot-1)
quicksort(x,pivot+1,r)
# Partition function: finds pivot value, defines the left value as the one directly above pivot value, and compares this to the right value.
def partition(x,p,r):
pivotval = x[p]
left = p + 1
right = r
# While left <= right:
while left <= right:
con = con + 1
#move left up until you reach a value that is less than the pivot value
while x[left] <= pivotval:
con = con + 1
left = left + 1
asn = asn + 1
#move right down until you reach a value that is greater than the pivot value
while x[right] > pivotval:
con = con + 1
right = right -1
asn = asn + 1
# swap left and right
if left < right:
con = con + 1
t = x[right]
x[right] = x[left]
x[left] = t
asn = asn + 3
# swap pivot value and right
t = x[p]
x[p] = x[right]
x[right] = t
asn = asn + 3
# return right for use as new pivot value
return right
return x
|
7ee3e769b37470bedfde91ebbbb9ccd8432bbc40 | SnehankaDhamale/Python-Assg-WFH- | /Assignment6/ex20.py | 172 | 4.25 | 4 | #Write a Python program to print all ASCII character with their values
for i in range(1,255): #ascii range is 1-254
ch=chr(i) #typecast int to char
print(i,"=>",ch) |
862e50bcd279acf307f269fbf79493ddd42e4bd7 | HenriquedaSilvaCardoso/Exercicios-CursoemVideo-Python | /Exercícios em Python/PythonExercícios/ex036.py | 472 | 3.640625 | 4 | vcasa = float(input('Qual o valor da casa a ser comprada? R$'))
sal = float(input('Qual o seu salário? R$'))
tem = (int(input('Em quantos anos você pretende pagar essa casa? ')))
par = vcasa/(tem*12)
print(f'Uma casa de R${vcasa:.2f} sendo paga em {tem} anos terá uma prestação de {prest:.2f}')
if prest > 0.3*sal:
print('\033[4;31mEmpréstimo negado, parcela excede 30% do salário')
else:
print('\033[4;32mEmpréstimo aprovado! Bem vindo a sua nova casa!')
|
61a89fea69950a42ce39ffcfd562f6b529dbde25 | strongliu110/offer | /51_InversePairs.py | 2,234 | 3.6875 | 4 | """
// 面试题51:数组中的逆序对
// 题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组
// 成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
"""
import copy
# 归并排序(分治)。时间O(nlogn),空间O(n)
def merge_sort(nums):
if len(nums) <= 1:
return nums
num = len(nums) // 2
left = merge_sort(nums[:num]) # 左边有序
right = merge_sort(nums[num:]) # 右边有序
return merge(left, right) # 再将二个有序数列合并
def merge(left, right):
l, r = 0, 0
result = []
while l < len(left) and r < len(right):
if left[l] < right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
result += left[l:]
result += right[r:]
return result
# 先把数组依次拆开,然后合并的时候统计逆序对数目,并排序
def inverse_pairs(nums):
if not nums:
return 0
start, end = 0, len(nums) - 1
tmp = copy.deepcopy(nums)
return inverse_pairs_core(tmp, start, end)
def inverse_pairs_core(nums, start, end):
if start == end: # 递归结束条件
return 0
length = (end - start) // 2
left = inverse_pairs_core(nums, start, start + length)
right = inverse_pairs_core(nums, start + length + 1, end)
# i 初始化为前半段最后一个数字的下标
i = start + length
# j 初始化为后半段最后一个数字的下标
j = end
# 本次逆序对数目
count = 0
t = []
while i >= start and j >= start + length + 1:
if nums[i] > nums[j]:
t.append(nums[i])
count += j - start - length
i -= 1
else:
t.append(nums[j])
j -= 1
while i >= start:
t.append(nums[i])
i -= 1
while j >= start + length + 1:
t.append(nums[j])
j -= 1
nums[start:end + 1] = t[::-1] # 倒序
return count + left + right
if __name__ == '__main__':
test = [7, 5, 6, 4, 8, 1, 2, 9]
print(inverse_pairs(test))
test2 = [1, 2, 3, 4, 5, 6, 7, 90, 21, 23, 45]
print(merge_sort(test2))
|
6ae0835e1381e2172d1e9548e01eb0257a95343b | nikhil2195/pythonprojects | /bubblesort/bubblesort.py | 457 | 4.1875 | 4 | def bubblesort(sortlist):
l=len(sortlist)
for i in range(l):
for j in range(i+1,l):
if sortlist[i]>sortlist[j]:
sortlist[i],sortlist[j]=sortlist[j],sortlist[i]
return sortlist
def main():
print("Enter the list cof numbers to be sorted.Keep a space between the numbers")
numbers=input()
sortlist=list(map(int, numbers.split()))
sortedlist=bubblesort(sortlist)
print(sortedlist)
main()
|
1211abc8d56ba0bca7a163f3c87990edeedf7eb4 | AndGasper/code_playground | /simple_line_chart_ch3.py | 399 | 3.78125 | 4 | from matplotlib import pyplot as plt
years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
# create a line chart, years on x-axis, gdp on y-axis
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
# title for plot
plt.title("Nominal GDP")
# Label for y-axis
plt.ylabel("Billions (USD)")
# display the chart
plt.show() |
adfeac03977dd1fbe1518655d4b8bb7504c84dfc | meoweeb/Pricing-Project | /pricetoolscript-fixing.py | 2,551 | 4.5625 | 5 | """
This tool is designed to take user input of cost and determine the range of
pricing needed to make a profit greater than their desired value.
"""
#shipping function - determines if we pay shipping and returns true or false
def ship_true(shipping_bool):
has_shipping = input("Do we pay shipping on this? Y/N? ")
if has_shipping == "Y" or has_shipping == "y":
shipping_bool = True
elif has_shipping == "N" or has_shipping == "n":
shipping_bool = False
else:
print("Please enter only Y or N. ")
ship_true(shipping_bool)
return shipping_bool
def round_to_5(round_this):
round_modulo = round_this % 5.
round_this = round_this + (5. - round_modulo)
return round_this
def installpricetool():
# ask user for cost
price_cost = float(input("What is our cost? $"))
our_cost = price_cost
shipping_yesno = True
shipping_yesno = ship_true(shipping_yesno)
if shipping_yesno == False:
shipping_cost = 0.
else:
shipping_cost = input("What is shipping cost? If unknown, type U. $")
if shipping_cost == "U" or shipping_cost == "u":
shipping_cost = 12.
print("Shipping cost default is $" + str(shipping_cost) + ".")
else:
float(shipping_cost)
print("Shipping cost: $" + str(shipping_cost))
# shipping costs are added
our_cost = float(price_cost) + float(shipping_cost)
print("Our total cost with shipping is $" + str(our_cost) + ".")
# ask user for desired profit
desired_profit = float(input("What is the minimum profit desired? $"))
commission_percent = .40
modifying_percent = (desired_profit + our_cost) / ((1. - commission_percent) * our_cost)
print(modifying_percent)
minimum_pricing = round((our_cost * modifying_percent), 3)
maximum_pricing = round((our_cost * (modifying_percent + 1.)), 3)
round_min_price = round_to_5(minimum_pricing)
round_max_price = round_to_5(maximum_pricing)
# print values for user
print("With a cost of $" + str(our_cost) + " including shipping,")
print("your desired profit (after commission) of $" + str(desired_profit) + ",")
print("we recommend a pricing range between $" + str(round_min_price) + "-$" + str(round_max_price) + ".")
restart = input("Start over? Y/N ")
if restart == "Y" or restart == "y":
installpricetool()
else:
print("Close tool.")
installpricetool()
|
7857e3db5217411ead0ea5c95cde7be0e9b32260 | JaiHindocha/Combat-Game | /main.py | 9,868 | 3.578125 | 4 | import random
class PlayerClass:
def __init__(self, attack, speed, health, heal):
self._AttackIncrease = attack
self._SpeedIncrease = speed
self._HealthIncrease = health
self._HealIncrease = heal
#self._Special = special
def returnAttackIncrease(self):
return self._AttackIncrease
def returnSpeedIncrease(self):
return self._SpeedIncrease
def returnHealthIncrease(self):
return self._HealthIncrease
def returnHealIncrease(self):
return self._HealIncrease
class Wizard(PlayerClass):
def __init__(self):
super().__init__(8,0,100,30) #"Deflect Attack"
def chooseWeapon(self):
print("""
Weapons Available:
1. Wizard Staff
2. Shield
""")
choice=input("Enter weapon 1 or 2: ")
while choice not in ['1','2']:
print("Please choose 1 or 2")
choice=input("Enter weapon 1 or 2: ")
if choice == '1':
return WizardStaff(),"Wizard"
else:
return Shield(),"Shield"
class Warrior(PlayerClass):
def __init__(self):
super().__init__(12,2,25,20) #"Double Sword Attack"
def chooseWeapon(self):
print("""
Weapons Available:
1. Sword
2. Dagger
3. Shield
""")
choice=input("Enter weapon 1 or 2 or 3: ")
while choice not in ['1','2','3']:
print("Please choose 1 or 2 or 3")
choice=input("Enter weapon 1 or 2 or 3: ")
if choice == '1':
return Sword(),"Sword"
if choice == '2':
return Dagger(),"Dagger"
else:
return Shield(),"Shield"
class Archer(PlayerClass):
def __init__(self):
super().__init__(4,3,25,15) #"Triple Arrow Shot"
def chooseWeapon(self):
print("""
Weapons Available:
1. Dagger
2. Bow and Arrow
""")
choice=input("Enter weapon 1 or 2: ")
while choice not in ['1','2','3']:
print("Please choose 1 or 2")
choice=input("Enter weapon 1 or 2: ")
if choice == '1':
return Dagger(),"Dagger"
else:
return Bow(),"Bow"
class PlayerRace:
def __init__(self,attack,speed,health,heal):
self._Attack = attack
self._Speed = speed
self._Health = health
self._Heal = heal
def returnAttack(self):
return self._Attack
def returnHealth(self):
return self._Health
def returnSpeed(self):
return self._Speed
def returnHeal(self):
return self._Heal
class Human(PlayerRace):
def __init__(self):
super().__init__(6,2,100,5)
class Elf(PlayerRace):
def __init__(self):
super().__init__(4,3,100,10)
class Giant(PlayerRace):
def __init__(self):
super().__init__(8,0,150,0)
class Weapon:
def __init__(self, damage, speed,block):
self._DamageBoost = damage
self._SpeedBoost = speed
self._Block = block
def returnDamageBoost(self):
return self._DamageBoost
def returnSpeedBoost(self):
return self._SpeedBoost
def returnBlock(self):
return self._Block
class WizardStaff(Weapon):
def __init__(self):
super().__init__(4,1,0)
class Shield(Weapon):
def __init__(self):
super().__init__(2,2,1)
class Sword(Weapon):
def __init__(self):
super().__init__(5,2,0)
class Dagger(Weapon):
def __init__(self):
super().__init__(3,4,0)
class Bow(Weapon):
def __init__(self):
super().__init__(2,4,0)
class BattleAxe(Weapon):
def __init__(self):
super().__init__(4,1,0)
class Fire(Weapon):
def __init__(self):
super().__init__(random.randint(6,10),1,0)
class Player:
def __init__(self, _class, weapon):
self._damage = 0
self._health = 0
self._speed = 0
self._heal = 0
self._class = _class
self._weapon = weapon
self._race = ''
self._block=0
def chooseRace(self):
print("""
Races:
1. Human - [Damage: 6, Player Attack Speed: 2, Health: 100, Heal: 5]
2. Elf - [Damage: 4, Player Attack Speed: 3, Health: 100, Heal: 10]
3. Giant - [Damage: 8, Player Attack Speed: 0, Health: 150, Heal: 0]
""")
choice = input("Choose a race: ")
while choice not in ['1','2','3']:
print("Invalid choice")
choice = input("Choose an option: ")
if choice == '1':
self._race = Human()
elif choice == '2':
self._race = Elf()
else:
self._race = Giant()
self._damage += self._race.returnAttack()
self._health += self._race.returnHealth()
self._speed += self._race.returnSpeed()
self._heal += self._race.returnHeal()
def classStats(self):
self._damage += (self._class.returnAttackIncrease() + self._weapon.returnDamageBoost())
self._health += self._class.returnHealthIncrease()
self._speed += (self._class.returnSpeedIncrease() + self._weapon.returnSpeedBoost())
self._heal += self._class.returnHealIncrease()
self._block = self._weapon.returnBlock()
def displayStats(self):
print("\nCHOSEN STATS: ")
print("Damage:",self._damage)
print("Health:",self._health)
print("Attacks per second:",self._speed)
print("Heal:",self._heal)
def Turn(self):
choice=input("Enter 'a' for attack, 'b' for block or 'h' for heal: ")
while choice not in ['a','b','h']:
choice=input("Enter 'a' for attack, 'b' for block or 'h' for heal: ")
return choice
def getHealth(self):
return self._health
def setHealth(self, health):
self._health = health
def getSpeed(self):
return self._speed
def getHeal(self):
return self._heal
def getAttack(self):
return self._damage
class EnemyRace:
def __init__(self,attack,health,speed):
self._Attack = attack
self._Health = health
self._Speed = speed
def returnAttack(self):
return self._Attack
def returnHealth(self):
return self._Health
def returnSpeed(self):
return self._Speed
class Dragon(EnemyRace):
def __init__(self):
super().__init__(10,400,2)
class Orc(EnemyRace):
def __init__(self):
super().__init__(7,300,4)
class Enemy:
def __init__(self):
self._Attack = 0
self._Health = 0
self._Speed = 0
self._Block = 0
self._weaponType = ''
self._raceType = ''
self._weapon = ''
def randomRace(self):
choice = random.randint(1,3)
if choice == 1:
self._race = Dragon()
self._raceType = "Dragon"
self._weapon = Fire()
self._weaponType = 'Fire'
else:
self._race = Orc()
self._raceType="Orc"
choice = random.randint(2,7)
if choice == 2:
self._weapon = Shield()
self._weaponType = "Shield"
elif choice == 3:
self._weapon = Sword()
self._weaponType = "Sword"
elif choice == 4:
self._weapon = Dagger()
self._weaponType = "Dagger"
elif choice == 5:
self._weapon = Bow()
self._weaponType = "Bow and Arrow"
else:
self._weapon = BattleAxe()
self._weaponType = "Battle Axe"
self._Attack += (self._race.returnAttack() + self._weapon.returnDamageBoost())
self._Health += self._race.returnHealth()
self._Speed += (self._race.returnSpeed() + self._weapon.returnSpeedBoost())
self._Block += self._weapon.returnBlock()
def displayStats(self):
print("\n")
print("ENEMY STATS:")
print("Race:",self._raceType)
print("Weapon:",self._weaponType)
print("Enemy Damage:",self._Attack)
print("Enemy Health:",self._Health)
print("Enemy Attack Speed:",self._Speed)
def Turn(self):
turn = random.choice(['a','b'])
return turn
def getHealth(self):
return self._Health
def setHealth(self,newHealth):
self._Health = newHealth
def getAttack(self):
return self._Attack
def getSpeed(self):
return self._Speed
def chooseClass():
print("""
Races:
1. Wizard - [Damage: 8, Speed Boost: 0, Health Boost: 100, Heal: 30]
2. Warrior - [Damage: 12, Speed Boost: 2, Health Boost: 25, Heal: 20]
3. Archer - [Damage: 3, Speed Boost: 3, Health Boost: 25, Heal: 10]
""")
choice = input("Choose a class: ")
while choice not in ['1','2','3']:
print("Invalid choice")
choice = input("Choose an option: ")
if choice == '1':
_class = Wizard()
weapon,weaponType = _class.chooseWeapon()
elif choice == '2':
_class = Warrior()
weapon,weaponType = _class.chooseWeapon()
else:
_class = Archer()
weapon,weaponType = _class.chooseWeapon()
return _class,weapon,weaponType
_class,weapon,weaponType = chooseClass()
user = Player(_class,weapon)
user.chooseRace()
user.classStats()
user.displayStats()
userAttack = user.getAttack()
userSpeed = user.getSpeed()
userHeal = user.getHeal()
print(weaponType)
enemy = Enemy()
enemy.randomRace()
enemy.displayStats()
enemyAttack = enemy.getAttack()
enemySpeed = enemy.getSpeed()
while user.getHealth() > 0 and enemy.getHealth() > 0:
enemyTurn = enemy.Turn()
enemyHealth = enemy.getHealth()
userTurn = user.Turn()
userHealth = user.getHealth()
if enemyTurn == 'a':
if userTurn == 'a':
enemyHealth -= userAttack * userSpeed
enemy.setHealth(enemyHealth)
userHealth -= enemyAttack * enemySpeed
user.setHealth(userHealth)
print("THE ENEMY ATTACKED!")
print("You took",enemyAttack * enemySpeed,'damage')
print("The enemy took",userAttack * userSpeed,'damage')
elif userTurn == 'b' and weapon != 'Shield':
userHealth -= 10
user.setHealth(userHealth)
print("THE ENEMY ATTACKED!")
print("You took 10 damage")
elif userTurn == 'b' and weapon == 'Shield':
print("THE ENEMY ATTACKED!")
print("You took 0 damage")
elif userTurn == 'h':
userHealth -= enemyAttack * enemySpeed
user.setHealth(userHealth)
print("THE ENEMY ATTACKED!")
print("You took",enemyAttack * enemySpeed,'damage')
print("The enemy took 0 damage")
elif enemyTurn == 'b':
if userTurn == 'a':
enemyHealth -= 5
enemy.setHealth(enemyHealth)
print("THE ENEMY BLOCKED!")
print("You took 0 damage")
print("The enemy took 5 damage")
elif userTurn == 'h':
userHealth += userHeal
user.setHealth(userHealth)
print("THE ENEMY BLOCKED!")
print("You gained",userHeal,"health")
else:
print("YOU AND THE ENEMY BOTH BLOCKED!")
print("\n")
if user.getHealth() > 0 and enemy.getHealth() > 0:
print("Your health:",userHealth)
print("Enemy health:",enemyHealth)
print("\n")
elif user.getHealth() < 0 and enemy.getHealth() < 0:
print("YOU BOTH TIE!!!")
elif user.getHealth() > 0 and enemy.getHealth() < 0:
print("YOU WIN!!!")
else:
print("YOU LOSE!!!")
|
4d5f420d62a3c5b26dfef1d59576b9646caa5900 | davendiy/ads_course2 | /subject5_trees/3358.py | 5,206 | 3.703125 | 4 | #!/usr/bin/env python3
# -*-encoding: utf-8-*-
# by David Zashkolny
# 2 course, comp math
# Taras Shevchenko National University of Kyiv
# email: davendiy@gmail.com
class Heap:
""" Клас структура даних Купа """
__slots__ = ('mItems', 'mSize')
def __init__(self):
""" Конструктор """
self.mItems = [0]
self.mSize = 0
def empty(self):
""" Перевіряє чи купа порожня
:return: True, якщо купа порожня
"""
return len(self.mItems) == 1
def insert(self, *k):
""" Вставка елемента в купу
:param k: k[0] - Елемент, що вставляється у купу
"""
self.mSize += 1
self.mItems.append(k[0]) # Вставляємо на останню позицію,
self.siftUp() # просіюємо елемент вгору
def getMaximum(self):
return self.mItems[1] if len(self.mItems) > 1 else 0
def extractMaximum(self):
""" Повертає мінімальний елемент кучі
:return: Мінімальний елемент кучі
"""
root = self.mItems[1] # Запам'ятовуємо значення кореня дерева
self.mItems[1] = self.mItems[-1] # Переставляємо на першу позицію останній елемент (за номером) у купі
self.mItems.pop() # Видаляємо останній (за позицією у масиві) елемент купи
self.mSize -= 1
self.siftDown() # Здійснюємо операцію просіювання вниз, для того,
# щоб опустити переставлений елемент на відповідну позицію у купі
return root # повертаємо значення кореня, яке було запам'ятовано на початку
def siftDown(self):
""" Просіювання вниз """
i = 1
while (2 * i + 1) <= self.mSize:
left = 2 * i
right = 2 * i + 1
min_child = self.maxChild(left, right)
if self.mItems[i][0] < self.mItems[min_child][0] or \
(self.mItems[i][0] == self.mItems[min_child][0] and
self.mItems[i][1] > self.mItems[min_child][1]):
self.swap(min_child, i)
i = min_child
def siftUp(self):
""" Дпопоміжний метод просіювання вгору """
i = len(self.mItems) - 1
while i > 1:
parent = i // 2
if self.mItems[i][0] > self.mItems[parent][0]:
self.swap(parent, i)
elif self.mItems[i][0] == self.mItems[parent][0] and \
self.mItems[i][1] < self.mItems[parent][1]:
self.swap(parent, i)
i = parent
def swap(self, i, j):
""" Допоміжний метод для перестановки елементів у купі,
що знаходяться на заданих позиціях i та j
:param i: перший індекс
:param j: другий індекс
"""
self.mItems[i], self.mItems[j] = self.mItems[j], self.mItems[i]
def maxChild(self, left_child, right_child):
""" Допоміжна функція знаходження меншого (за значенням) вузла серед нащадків поточного
:param left_child: лівий син
:param right_child: правий син
:return: менший з двох синів
"""
if right_child < self.mSize:
return left_child
else:
if self.mItems[left_child] > self.mItems[right_child]:
return left_child
else:
return right_child
class PriorityQueue(Heap):
__slots__ = Heap.__slots__ + ('mElementMap',)
def __init__(self):
Heap.__init__(self)
self.mElementMap = {}
def insert(self, *k):
k = k[0]
priority = self.mElementMap.get(k, None)
if priority is None:
self.mElementMap[k] = 1
Heap.insert(self, (1, k))
else:
self.mElementMap[k] += 1
Heap.insert(self, (priority + 1, k))
def extractMaximum(self):
res = Heap.extractMaximum(self) # type: tuple
self.mElementMap[res[1]] -= 1
return res
#
# def __str__(self):
# return f'PriorityQueue({self.mItems})'
#
# def __repr__(self):
# return f'PriorityQueue({self.mItems})'
if __name__ == '__main__':
n = int(input())
task = PriorityQueue()
for count in range(n):
tmp = input().split()
if tmp[0] == '+':
task.insert(int(tmp[1]))
rez = task.getMaximum()
rez = rez if rez == 0 else rez[1]
print(rez)
else:
task.extractMaximum()
rez = task.getMaximum()
rez = rez if rez == 0 else rez[1]
print(rez)
|
1a8052b8b2d5406cf6fa8feaa2f91a6b4133c943 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2452/58586/236423.py | 446 | 3.5625 | 4 | lines=int(input())
matrix=[]
for i in range(lines):
row=list(map(int,input().split(",")))
matrix.append(row)
start=0
end=len(matrix)*len(matrix[0])-1
width=len(matrix[0])
target=int(input())
while start<end:
mid=(start+end)//2
if matrix[mid//width][mid%width]==target:
break
elif matrix[mid//width][mid%width]<target:
start=mid+1
else:
end=mid
if(start<end):
print(True)
else:
print(False) |
c08633a8c506ad17fc1d6a6a787cd2703722a7d3 | lishulongVI/leetcode | /python/397.Integer Replacement(整数替换).py | 2,275 | 3.84375 | 4 | """
<p>
Given a positive integer <i>n</i> and you can do operations as follow:
</p>
<p>
<ol>
<li>If <i>n</i> is even, replace <i>n</i> with <code><i>n</i>/2</code>.</li>
<li>If <i>n</i> is odd, you can replace <i>n</i> with either <code><i>n</i> + 1</code> or <code><i>n</i> - 1</code>.</li>
</ol>
</p>
<p>
What is the minimum number of replacements needed for <i>n</i> to become 1?
</p>
</p>
<p><b>Example 1:</b>
<pre>
<b>Input:</b>
8
<b>Output:</b>
3
<b>Explanation:</b>
8 -> 4 -> 2 -> 1
</pre>
</p>
<p><b>Example 2:</b>
<pre>
<b>Input:</b>
7
<b>Output:</b>
4
<b>Explanation:</b>
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1
</pre>
</p><p>给定一个正整数 <em>n</em>,你可以做如下操作:</p>
<p>1. 如果 <em>n </em>是偶数,则用 <code>n / 2</code>替换 <em>n</em>。<br />
2. 如果 <em>n </em>是奇数,则可以用 <code>n + 1</code>或<code>n - 1</code>替换 <em>n</em>。<br />
<em>n </em>变为 1 所需的最小替换次数是多少?</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>
8
<strong>输出:</strong>
3
<strong>解释:</strong>
8 -> 4 -> 2 -> 1
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>
7
<strong>输出:</strong>
4
<strong>解释:</strong>
7 -> 8 -> 4 -> 2 -> 1
或
7 -> 6 -> 3 -> 2 -> 1
</pre>
<p>给定一个正整数 <em>n</em>,你可以做如下操作:</p>
<p>1. 如果 <em>n </em>是偶数,则用 <code>n / 2</code>替换 <em>n</em>。<br />
2. 如果 <em>n </em>是奇数,则可以用 <code>n + 1</code>或<code>n - 1</code>替换 <em>n</em>。<br />
<em>n </em>变为 1 所需的最小替换次数是多少?</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>
8
<strong>输出:</strong>
3
<strong>解释:</strong>
8 -> 4 -> 2 -> 1
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>
7
<strong>输出:</strong>
4
<strong>解释:</strong>
7 -> 8 -> 4 -> 2 -> 1
或
7 -> 6 -> 3 -> 2 -> 1
</pre>
"""
class Solution(object):
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
|
65cf921783e0f4b82e7f60dd2744aeb879eac326 | zaimeali/Data-Structure-and-Algorithms | /LCO Competitive/Day14.py | 803 | 3.53125 | 4 | def printAllCombination(arr):
if len(arr) == 0:
return []
if len(arr) == 1:
return [arr]
I = []
for i in range(len(arr)):
m = arr[i]
remLst = arr[:i] + arr[i+1:]
for p in printAllCombination(remLst):
I.append([m] + p)
return I
def fourPairCombination(arr):
combination = []
for person in arr:
for ret in arr:
temp = []
for com_person in arr:
if person != ret:
temp.append(ret)
temp.append(person)
combination.append(temp)
print(combination)
if __name__ == '__main__':
people = ['Ram', 'Anuj', 'Deepak', 'Ravi']
fourPairCombination(people)
print("================")
print(printAllCombination(people))
|
776d1668db4fce1c212f1300280ef1ceb2955554 | rgokhale31/ClassNameParser | /parser.py | 3,736 | 3.828125 | 4 | import json
#reads the file and extracts json components
def jsonReader(filename):
with open(filename, encoding='utf-8') as data_file:
jsonData = json.loads(data_file.read())
return jsonData
#outputs the relevant json data based on the word given by the user
def promptOutput(jsonData, inputWord):
output = searchWordRecurser(jsonData, inputWord)
outputList = []
numInputClass = 0
if (inputWord == "classNames"):
for sublist in output:
for curr in sublist:
outputList.append(curr)
else:
for curr in output:
outputList.append(curr)
if curr == "Input":
numInputClass = numInputClass + 1
print(outputList)
print("")
if (inputWord == "class"):
print("Number of Classes called 'Input' (Test to ensure correctness)")
print(numInputClass)
return
#outputs all the possible json data points the user would otherwise see separately
#extra functionality, more so for testing purposes
def promptAllOutput(jsonData):
outputClass = searchWordRecurser(jsonData, "class")
outputNames = searchWordRecurser(jsonData, "classNames")
outputIdents = searchWordRecurser(jsonData, "identifier")
outputList = []
for curr in outputClass:
outputList.append(curr)
for sublist in outputNames:
for curr in sublist:
outputList.append(curr)
for curr in outputIdents:
outputList.append(curr)
print(outputList)
return
#looks for the relevant data points based on the selector the user chose
def searchWordRecurser(jsonData, userInput):
#check if data is list type
#recursively checks subgroups, yield matching data points to user input
if (isinstance(jsonData, list)):
for dataPoint in jsonData:
for children in searchWordRecurser(dataPoint, userInput):
yield children
#check if data is dictionary type
#recursively check subgroups, yield matching data points to user input
elif (isinstance(jsonData, dict)):
for currWord, nestedData in jsonData.items():
if currWord == userInput:
yield nestedData
for jsonDataPoint in searchWordRecurser(nestedData, userInput):
yield jsonDataPoint
else:
return
return
#main method, user is consistently prompted to select a selector
def main():
cantinaData = jsonReader('SystemViewController.json')
userAnswer = "";
print("Welcome!")
print("Please select the type that you would like to see.")
print("Your options: 'class', 'classNames', 'identifier', 'all' or enter 'exit' if you wish to end the program.")
print("")
#consistently prompt for user input until the user exits
while userAnswer != "exit":
userAnswer = input("Please enter your answer: ")
userAnswer = userAnswer.lower()
print("")
if userAnswer == "class":
promptOutput(cantinaData, userAnswer)
elif userAnswer == "classnames":
userAnswer = "classNames"
promptOutput(cantinaData, userAnswer)
elif userAnswer == "identifier":
promptOutput(cantinaData, userAnswer)
elif userAnswer == "all":
promptAllOutput(cantinaData)
elif userAnswer == "exit":
print("Thank you for your participation. Have a nice day!")
break;
else:
print("Not valid. Try Again!")
#needed so that main method is run when program is run
if __name__ == "__main__":
main()
|
1fe0675192a2438deaf0dbc92c331f71c50180e1 | tsaxena/Master_Thesis | /NetAdapt/utils/compute_table/wideresnet_tf.py | 1,005 | 3.71875 | 4 | """functions used to create smaller models that are to be used in the tables in tensorflow"""
from tensorflow.keras.layers import BatchNormalization, Conv2D, AveragePooling2D, Dense, Activation, Flatten
from tensorflow.keras.models import Model
def make_conv_model(inputs, out_channels, stride, kernel_size=3):
"""creates a small sequential model composed of a convolution, a batchnorm and a relu activation"""
outputs = Conv2D(out_channels, kernel_size=kernel_size, strides=stride, padding="same", use_bias=False)(inputs)
outputs = BatchNormalization()(outputs)
outputs = Activation('relu')(outputs)
return Model(inputs=inputs, outputs=outputs)
def make_fc_model(inputs, num_classes, width):
"""creates a small sequential model composed of an average pooling and a fully connected layer"""
outputs = AveragePooling2D(pool_size=width)(inputs)
outputs = Flatten()(outputs)
outputs = Dense(units=num_classes)(outputs)
return Model(inputs=inputs, outputs=outputs)
|
693d94d5c82e62f57ce463bc89c2aa58b98673ce | wael20-meet/meetyl1201819 | /final_stage.py | 8,753 | 3.609375 | 4 |
import time
import turtle
from turtle import *
import random
turtle.tracer(0)
turtle.hideturtle()
import math
import sys
colormode(255)
turtle.setup(950,534)
class Ball(Turtle):
def __init__(self, x, y, dx, dy, radius, color):
Turtle.__init__(self)
self.pu()
self.goto(x,y)
self.dx = dx
self.dy = dy
self.radius = radius
self.shapesize(radius/10)
self.shape("circle")
r = random.randint (0,255)
g = random.randint (0,255)
b = random.randint (0,255)
self.color((r,g,b))
def move(self, screen_width, screen_height):
currentx = self.xcor()
currenty = self.ycor()
newx = currentx + self.dx
newy = currenty + self.dy
right_side_ball = newx + self.radius
left_side_ball = newx - self.radius
top_side_ball = newy + self.radius
bottom_side_ball = newy - self.radius
self.goto (newx , newy)
if right_side_ball >= screen_width:
self.dx = -self.dx
if left_side_ball <= -screen_width:
self.dx = -self.dx
if top_side_ball >= screen_height:
self.dy = -self.dy
if bottom_side_ball <= -screen_height:
self.dy = -self.dy
score = 0
RUNNING = True
sleep = 0.01996
SCREEN_WIDTH = turtle.getcanvas().winfo_width()//2
SCREEN_HEIGHT =turtle.getcanvas().winfo_height()//2
MY_BALL = Ball(0,0,30,20,30,"yellow")
NUMBER_OF_BALLS = 8
MINIMUM_BALL_RADIUS = 25
MAXIMUM_BALL_RADIUS = 45
MINIMUM_BALL_DY = -5
MAXIMUM_BALL_DY = 5
MINIMUM_BALL_DX = -5
MAXIMUM_BALL_DX = 5
BALLS = []
for i in range (NUMBER_OF_BALLS):
x = random.randint(int(-SCREEN_WIDTH) + int(MAXIMUM_BALL_RADIUS) , int(SCREEN_WIDTH) - int(MAXIMUM_BALL_RADIUS))
y = random.randint(int(-SCREEN_HEIGHT) + int(MAXIMUM_BALL_RADIUS),int(SCREEN_HEIGHT) - int(MAXIMUM_BALL_RADIUS))
dx = random.randint(MINIMUM_BALL_DX,MAXIMUM_BALL_DX)
if dx == 0:
dx = random.randint(MINIMUM_BALL_DX,MAXIMUM_BALL_DX)
dy = random.randint(MINIMUM_BALL_DY,MAXIMUM_BALL_DY)
if dy == 0:
dy = random.randint(MINIMUM_BALL_DY,MAXIMUM_BALL_DY)
radius = random.randint(MINIMUM_BALL_RADIUS,MAXIMUM_BALL_RADIUS)
color = (random.random(), random.random(), random.random())
ball = Ball(x, y, dx, dy, radius, color)
BALLS.append (ball)
food_list=[]
for i in range(15):
r= 1
x=random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS, SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
y=random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS)
screen=turtle.Screen()
screen.addshape("flappy.gif")
FOOD=Ball(x,y,r,0,0,"pink")
FOOD.shape("flappy.gif")
food_list.append(FOOD)
def move_all_balls():
for cow in BALLS:
cow.move(SCREEN_WIDTH, SCREEN_HEIGHT)
def collide(ball_a, ball_b):
ball_a_pos = ball_a.pos()
ball_b_pos = ball_b.pos()
if ball_a == ball_b :
return False
ball_a.xcor()
ball_a.ycor()
ball_b.xcor()
ball_b.ycor()
DISTANCE_BETWEEN_CENTERS = ((ball_a.xcor()-ball_b.xcor())**2 + (ball_a.ycor()-ball_b.ycor())**2)**0.5
if DISTANCE_BETWEEN_CENTERS+10 <= ball_a.radius + ball_b.radius:
return True
else:
return False
def check_all_balls_collision():
for ball_a in balls:
for ball_b in balls:
if check_collide(ball_a,ball_b) == True:
radius1 = ball_a.r
radius2 = ball_b.r
random_x = random.randint(screen_random1_x,screen_random2_x)
random_y = random.randint(screen_random1_y,screen_random2_y)
random_dx = random.randint(minimum_ball_dx,maximum_ball_dx)
while random_dx == 0:
random_dx = random.randint(minimum_ball_dx,maximum_ball_dx)
random_dy = random.randint(minimum_ball_dy,maximum_ball_dy)
while random_dy == 0:
random_dy = random.randint(minimum_ball_dy,maximum_ball_dy)
radius = random.randint(minimum_ball_radius,maximum_ball_radius)
color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
if radius1 > radius2:
ball_b.goto(random_x,random_y)
ball_b.dx = random_dx
ball_b.dy = random_dy
ball_b.r = radius
ball_b.shapesize(ball_b.r/10)
ball_b.color = color
ball_a.r += 0.5
ball_a.shapesize(ball_a.r/10)
elif radius1 < radius2:
ball_a.goto(random_x,random_y)
ball_a.dx = random_dx
ball_a.dy = random_dy
ball_a.r = radius
ball_a.shapesize(ball_a.r/10)
ball_a.color = color
ball_b.r += 0.5
ball_b.shapesize(ball_b.r/10)
def check_food_collision():
# global MY_BALL
for food in food_list:
if MY_BALL.radius <= food.radius:
RUNNING = False
elif collide(ball_a,ball_b) == True:
radius = MY_BALL
random_x = random.randint(screen_random1_x,screen_random2_x)
random_y = random.randint(screen_random1_y,screen_random2_y)
radius = random.randint(minimum_ball_radius,maximum_ball_radius)
color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
elif radius.MY_BALL > radius.food:
MY_BALL.goto(random_x,random_y)
MY_BALL.r = radius
MY_BALL.shapesize(Ball.r/10)
MY_BALL.color = color
MY_BALL += 0.5
def check_myball_collision():
for i in BALLS:
if collide(i,MY_BALL) == True:
radius_i = i.radius
radius_MY_BALL= MY_BALL.radius
ball_a = MY_BALL
ball_b = i
if MY_BALL.radius <= i.radius:
RUNNING = False
turtle.goto(-200,0)
turtle.color("red")
turtle.write("GAME OVER , YOU'RE A LOOOOOOOSER!!!!!!!", move=False, font=("Arial", 20, "bold"))
time.sleep(10)
sys.exit("Error message")
else:
X_coordinate = random.randint(int(-SCREEN_WIDTH) + int(MAXIMUM_BALL_RADIUS) , int(SCREEN_WIDTH) - int(MAXIMUM_BALL_RADIUS))
Y_coordinate = random.randint(int(-SCREEN_HEIGHT) + int(MAXIMUM_BALL_RADIUS),int(SCREEN_HEIGHT) - int(MAXIMUM_BALL_RADIUS))
X_axis_speed = random.randint(MINIMUM_BALL_DX,MAXIMUM_BALL_DX)
while X_axis_speed == 0:
X_axis_speed = random.randint(MINIMUM_BALL_DX,MAXIMUM_BALL_DX)
Y_axis_speed = random.randint(MINIMUM_BALL_DY,MAXIMUM_BALL_DY)
while Y_axis_speed == 0:
Y_axis_speed = random.randint(MINIMUM_BALL_DY,MAXIMUM_BALL_DY)
radius = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
color = (r,g,b)
ball_b.goto(X_coordinate, Y_coordinate)
ball_b.dx = X_axis_speed
ball_b.dy = Y_axis_speed
ball_b.shapesize(radius/10)
ball_b.color(color)
ball_a.radius = ball_a.radius+1
ball_a.shapesize(ball_a.radius/10)
return True
def movearound(event):
NEW_X_coordinate = event.x - SCREEN_WIDTH
NEW_Y_coordinate = -(event.y - SCREEN_HEIGHT)
MY_BALL.goto(NEW_X_coordinate, NEW_Y_coordinate)
turtle.getcanvas().bind("<Motion>", movearound)
turtle.listen()
while RUNNING == True:
if SCREEN_WIDTH!=turtle.getcanvas().winfo_width()/2 or SCREEN_HEIGHT!=turtle.getcanvas().winfo_height()/2 :
SCREEN_WIDTH=turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT=turtle.getcanvas().winfo_height()/2
move_all_balls()
if check_myball_collision() == False:
running = False
turtle.goto(0,0)
turtle.write("Game Over",align="center",font=("Arial", 50, "normal"))
turtle.update()
time.sleep(5)
turtle.update()
time.sleep(sleep)
move_all_balls()
check_myball_collision()
check_food_collision()
turtle.mainloop() |
ed86f635bc719b608cc89eef1552ff2f66277d89 | efreeman15/gwc | /object pseudocode no lecture.py | 2,377 | 4.75 | 5 | # how to define a cat object.
# THIS IS NOT VALID PYTHON CODE!!!!!!!!!!!!!!!!!!!!!
# THIS IS JUST AN EXAMPLE OF HOW CODE MIGHT LOOK.
# defining the Cat object
object Cat:
# this function is called automatically
# when we define a new instance of our class
def __init__(whiskers, color, size):
# save our parameters to variables (attributes)
w = whiskers
c = color
s = size
# define attributes without using parameters
feline = True
# new function (method) for ALL Cat objects
def meow():
print("Meow!")
# new method for all Cat objects using parameters
def eat(food):
print("The cat ate all of the %s!"%(food))
# now we are unindented out of the class definition body
# we are finished defining our object--our Cat template is done!
# --------------------------------------------------
# create a new instance of our Cat object
# this instance has 5 whiskers, a black color, and a large size
cat1 = Cat(5, "black", "large")
# to access attributes we use a . (period)
print(cat1.s) # this would print "large"
print(cat1.w) #this would print 5
print(cat1.f) # this would print True
# to access methods we also use a .
cat1.meow() # this would print "Meow!"
cat1.eat("fish") # this would print "The cat ate all the fish!"
cat1.eat("ice cream") # would print "The cat ate all the ice cream!"
# now we are going to define a second instance of the Cat object
cat2 = Cat(4, "orange", "medium")
print(cat2.s) # this would print ("medium")
cat2.meow() # this would print "Meow!"
# we can do this for as many Cats as we want!
cat3 = Cat(100, "purple", "enormous")
cat4 = Cat(0, "white", "tiny")
cat5 = Cat(10, "spotted", "small")
# we can also do the following to redefine attributes of an existing
# instance of the Cat object:
cat1.s = "small"
print(cat1.s) # this would print "small" even though it used to be "large"
# ! THE FOLLOWING CODE WILL NOT WORK !
badcat1 = Cat(5, "brown", "medium", False) # we have not set up a fourth parameter
badcat2 = Cat() # we have not defined our whiskers, color, and size attributes
badcat3 = (2, "green", "big") # we have not told Python to use the Cat object
badcat4 = Cat(3, "orange", "tiny") # this is an OK definition
print(badcat4.whiskers) # this is not defined, we would need to use badcat4.w
|
200d679ccb698ca8e919f9a57c61137a796e82dd | CallumGasteiger/dec2bin | /dec2bin.py | 195 | 3.578125 | 4 | def dec2bin(num):
list = []
while num >= 1:
if num % 2 == 1:
list.insert(0, 1)
num = num - 1
num = num/2
else:
list.insert(0, 0)
num = num/2
print list |
273d1c161d7ae047e847b4fdaa9339abac2fb0e2 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/508 Most Frequent Subtree Sum.py | 1,489 | 3.953125 | 4 | #!/usr/bin/python3
"""
Given the root of a tree, you are asked to find the most frequent subtree sum.
The subtree sum of a node is defined as the sum of all the node values formed by
the subtree rooted at that node (including the node itself). So what is the most
frequent subtree sum value? If there is a tie, return all the values with the
highest frequency in any order.
Examples 1
Input:
5
/ \
2 -3
return [2, -3, 4], since all the values happen only once, return all of them in
any order.
Examples 2
Input:
5
/ \
2 -5
return [2], since 2 happens twice, however -5 only occur once.
Note: You may assume the sum of values in any subtree is in the range of 32-bit
signed integer.
"""
# Definition for a binary tree node.
c_ TreeNode:
___ - , x
val x
left N..
right N..
____ c.. _______ d..
c_ Solution:
___ findFrequentTreeSum root
"""
traverse with counter
:type root: TreeNode
:rtype: List[int]
"""
counter d.. i..
traverse(root, counter)
ret [[], 0]
___ k, v __ counter.i..
__ v > ret[1]:
ret[0] [k]
ret[1] v
____ v __ ret[1]:
ret[0].a..(k)
r.. ret[0]
___ traverse root, counter
__ n.. root:
r.. 0
cur root.val
cur += traverse(root.left, counter)
cur += traverse(root.right, counter)
counter[cur] += 1
r.. cur
|
28548c0a5a58c5377ee4a03fc726d436040c4ad3 | caiopg/random-text-generator | /wordgenerator.py | 574 | 3.75 | 4 | import random
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
LETTERS = VOWELS+CONSONANTS
def assemble_word(user_options):
generated_word = ""
for option in user_options:
if option == 'v':
generated_word = generated_word + random.choice(VOWELS)
elif option == 'c':
generated_word = generated_word + random.choice(CONSONANTS)
elif option == 'l':
generated_word = generated_word + random.choice(LETTERS)
else:
generated_word = generated_word + option
return generated_word;
|
8496fdc4a044df128b3c1857dbd8e37250739b1c | atg-abhijay/LeetCode_problems | /hamming_distance_461.py | 522 | 4 | 4 | """
URL of problem:
https://leetcode.com/problems/hamming-distance/description/
"""
def main(x, y):
xor_result = x ^ y
# converting result to binary
# and getting rid of the '0b'
# at the beginning of the number
xor_result = bin(xor_result)[2:]
hamming_dist = 0
for digit in xor_result:
if digit == '1':
hamming_dist += 1
# print("Hamming distance:", hamming_dist)
return hamming_dist
main(int(input("Give first number: ")), int(input("Give second number: ")))
|
30e58c361ab33acb6fd20a43ad357c6a6c222e55 | ectky/PythonProjects | /Loops/Min-Number.py | 124 | 3.796875 | 4 | n = int(input())
Min = int(input())
for i in range(1, n):
num = int(input())
Min = min(Min, num)
print(Min)
|
24cdf92d04f733851006f1dbf66ba037ebf06934 | Pythonyte/lc | /misc/misc_codes/reorganize_string.py | 723 | 3.578125 | 4 | def reorganize_string(S):
from collections import Counter
import heapq
# for aab => pq = [(-2,a),(-1,b)]
# DOING NETAGIVE FOR MIN HEAP USAGE OF HEAPQ
pq = [(-value, key) for key, value in Counter(S).items()]
heapq.heapify(pq)
prev_freq, prev_char, result = 0, '', ''
while pq:
freq, char = heapq.heappop(pq)
result += char
if prev_freq < 0:
heapq.heappush(pq, (prev_freq, prev_char))
prev_freq, prev_char = freq+1, char
if len(result) != len(S): return ""
return result
print(reorganize_string('aab'))
print(reorganize_string('aaab'))
print(reorganize_string('aaabcd'))
print(reorganize_string('bbccdd'))
print(reorganize_string('a')) |
174d33540f0ae4b4e197a074f4dbb223574b2c27 | mws19901118/Leetcode | /Code/Maximum Twin Sum of a Linked List.py | 1,019 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
fast, slow = head, head #Use fast and slow pointers to find the mid point of linked list.
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
fast = fast.next
curr = slow.next #Reverse the second half.
while curr is not fast:
slow.next = curr.next
curr.next = fast.next
fast.next = curr
curr = slow.next
result = 0 #Find the max twin sum by traversing first half and second half simultaneously.
while curr:
result = max(head.val + curr.val, result)
head = head.next
curr = curr.next
return result
|
89eea1e6ab5b7e4e80fa834a72c8ff7f27336756 | ZX1209/gl-algorithm-practise | /leetcode-gl-python/leetcode-437-路径总和-III.py | 2,739 | 3.65625 | 4 | # leetcode-437-路径总和-III.py
# 给定一个二叉树,它的每个结点都存放着一个整数值。
# 找出路径和等于给定数值的路径总数。
# 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
# 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
# 示例:
# root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
# 10
# / \
# 5 -3
# / \ \
# 3 2 11
# / \ \
# 3 -2 1
# 返回 3。和等于 8 的路径有:
# 1. 5 -> 3
# 2. 5 -> 2 -> 1
# 3. -3 -> 11
"""
思路:
一层一层??
搜索??
参考,似乎是判断,上面节点的路径和有的个数,然后,看这个总和跟
这个节点差值的个数,就是,这个节点的所有可能形成的和.就这样,递归,求到
所有的..
答案是上浮的..
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import defaultdict
class Solution(object):
def pathSum(self, root, isum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
paths = defaultdict(int)
paths[0] = 1
def helper(node, partial):
if not node:
return 0
partial += node.val
count = paths[partial - isum]
# print(partial)
# print(paths)
# print(count)
# print('-'*10)
paths[partial] += 1
count += helper(node.left,partial)
count += helper(node.right,partial)
paths[partial] -=1
return count
return helper(root,0)
# nodes = [root]
# vals = [[root.val]]
# while nodes:
# tmpnodes = []
# for node in nodes:
# if node.left:
# tmpnodes.append(node.left)
# if node.right:
# tmpnodes.append(node.right)
# if tmpnodes: vals.append([tmp.val for tmp in tmpnodes])
# nodes = tmpnodes
# self.count = 0
# def dfs(node,l,e,tsum):
# if l>=e:
# if tsum==isum:
# self.count+=1
# return None
# for val in vals[l]:
# dfs(e,l+1,tsum+val)
# return None
# # 配对数
# for i in range(1,len(vals)+1):
# # 开始标号
# for j in range(0,len(vals)-i+1):
# dfs(j+i,j,0)
# return self.count |
4ab9eed249842f1a25c5832c66c492a1c5c70235 | gaohaoning/leetcode_datastructure_algorithm | /LeetCode/HashMap/290.py | 1,939 | 3.78125 | 4 | #!/usr/bin/env python
# coding:utf-8
"""
290. 单词模式
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。
这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false
示例 4:
输入: pattern = "abba", str = "dog dog dog dog"
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
"""
# ================================================================================
"""
普通解法
"""
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
ls = str.split()
if len(pattern) != len(ls) or len(set(pattern)) != len(set(ls)):
return False
#
used = {}
for k, v in zip(pattern, ls):
if k not in used:
used[k] = v
pass
elif used[k] != v:
return False
pass
return True
# ================================================================================
"""
牛逼解法
"""
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
ls = str.split()
z = zip(pattern, ls)
return len(pattern) == len(ls) and len(set(pattern)) == len(set(ls)) == len(set(z))
# ================================================================================
# ================================================================================
|
0cb706fdd05cdbfb8310255ba9bced03dc5fcac9 | yuju13488/pyworkspace | /m10_class/overridding.py | 511 | 3.9375 | 4 | class Parent:
def m1(selfs):
print('Parent:m1()')
def m2(selfs):
print('Parent:m2()')
class Child1(Parent):
def m3(self):
print('Child1:m3()')
def m2(self):
print('Child1:m2()') #覆寫、改寫父類別的方法
class Child2(Parent):
def m4(self):
print('Child2:m4()')
def main():
child1=Child1()
child1.m1()
child1.m2() #Child1:m2()
child1.m3()
child2=Child2()
child2.m1()
child2.m2() #Parent:m2()
child2.m4()
main() |
50f7d3d74363c7024f704113962255f67e9a88d9 | JSYoo5B/TIL | /PS/BOJ/4673/4673.py | 338 | 3.609375 | 4 | #!/usr/bin/env python3
def d_func(num):
for d in str(num):
num += int(d)
return num
if __name__ == '__main__':
gen_numbers = set()
for i in range(10000 + 1):
gen_numbers.add(d_func(i))
self_numbers = [ i for i in range(10000 + 1) if i not in gen_numbers ]
for n in self_numbers:
print(n)
|
8f394c528cc3d285fbc58d49690753cb254bb8f2 | Mateus-Silva11/AulasPython | /Aula_4/Aula4_1.py | 1,286 | 3.984375 | 4 | # Aula 4_2 13-11-2019
# Booleanas
#--- Variável booleana simples com True ou False
validador = False
#--- Substituição do valor inicial
validador = True
#--- Criação de variável booleana através de expressão de igualdade
idade = 18
validador = ( idade == 18 )
print(validador)
#--- Criação de variável booleana através de expressão da diferença
validador = ( idade != 18 )
print(validador)
#--- Criação de variável booleana através de expressão de maior
validador = ( idade > 18 )
print(validador)
#--- Criação de variável booleana através de expressão da menor
validador = ( idade < 18 )
print(validador)
#--- Criação de variável booleana através de expressão da maior e igual
validador = ( idade >= 18 )
print(validador)
#--- Criação de variável booleana através de expressão da menor e igual
validador = ( idade <= 18 )
print(validador)
#--- Criação de variável booleana através de expressão de negação
validador = not True
validador = not False
sorteado = 'Marcela'
#--- Criação de variável booleana através de duas expressões e operador E
validador = (sorteado=='Mateus' and sorteado=='Marcela')
#--- Criação de variável booleana através de duas expressões e operador OU
validador = (sorteado=='Mateus' or sorteado=='Marcela') |
377b293f98399186492f014a772258b4d9c209aa | rrwt/daily-coding-challenge | /daily_problems/linked_list.py | 717 | 3.71875 | 4 | from typing import Optional, Union, List
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.next: Optional[Node] = None
def print_ll(head: Node) -> None:
runner = head
while runner.next:
print(runner.data, end="->")
runner = runner.next
if runner:
print(runner.data)
def get_node_count(head: Node) -> int:
runner = head
count = 0
while runner:
count += 1
runner = runner.next
return count
def create_ll_from_list(values: List[Union[int, str]]) -> Node:
head = tail = Node(values[0])
for element in values[1:]:
tail.next = Node(element)
tail = tail.next
return head
|
08ce988bb8b10a78507c29948c0e5b65a5a993ba | alialmhdi/SmartCalculator | /Problems/CapWords/task.py | 241 | 4.09375 | 4 | user_input = input()
user_input_list = user_input.split("_")
words = []
if len(user_input_list) >= 2:
for word in user_input_list:
words.append(word.capitalize())
print("".join(words))
else:
print(user_input.capitalize()) |
ff9e691ba0f2dbedcffb7fb31e555c6ff399f70d | EinarK2/einark2.github.io | /Forritun/Forritun 1/Verkefni 1/Vísa 22.08.18.py | 407 | 3.515625 | 4 | #Höfundur Einar
# Forrit um vísu
print("halló")
karl=input("hvað heitir karlinn? ") #Les inn það sem er skrifað
kona=input("hvað heitir konan?? ")
drykkur=input("hvað drekka þau??? ")
#útskrift vísa
print("----------------------------------------------")
print(karl+" og "+kona+" eru hjón")
print("Óttalega mikil flón")
print("Þau eru bæði sæt og fín")
print("og þau drekka "+drykkur)
#the end
|
1b2ca7051a7c1aba1b08cc89871d1306a4aee035 | CrashLaker/HabitsID | /red2.py | 925 | 3.578125 | 4 | import random, time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
# Set GPIO to Broadcom system and set RGB Pin numbers
RUNNING = True
GPIO.setmode(GPIO.BCM)
red = 26
green = 20
blue = 27
# Set pins to output mode
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)
Freq = 100 #Hz
# Setup all the LED colors with an initial
# duty cycle of 0 which is off
RED = GPIO.PWM(red, Freq)
RED.start(0)
GREEN = GPIO.PWM(green, Freq)
GREEN.start(0)
BLUE = GPIO.PWM(blue, Freq)
BLUE.start(0)
# Define a simple function to turn on the LED colors
def color(R, G, B, on_time):
# Color brightness range is 0-100%
RED.ChangeDutyCycle(R)
GREEN.ChangeDutyCycle(G)
BLUE.ChangeDutyCycle(B)
time.sleep(on_time)
# Turn all LEDs off after on_time seconds
RED.ChangeDutyCycle(0)
GREEN.ChangeDutyCycle(0)
BLUE.ChangeDutyCycle(0)
color(100, 0, 0, 1)
#color(0, 100, 0, 2)
|
e956a96e0c3926f1930bebcdee63cdd470b174a2 | PrashilAlva/Programs | /Practice/Data Analytics (Heraizen)/Assignment/Set 2/q3.py | 346 | 3.71875 | 4 | n=int(input())
prime=list()
for i in range(2,n+1):
flag=0
for j in range(2,i//2+1):
if i%j==0:
flag=1
break
if flag==0:
prime.append(i)
print(prime)
sum=0
for ele in prime:
sum=sum+ele
print(sum)
squareprime=list()
for ele in prime:
squareprime.append(ele*ele)
print(squareprime) |
b458144c5bb94e8e08f5041393bbe057fab24acc | IvanciuVlad/PbInfo | /Clasa a IX-a/Algoritmi elementari/Cifrele unui număr/suma_cifrelor.py | 93 | 3.53125 | 4 | n = raw_input("")
n = int(n)
s = 0
while(n > 0):
s += n % 10
n = n // 10
print(str(s))
|
e8c0b19395e35fb42374404d56e830962b145d74 | GitAj19/Python-is-easy | /Homework Assignment #3: "If" Statements/main.py | 602 | 4.0625 | 4 | """Python Homework #3 - If Statements"""
import functions
# Print details
print("Check equal numbers 9, 8, 8")
print(functions.checkEqual(9,"8",8))
print("Check equal numbers 101, 101, 450")
print(functions.checkEqual(101, 101, 450))
print("Check equal numbers 10, 1.01, 10")
print(functions.checkEqual(10, 1.01, 10))
print("Check equal numbers -1.234 1.234, -8.3")
print(functions.checkEqual(-1.234, 1.234, -8.3))
print("Check equal numbers 5.3, -54, -5.3")
print(functions.checkEqual(5.3, -54, -5.3))
print("Check equal numbers -1.1, -5.3, -1.1")
print(functions.checkEqual(-1.1, -5.3, -1.1))
|
27925a43687cbc09034903eb2e2bc86b8d021cb9 | coderkhaleesi/Data-Science-Interview-Preparation | /DataStructuresAndAlgorithms/RecursionAndBacktracking/searchKeyInArray.py | 409 | 3.921875 | 4 | #Given an array of elements A, and a key k, search for k in A. If the key is present in the array A, return the index of key in A, else return -1
def searchElement(A, i, j, k):
if (i <= j):
if A[i] == k:
print(i)
return i
else:
return searchElement(A, i+1, j, k)
else:
return -1
if __name__=="__main__":
A = [1,2,5,6,7,8, -1]
index = searchElement(A, 0, len(A)-1, 7)
print(index) |
d62b2ebf517e9a704341f760bc6d68e5b6bec517 | kiryeong/python_intermediate_study | /p_chapter02_02.py | 2,738 | 3.625 | 4 | #Chapter 02-02
#객체 지향 프로그래밍(OOP) -> 코드의 재사용, 코드 중복 방지, 유지보수, 대형프로젝트
#규모가 큰 프로젝트(프로그램) -> 함수 중심 -> 데이터 방대 -> 복잡
#클래스 중심 -> 데이터 중심 -> 객체로 관리
#class Car(object):와 같은 거임 object를 상속받은 것
class Car():
"""
Car class
Author : Nam
Date : 2020.09.28
"""
#클래스 변수(모든 인스턴스가 공유)
car_count = 0
def __init__(self, company, details):
self._company = company #_가 있는 변수는 instance변수고, _가 없는 것은 모두가 공유하는 클래스 변수구나 암묵적 룰
self._details = details
Car.car_count += 1
def __str__(self):
return 'str : {} - {}'.format(self._company, self._details)
def __repr__(self):
return 'repr : {} - {}'.format(self._company, self._details)
def __del__(self):
Car.car_count -= 1
def detail_info(self):
print('Current ID : {}'.format(id(self)))
print('Car Detail Info : {} {}'.format(self._company, self._details.get('price')))
#self가 붙어있는게 instance 변수
#self를 인자로 받는 것은 instance method
#Self 의미
car1 = Car('Ferrari', {'color' : 'White', 'horsepower' : 400, 'price' : 8000})
car2 = Car('Bmw', {'color' : 'Black', 'horsepower' : 270, 'price' : 5000})
car3 = Car('Audi', {'color' : 'Silver', 'horsepower' : 300, 'price' : 6000})
# ID 확인
print(id(car1))
print(id(car2))
print(id(car3))
print(car1._company == car2._company)
print(car1 is car2)
#dir & __dict__ 확인
#dir : instance가 상속받은 attribute들을 list형태로 다 보여줌
print(dir(car1))
print(dir(car2))
print()
print()
#__dict__ : 안에 뭐있는지 궁금할 때
print(car1.__dict__)
print(car2.__dict__)
#Dortring
print(Car.__doc__)
print()
#실행
car1.detail_info()
Car.detail_info(car1)
car2.detail_info()
Car.detail_info(car2)
#에러
#Car.detail_info()
#비교
print(car1.__class__, car2.__class__)
print(id(car1.__class__), id(car2.__class__), id(car3.__class__))
#공유확인
print(car1.car_count)
print(car2.car_count)
print(car1.__dict__)
print(car2.__dict__)
print(dir(car1)) #클래스 변수 확인 할 때는 dir로 확인하는게 좋다.
print(dir(Car))
#접근
print(car1.car_count)
print(Car.car_count)
del car2
#삭제 확인
print(car1.car_count)
print(Car.car_count)
#인스턴스 네임스페이스에 없으면 상위에서 검색
#즉, 동일한 이름으로 변수 생성 가능(인스턴스 검색 후 -> 상위(클래스 변수, 부모클래스 변수))
|
c793cb680e139ffc713b694da0fd054fd1d769f3 | 2020ayao/Word_Ladder | /word_ladder_astar.py | 6,477 | 4.0625 | 4 | import math, random, time, heapq
class PriorityQueue():
"""Implementation of a priority queue
to store nodes during search."""
# TODO 1 : finish this class
# HINT look up/use the module heapq.
def __init__(self):
self.queue = []
self.current = 0
def next(self):
if self.current >= len(self.queue):
self.current
raise StopIteration
out = self.queue[self.current]
self.current += 1
return out
def pop(self):
# Your code goes here
return heapq.heappop(self.queue) # use heappop method to add to priority queue
def remove(self, nodeId):
# Your code goes here
return self.remove(nodeId) # use nodeId to find which node and remove that node
def __iter__(self):
return self
def __str__(self):
return 'PQ:[%s]' % (', '.join([str(i) for i in self.queue]))
def append(self, node):
# Your code goes here
heapq.heappush(self.queue, node) # using heappush method and append node to heapq
def __contains__(self, key):
self.current = 0
return key in [n for v, n in self.queue]
def __eq__(self, other):
return self == other
def size(self):
return len(self.queue)
def clear(self):
self.queue = []
def top(self):
return self.queue[0]
__next__ = next
def check_pq(): # method already made in shell code
''' check_pq is checking if your PriorityQueue
is completed or not'''
pq = PriorityQueue()
temp_list = []
for i in range(10):
a = random.randint(0, 10000)
pq.append((a, 'a'))
temp_list.append(a)
temp_list = sorted(temp_list)
for i in temp_list:
j = pq.pop()
if not i == j[0]:
return False
return True
def generate_adjacents(current, word_list):
''' word_list is a set which has all words.
By comparing current and words in the word_list,
generate adjacents set and return it'''
adj_set = set() # creates set to store adjacencies
# TODO 2: adjacents
# Your code goes here
adj_list = set()
alph = "abcdefghijklmnopqrstuvwxyz"
for i in range(len(current)):
for j in alph:
word = current[:i] + j + current[i + 1:]
if word != current and word in word_list:
adj_list.add(word)
return adj_list
def dist_heuristic(v, goal):
''' v is the current node. Calculate the heuristic function
and then return a numeric value'''
# TODO 3: heuristic
# Your code goes here
num = 0 # instantiate num to store the distance of heuristic function
for i in range(len(goal)): # traverse each letter in goal word
if v[i] != goal[i]: # if they don't match
num += 1 # increment num
return num # return the number of differences between v and goal
def a_star(word_list, start, goal, heuristic=dist_heuristic):
'''A* algorithm use the sum of cumulative path cost and the heuristic value for each loop
Update the cost and path if you find the lower-cost path in your process.
You may start from your BFS algorithm and expand to keep up the total cost while moving node to node.
'''
frontier = PriorityQueue() # instantiate a priority queue to hold all nodes
frontier.append((0, start, [start])) # begin with tuple state of cost 0 into frontier
dict = {start: dist_heuristic(start, goal)} # make a dictionary to hold path costs (heuristic values)
if start == goal: return [] # checking goalState()
# TODO 4: A* Search
# Your code goes here
while frontier.size() > 0: # while statement to check frontier size, should not be empty unless returned None
cost, current, path = frontier.pop() # separate tuple into variables
if current == goal: # checking goal
return path # return the path
for e in generate_adjacents(current, word_list): # traverse every word with one letter differences
# if e not in dict: #if word e has not been used yet
word_list.remove(e) # remove the word from word_list
frontier.append((dist_heuristic(current, goal) + 1 + dict[current], e, path + [e])) # add next node
# cost equals heuristic function + cumulative cost from dict + 1 due to extra step
dict[e] = dict[current] + 1 # + dist_heuristic(e,goal) #create dict entry with key e which stores cumulative cost
return None # none
def main():
word_list = set()
wor_list = set()
file = open("words_6_longer.txt", "r")
for word in file.readlines():
word_list.add(word.rstrip('\n'))
wor_list.add(word.rstrip('\n'))
file.close()
initial = input("Type the starting word: ")
goal = input("Type the goal word: ")
cur_time = time.time()
path_and_steps = (a_star(word_list, initial, goal))
path_nd_steps = (a_star(wor_list, goal, initial))
if path_and_steps != None and path_nd_steps != None:
if len(path_nd_steps) < len(path_and_steps):
print(path_nd_steps[::-1])
print("steps: ", len(path_nd_steps))
else: # because A*star sometimes gets longer path length,
print(path_and_steps) # you must double check if reverse case is shorter
print("steps: ", len(path_and_steps))
print("Duration: ", time.time() - cur_time)
else:
print("There's no path")
if __name__ == '__main__':
main()
'''Sample output 1
Type the starting word: listen
Type the goal word: beaker
['listen', 'lister', 'bister', 'bitter', 'better', 'beater', 'beaker']
steps: 7
Duration: 0.000997304916381836
Sample output 2
Type the starting word: vaguer
Type the goal word: drifts
['vaguer', 'vagues', 'values', 'valves', 'calves', 'cauves', 'cruves', 'cruses', 'crusts', 'crufts', 'crafts', 'drafts', 'drifts']
steps: 13
Duration: 0.0408782958984375
Sample output 3
Type the starting word: klatch
Type the goal word: giggle
['klatch', 'clatch', 'clutch', 'clunch', 'glunch', 'gaunch', 'launch', 'launce', 'paunce', 'pawnce', 'pawnee', 'pawned', 'panned', 'panged', 'banged', 'bunged', 'bungee', 'bungle', 'bingle', 'gingle', 'giggle']
steps: 21
Duration: 0.0867915153503418
'''
|
5f1572201b52a35d996bc31b1a483b695dcb93cb | rlan/pyml | /pyml/RunningVariance.py | 1,865 | 3.75 | 4 | from __future__ import division
from __future__ import print_function
class RunningVariance:
"""Compute running variance using Welford's algorithm
https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
Example
-------
>>> from RunningVariance import RunningVariance
>>> s = RunningVariance()
Initial values
>>> s.count()
0
>>> s.mean()
nan
>>> s.variance()
nan
>>> s.sampleVariance()
nan
Update with some values
>>> data = [1.0, 2.0, 3.0, 4.0, 5, 6, 7, 8, 9]
>>> isinstance(s(data), RunningVariance)
True
>>> s.count()
9
>>> s.mean()
5.0
>>> s.variance()
6.666666666666667
>>> s.sampleVariance()
7.5
Clear
>>> isinstance(s.clear(), RunningVariance)
True
>>> s.count()
0
>>> s.mean()
nan
>>> s.variance()
nan
"""
def __init__(self):
self.clear()
def __call__(self, input):
try:
for scalar in input:
self.update(scalar)
except TypeError:
self.update(input)
return self
def clear(self):
self.count_ = 0
self.mean_ = 0.0
self.M2_ = 0.0
return self
def update(self, input):
self.count_ += 1
delta = input - self.mean_
self.mean_ = self.mean_ + delta / self.count_
delta2 = input - self.mean_
self.M2_ = self.M2_ + delta * delta2
return self
def count(self):
return self.count_
def mean(self):
if self.count_ < 2:
return float('nan')
else:
return self.mean_
def variance(self):
if self.count_ < 1:
return float('nan')
else:
return self.M2_ / self.count_
def sampleVariance(self):
if self.count_ < 2:
return float('nan')
else:
return self.M2_ / (self.count_ - 1)
if __name__ == "__main__":
import doctest
import sys
(failure_count, test_count) = doctest.testmod()
sys.exit(failure_count)
|
640ca376db03a7c1e58901014c02c1c3e212bfe1 | anupamsharma/algo | /math_util.py | 2,605 | 3.765625 | 4 | import math
import sys
def get_binomial_coeffs_matrix(n):
"""
It returns the matrix a[n+1][n+1] containing binomial coefficient for a[i][j] for i>=j.
"""
max_n = n + 1
b_coeff = [range(0, max_n) for i in range(0, max_n) ]
b_coeff[0][0] = 1
b_coeff[1][1] = 1
b_coeff[1][0] = 1
for i in range(1, max_n):
max_j = i
b_coeff[i][0] = 1
b_coeff[i][i] = 1
for j in range(1, max_j):
b_coeff[i][j] = b_coeff[i-1][j-1] + b_coeff[i-1][j]
b_coeff[i][j] = b_coeff[i][j] % NUMBER
return b_coeff
def get_primes(n):
"""
Returns a n+1 length boolean list a indicating if i is prime by value of a[i]. It usage Sieve of Eratosthenes for
this.
doctest
>>> get_primes(5)
[True, True, True, True, False, True]
"""
assert(n>1)
primes = [True for i in range(0, n + 1)]
m = math.floor(math.sqrt(n))
count = 2
while(count <= m):
if primes[count]:
m_in = n/count
for i in range(2 * count, m_in * count + 1, count):
primes[i] = False
count = count + 1
return primes
def get_prime_numbers(n):
count = 0
primes = []
for i in get_primes(n):
if i: primes.append(count)
count = count + 1
return primes
def gcd(a, b):
"""
Calculates Greatest common devisor of two number using Euclid's theorem.
>>> gcd(5,4)
1
>>> gcd(10,4)
2
>>> gcd(50,10)
10
>>> gcd(1, 20)
1
>>> gcd(20, 20)
20
"""
if (a==b):
return a
if (a==1 or b==1):
return 1
x1 = max(a,b)
x2 = min(a,b)
rem = x1 % x2
if rem == 0:
return x2
else:
return gcd(x2, rem)
def lcm(a, b):
"""
Calculates LCM of a and b.
"""
return (a*b) / gcd(a, b)
def get_lattice_polygon_area(inside_points, boundary_points):
"""
Calculates area of lattice polygon based on Pick's Theorem.
"""
return inside_points + (boundary_points / 2) - 1
def intersect_of_two_rectangles(rect1_b_l, rect1_t_r, rect2_b_l, rect2_t_r,:
"""
This function returns the intersect of two rectangles if rectangles intersects otherwise None.
Rectangle should be represented as bottom left and right top.
"""
b_l = (max(rect1_b_l[0], rect2_b_l[0]), max(rect1_b_l[1], rect2_b_l[1])
t_r = (max(rect1_t_r[0], rect2_t_r[0]), max(rect1_t_r[1], rect2_t_r[1])
if (t_r[0] > b_l[0] and t_r[1] > b_l[1]):
return (b_l, t_r)
return None
|
3d0d9e2df948e64a8ffcf38d253e672e0d5aaea9 | kunalkhandelwal/Python-Projects | /movie.py | 510 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 12 14:20:34 2021
@author: kkhan
"""
import imdb
hr = imdb.IMDb()
movie_name= input("Please enter the name of the Movie: ")
movies = hr.search_movie((str()))
index =movies[0].getID()
movie = hr.get_movie(index)
title= movie['title']
year= movie['year']
cast= movie['cast']
list_of_cast = " ,".join(map(str,cast))
print("Title of the Movie:\n",title)
print("Year of Release of the Movie:\n",year)
print("Full Cast of the Movie:\n",list_of_cast) |
09dde4093ac3df809a011908102d6cc0e133e4b7 | AZAZAZAZ1/first_re-pository | /EXCELLL.py | 1,668 | 3.59375 | 4 |
#C:\Users\E.H.PAUE\Desktop\python lessons
import openpyxl
import os
os.chdir('C:\\Users\\E.H.PAUE\\python lessons')# change the directory of where the file is Excell sheet saved # dont forget to put \\ in the path
workbook = openpyxl.load_workbook('example.xlsx') # to open the excell sheet that saved in the above directory # the type of (woorkbook) is 'worbook'
type(workbook)
sheet= workbook["Sheet1"] # to open specific sheet
type(sheet)
sheetnames= workbook.sheetnames # to get all sheets in the workbook
#oldcode :sheet = workbook.get_sheet_by_name('Sheet1') # to open specific sheet in the excell work book # type is 'worksheet'
# old code :sheet = workbook.get_sheet_names() # to get all shhets in the workbook
# old code :sheet['A1'] # cell A1
#Old code :cell.value() # to get the cell value / or what written on it.
print (type(workbook))
print(type(sheet))
cell=sheet['A1'] # to select specif cell only
print(cell)# you will get <Cell 'Sheet1'.A1>
cell_value= cell.value # to get the value of the cell ('A1')
print(cell_value) # you will get 73
cellobject = sheet.cell(2,6) # row 2, column 6 you will get F2 (te select the cell by knowing the row and colum numbers)
print(cellobject)
for i in range(1,8):
print (i,sheet.cell(row=1, column=2).value) #
#print(sheet)
#print(sheetnames)
#cell_value = sheet.cell(1,5) # column1 , row 5
#sheet.value
#print(cell_value)
#print (sheet.value)
#wb.close()
# another code that can be used :
#from openpyxl import *
#source_file = load_workbook("file_path") # you can use the path instead of file name, no need to change the directory
#sheet = source_file["sheet_name"]
|
b96ca824dc22a9e3547f49f6e18976a70b579bce | wendelsilva/Python | /exercicios/exe028.py | 478 | 3.796875 | 4 | from random import choice
lista = [0,1,2,3,4,5]
escolher = choice(lista)
print("loading...")
print("O computador escolheu um número")
opcao = int(input("Escolha um número entre 0 e 5: "))
if opcao == escolher:
print("Parabens, você venceu!!")
print("O número escolhido pelo computador foi {} e o seu {}".format(escolher,opcao))
else:
print("tente novamente, você perdeu")
print("O número escolhido pelo computador foi {} e o seu {}".format(escolher,opcao)) |
33271bf2a9273093db3b29be5ddaf37536e17209 | manickaa/CodeBreakersCode | /Strings/Worksheet/checkValidSubstitutions.py | 824 | 3.984375 | 4 | class Solution:
def isValid(self, s: str) -> bool:
#O(N) time
#O(N) space if all characters are expect 'c'
if len(s) < 3:
return False
stack = []
for char in s:
if char != 'c':
stack.append(char)
elif char == 'c':
if stack and stack[-1] == 'b':
stack.pop()
if stack and stack[-1] == 'a':
stack.pop()
else:
return False
if not stack:
return True
else:
return False
if __name__ == '__main__':
sol = Solution()
print(sol.isValid("aabcbc"))
print(sol.isValid("abcabcababcc"))
print(sol.isValid("acabcb"))
print(sol.isValid("abccba"))
print(sol.isValid("a"))
|
349bfcc0e1cc16b4ebcff7cb94abf9f78820c4f4 | andersoncardoso/dump | /pypp4gamers/examples/animation.py | 807 | 3.546875 | 4 | #! /usr/bin/env python
# animation
from pypp4gamers import *
#setings
set_background_color(BLACK)
#initialize
pypp_init()
# defines main loop
def mainLoop():
x=10
y=20
vx = 5
vy = 5
width, height = get_screen_width(), get_screen_height()
while True:
#gets display and clean the screen
get_display()
# animation logic goes here
x = x+vx
y = y+vy
#draw_rect(name = 'square', size = (20,20) , pos=(x,y), color=(255,0,0))
draw_circle('a', radius=20, pos=(x,y), color=(255,0,0))
# update display and renders the screen
update_display()
if x > width-20 or x<0:
vx = -vx
if y > height-20 or y<0:
vy = -vy
mainLoop()
|
6d2d6a3832b60162365331cdebc0ee4a818b5964 | zalefin/sneruz | /sneruz/connective.py | 274 | 3.71875 | 4 |
def NOT(p):
return not p
def AND(p, q):
return p and q
def OR(p, q):
return p or q
def XOR(p, q):
return (p and not q) or (not p and q)
def IMPLIES(p, q):
return (not p) or (p and q)
def IFF(p, q):
return ((not p and not q) or (p and q))
|
89dd2b3b39962f1634bb4b52b810796b5deee60c | alexangupe/clasesCiclo1 | /P45/Clase4/interfaz.py | 884 | 3.75 | 4 | def bienvenida():
print("-------------------------------------------")
print("Bienvenido: Aplicación Cálculo de Impuestos")
print("-------------------------------------------")
def recogerPrecio4Productos():
producto1 = float(input('Ingrese el valor del primer producto: '))
producto2 = float(input('Ingrese el valor del segundo producto: '))
producto3 = float(input('Ingrese el valor del tercer producto: '))
producto4 = float(input('Ingrese el valor del cuarto producto: '))
return producto1,producto2,producto3,producto4
def reporte(precioRealCompra):
#return "Precio final de compra:"+str(precioRealCompra)
return f"Precio final de compra: {precioRealCompra}"
def finalizacionExitosa():
print("-------------------------------------------")
print("Finalización Exitosa")
print("-------------------------------------------") |
47a8e08acf10ce7eb47b5635eefdf65e299a3868 | muniri92/microsoft-interview-study | /src/find_rotation_point.py | 1,717 | 4.09375 | 4 | """
Write a function for finding the index of the "rotation point," which is where I started working from the beginning of the dictionary. This list is huge (there are lots of words I don't know) so we want to be efficient here.
words = [
'ptolemaic',
'retrograde',
'supplant',
'undulate',
'xenoepist',
'asymptote', # <-- rotates here!
'babka',
'banoffee',
'engender',
'karpatka',
'othellolagkage',
]
Since the list is mostly ordered, immediately think binary search
"""
def find_rotation_point(lst):
if len(lst) == 0:
raise Exception("List of words can't be empty!")
start_point = 0
end_point = len(lst) - 1
first = lst[0]
while start_point < end_point:
mid_point = start_point + ((end_point - start_point) // 2)
if lst[mid_point] >= first:
start_point = mid_point
else:
end_point = mid_point
if (start_point + 1) == end_point:
return end_point
if __name__ == '__main__':
perfect_list = ['asymptote', 'babka', 'banoffee', 'engender', 'karpatka', 'othellolagkage', 'ptolemaic', 'retrograde', 'supplant', 'undulate', 'xenoepist']
odd_list = ['othellolagkage', 'ptolemaic', 'retrograde', 'supplant', 'undulate', 'xenoepist', 'z', 'asymptote', 'babka', 'banoffee', 'engender', 'karpatka']
even_list = ['othellolagkage', 'ptolemaic', 'retrograde', 'supplant', 'undulate', 'xenoepist','asymptote', 'babka', 'banoffee', 'engender']
empty_list = []
print(find_rotation_point(perfect_list)) # 0
print(find_rotation_point(odd_list)) # 7
print(find_rotation_point(even_list)) # 6
print(find_rotation_point(empty_list)) # 0
|
0eb1e2f0f465e1e49b2cf133aac365d823749e48 | xtompok/prg2 | /list/list.py | 1,317 | 4.03125 | 4 | class ListNode(object):
def __init__(self,data):
super(ListNode,self).__init__()
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
super(LinkedList,self).__init__()
self.head = None
def append(self,data):
if self.head is None:
self.head = ListNode(data)
return
act = self.head
while act.next is not None:
act = act.next
new_node = ListNode(data)
act._next = new_node
def show(self):
"""Vytiskne jednotlivé prvky seznamu"""
if self.head is None:
# self.head = ListNode(data)
# seznam je prazdny
return
act = self.head
while act.next is not None:
# vytisknu hodnotu act
act = act.next
print("Prvek: {}".format(act.data))
def insert(self,idx,data):
"""Vloží na pozici idx prvek obsahující data,
ostatní odsune."""
# Dojdu na (idx-1). prvek
# Vytvořím nový prvek obsahující data
# odkaz next z (idx-1). prvku přesměruji na nový prvek
# odkaz z nového prvku přesměruji na (původně) i. prvek
ll = LinkedList()
ll.show()
ll.append(3)
ll.show()
ll.append(5)
ll.append(6)
ll.show() |
78ebb43397fa6506299cb46b6a4317b05ed0423e | Ariana1729/ariana1729.github.io | /writeups/2022/GreyCTF/Permutation/perm.py | 785 | 3.515625 | 4 | class Perm():
def __init__(self, arr):
assert self.valid(arr)
self.internal = arr
self.n = len(arr)
def valid(self, arr):
x = sorted(arr)
n = len(arr)
for i in range(n):
if (x[i] != i):
return False
return True
def __str__(self):
return ",".join(map(str, self.internal))
def __mul__(self, other):
assert other.n == self.n
res = []
for i in other.internal:
res.append(self.internal[i])
return Perm(res)
def __pow__(self, a):
res = Perm([i for i in range(self.n)])
g = Perm(self.internal)
while (a > 0):
if (a & 1): res = res * g
g = g * g
a //= 2
return res
|
22a46ad25d160525a0137a0ef1833d2845b89aff | AmrEsam0/HackerRank | /python3/2d_Array_DS.py | 709 | 3.609375 | 4 | #!/bin/python3
def list_sum(l):
total = 0
for i in range(len(l)):
total = total + l[i]
return total
def hourglassSum(arr):
max = -1000
s= []
sub_array = []
for m in range(4):
for col in range(4):
for row in range(3):
sub_array.append(arr[row + m][col: col + 3])
s = sub_array
hour_sum = list_sum(s[0]) + s[1][1] + list_sum(s[2])
if (max < hour_sum):
max = hour_sum
sub_array = []
return max
if __name__ == '__main__':
arr = [list(map(int, input().split())) for y in range(6)]
print(hourglassSum(arr))
|
f3b68660ea0e593638260247729a8ba20c8b1321 | jaewilson07/course-material | /exercices/230/solution.py | 312 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 23 17:37:53 2014
@author: Catherine
"""
def is_prime(n):
x = True
if n > 1:
for i in range(2, int(n ** .5)):
if (n % i) == 0:
x = False
return x
x = 100000000
while is_prime(x) is not True:
x = x + 1
print(x)
|
fae39f809f9202288cfe12ab7de8e63a05fd6341 | Rayban63/Coffee-Machine | /Problems/Calculator/task.py | 583 | 4 | 4 | first_num = float(input())
second_num = float(input())
operation = input()
no = ["mod", "div", "/"]
if second_num == (0.0 or 0) and operation in no:
print("Division by 0!")
elif operation == "mod":
print(first_num % second_num)
elif operation == "pow":
print(first_num ** second_num)
elif operation == "*":
print(first_num * second_num)
elif operation == "div":
print(first_num // second_num)
elif operation == "/":
print(first_num / second_num)
elif operation == "+":
print(first_num + second_num)
elif operation == "-":
print(first_num - second_num) |
40371230eb5f3a5b3e98e5fbc12624d681e52dbf | OmarMWarraich/Assignments | /32-Least_Common_Multiple.py | 238 | 4.09375 | 4 | # Ai Assignment 32 - Compute the Least Common Multiple of Two Positive Integers
n1 = int(input("Input Integer # 1 : "))
n2 = int(input("Input Integer # 2 : "))
x = n1
y = n2
while(y):
x, y = y, x % y
print("LCM is : ", (n1 * n2) / x)
|
7f2dcfb60194dfac2ad1cced431813d4eafa47a8 | B-Assis-O/Bernardo | /fibonacci.py | 275 | 3.890625 | 4 | n = int(input("Digite o número de termos desejado para a sequência de Fibonacci: "))
i = 1
b = 0
c = 1
a = 0
lista_fib = [0,1]
while i <= (n - 2):
a = c + b
b = c
c = a
lista_fib.extend([int(a)])
i = i + 1
print(lista_fib)
|
0730c1aa623b22523739dd3f0ff5d9943337ed10 | nikozhuharov/Python-Basics | /Introduction/08. Fish Tank.py | 381 | 3.671875 | 4 | # 1. Дължина в см – цяло число
# 2. Широчина в см – цяло число
# 3. Височина в см – цяло число
# 4. Процент зает обем – реално число
length = int(input())
width = int(input())
height = int(input())
percent = float(input())
print(((length*width*height)/1000)*(1-percent/100))
|
fddd0efebf80b9ffeff11cc2515fa385886edc29 | vitaliytsoy/problem_solving | /python/medium/reverse_words.py | 1,833 | 4.40625 | 4 | """
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
"""
class Solution:
def reverseWords(self, s: str) -> str:
split = s.split(' ')
result = ''
for index in range(1, len(split) + 1):
word = split[-index]
if len(word) == 0:
continue
result += f"{word} "
return result.strip()
def reverse_words(self, s: str) -> str:
words = []
word = ''
for index, letter in enumerate(s):
if len(word) == 0 and letter == ' ':
continue
if len(word) >= 1 and letter == ' ':
words.append(word)
word = ''
continue
word += letter
if index == len(s) - 1:
words.append(word)
word = ''
return ' '.join([words[index - 1] for index in range(len(words), 0, -1)])
solution = Solution()
# print(solution.reverseWords(" the sky is blue "))
# print(solution.reverse_words(" the sky is blue "))
# print(solution.reverse_words("the sky is blue"))
# print(solution.reverse_words("a good example"))
print(solution.reverse_words(" asdasd df f"))
|
6b0f9a6268da0577ce7fac4e6447bd8bc669fc23 | rafaeljordaojardim/python- | /regex/regex.py | 3,032 | 4.40625 | 4 | mystr = "YOu can learn any programming language, whether it is Python2, Python3"
import re
# a = re.match(pattern, string, optional flags)
# Try to apply the pattern at the start of the string,
# returning a match object, or None if no match was found.
a = re.match("You", mystr)
# entire method returned
a = re.match("you", mystr, re.I)
mystr = "can learn any programming language, whether it is Python2, Python3"
# if we want to get in the middle of the string uses search
# a = re.search(pattern, string, optional flags)
a = re.search(r"(.+?) +(\d) +(.+?)\s{2,}(\w)*" , mystr)
# find all returns a list
#Regular Expressions - the "re.match" and "re.search" methods
# a = re.match(pattern, string, optional flags) #general match syntax; "a" is called a match object if the pattern is found in the string, otherwise "a" will be None
mystr = "You can learn any programming language, whether it is Python2, Python3, Perl, Java, javascript or PHP."
import re #importing the regular expressions module
a = re.match("You", mystr) #checking if the characters "You" are indeed at the beginning of the string
a.group() #result is 'You'; Python returns the match it found in the string according to the pattern we provided
a = re.match("you", mystr, re.I) #re.I is a flag that ignores the case of the matched characters
# a = re.search(pattern, string, optional flags) #general search syntax; searching for a pattern throughout the entire string; will return a match object if the pattern is found and None if it's not found
arp = "22.22.22.1 0 b4:a9:5a:ff:c8:45 VLAN#222 L"
a = re.search(r"(.+?) +(\d) +(.+?)\s{2,}(\w)*", arp) #result is '22.22.22.1'; 'r' means the pattern should be treated like a raw string; any pair of parentheses indicates the start and the end of a group; if a match is found for the pattern inside the parentheses, then the contents of that group can be extracted with the group() method applied to the match object; in regex syntax, a dot represents any character, except a new line character; the plus sign means that the previous expression, which in our case is just a dot, may repeat one or more times; the question mark matching as few characters as possible
a.groups() #returns all matches found in a given string, in the form of a tuple, where each match is an element of that tuple
('22.22.22.1', '0', 'b4:a9:5a:ff:c8:45 VLAN#222', 'L')
#Regular Expressions - the "re.findall" and "re.sub" methods
a = re.findall(r"\d\d\.\d{2}\.[0-9][0-9]\.[0-9]{1,3}", arp) #returns a list where each element is a pattern that was matched inside the target string
['22.22.22.1'] #result of the above operation - a list with only one element, the IP address matched by the regex
b = re.sub(r"\d", "7", arp) #replaces all occurrences of the specified pattern in the target string with a string you enter as an argument
'77.77.77.7 7 b7:a7:7a:ff:c7:77 VLAN#777 L 77.77.77.77' #result of the above operation |
e49e5a94fc26bb536a0fd225448cd16654dcd941 | vishnia92/algo.python | /l2_3.py | 493 | 4.15625 | 4 | # 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
# Например, если введено число 3486, то надо вывести число 6843.
num = int(input('Введите целое число: '))
invers = 0
while num % 10 != 0 or num // 10 != 0:
invers = invers * 10 + num % 10
num //= 10
print(f'Обратное число = {invers}') |
5707c0985e9f1bbd412a1d4bcb5895e2337eb9d5 | haoonkim/python-challenge1 | /PyPoll/main.py | 1,860 | 3.703125 | 4 | #import csv dependencies
import os
import csv
#read csv and make the path for file
data_output = os.path.join('/Users/haoonkim/Desktop/election_data.csv')
#variables to count votes
total_vote = 0
khan_vote = 0
correy_vote = 0
li_vote = 0
otooley_vote = 0
#read data
with open(data_output, newline = '') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
#read the header first row
csv_header = next(csvreader)
#calculate total vote
#candidates' votes, so we can know who wins
for row in csvreader:
total_vote += 1
if row[2] == "Khan":
khan_vote += 1
elif row[2] == "Correy":
correy_vote += 1
elif row[2] == "Li":
li_vote += 1
else:
otooley_vote += 1
#candidate's vote percentage
khan_per = khan_vote / total_vote
correy_per = correy_vote / total_vote
li_per = li_vote / total_vote
otooley_per = otooley_vote / total_vote
#calculate winner
if khan_vote > correy_vote and khan_vote > li_vote and khan_vote > otooley_vote:
win = "Khan"
elif correy_vote > khan_vote and correy_vote > li_vote and correy_vote > otooley_vote:
win = "Correy"
elif li_vote > khan_vote and li_vote > correy_vote and li_vote > otooley_vote:
win = "Li"
else:
win = "O'tooley"
#print analysis
printout = (f"Election Results\n"
f"-------------------------\n"
f"Total Votes: {total_vote}\n"
f"-------------------------\n"
f"Khan: {khan_per:.3%} ({khan_vote})\n"
f"Correy: {correy_per:.3%} ({correy_vote})\n"
f"Li: {li_per:.3%} ({li_vote})\n"
f"O'Tooley: {otooley_per:.3%} ({otooley_vote})\n"
f"-------------------------\n"
f"Winner: {win}\n"
f"-------------------------")
print(printout)
|
c72e1d6a0ed995152d71a315dd8d2e5702a4de12 | bpuderer/python-snippets | /general/function_args.py | 901 | 3.953125 | 4 | # args=tuple, kwargs=dict
def ftn(a, b=0, *args, **kwargs):
print(f"a={a} b={b} args={args} kwargs:{kwargs}")
ftn(1)
ftn(1, 2)
ftn(1, 2, 3)
ftn(1, c=42)
# unpack list or tuple
# https://docs.python.org/3.7/tutorial/controlflow.html#unpacking-argument-lists
# PEP 448 added unbounded number of * and ** unpackings
lst = [1, 2, 3]
tup = (4, 5, 6)
ftn(*lst, *tup)
# unpack dict
d1 = {'a': 99, 'c': 42}
d2 = {'d': 43}
ftn(**d1, **d2)
# both
ftn(*lst, *tup, **d2) # cannot unpack d1 because multiple vals for a: TypeError
# PEP 3102 keyword only args
def ftn2(a, *, b=None, c):
print(f"a={a} b={b} c={c}")
# b and c must be specified by keyword
ftn2(1, c=3)
ftn2(1, b=2, c=3)
# forwarding arguments
def trace(f, *args, **kwargs):
print(f'args:{args} kwargs:{kwargs}')
result = f(*args, **kwargs)
print('result =', result)
return result
print(trace(int, 'fe', base=16))
|
0296343e8410032a44f1a72235d0e0e5c6e93aee | Fluffhead88/mystery-word | /normal.py | 1,305 | 4.03125 | 4 |
# Word guessing game, similar to hang man
import random
with open('/usr/share/dict/words') as infile:
word = infile.readlines()
answer = random.choice(word).lower().replace("\n", "")
used_letters = []
game_word = []
len_word = len(answer)
def display():
for char in answer:
game_word.append('_')
print("This word has ", len_word, "letters.")
return game_word
def play():
turns = 8
while turns > 0:
print ("You have", turns, "guesses remaining.")
print(game_word)
if '_' not in game_word:
print("You win!")
break
letter_guessed = (input("Guess a letter > ")).lower()
if letter_guessed in used_letters:
print ("You already guessed that letter.")
else:
used_letters.append(letter_guessed)
if letter_guessed in answer:
print("Correct!")
else:
turns -= 1
if turns >= 1:
print ("Sorry, please try again.")
if turns == 0:
print ("You lose!")
print ("The answer was", answer)
for letter in range(0, len_word):
if answer[letter] == letter_guessed:
game_word[letter] = letter_guessed
display()
play()
|
e03fc44540f70eda9f57b3d046674fab2494102b | lexust1/algorithms-stanford | /Course2/02c03w.py | 2,500 | 4.09375 | 4 | # Download the following text file:
# Median.txt
# The goal of this problem is to implement the "Median Maintenance" algorithm
# (covered in the Week 3 lecture on heap applications). The text file
# contains a list of the integers from 1 to 10000 in unsorted order;
# you should treat this as a stream of numbers, arriving one by one.
# Letting x_i denote the i-th number of the file, the k-th median m_k
# is defined as the median of the numbers x_1,...,x_k.
# (So, if k is odd, then m_k is ((k+1)/2)-th smallest number among
# x_1,...,x_k; if k is even, then m_k is the (k/2)-th smallest number among
# x_1,...,x_k.
# In the box below you should type the sum of these 10000 medians,
# modulo 10000 (i.e., only the last 4 digits). That is, you should
# compute (m1+m2+m3+⋯+m10000)mod 10000.
# OPTIONAL EXERCISE: Compare the performance achieved by heap-based and
# search-tree-based implementations of the algorithm.
import heapq
# Create a list of integers from txt-file
fh = open("Median.txt", "r")
list_str = fh.readlines()
fh.close()
lst = [int(el) for el in list_str]
# Create empty lists for two heaps and all medians
heap_low = [] #[1, 2 , 3]
heap_high = [] #[5, 6, 7]
medians = [] # 4
# Convert lists to heaps.
heapq.heapify(heap_low)
heapq.heapify(heap_high)
# Add initial conditions
heap_high.append(lst[0]) # use 2nd heap because heapq has min-heap only
medians.append(lst[0])
# Get every element in list and create algorithm for every heap.
for num in lst[1:]:
if num > heap_high[0]:
heapq.heappush(heap_high, num)
else:
# Heapq library in python does not have max-heap. Because we need to
# use a trick with negative values of min-heap.
heapq.heappush(heap_low, -num) #minus num! ()
# Count difference between heaps for balance
dif_heaps = len(heap_high) - len(heap_low)
# Choose heap for balance
if dif_heaps > 1:
bal_el = heapq.heappop(heap_high)
heapq.heappush(heap_low, -bal_el) #minus bal_el!
elif dif_heaps < - 1:
bal_el = heapq.heappop(heap_low)
heapq.heappush(heap_high, -bal_el) #minus bal_el!
#Count medians
if len(heap_low) < len(heap_high):
medians.append(heap_high[0])
else:
medians.append(-heap_low[0])
#Create answer
answer = sum(medians) % 10000
|
96380019ffe0fa14a4d120b5561c11fb75534d15 | joaopauloaramuni/python | /desafio_python/logica.py | 1,224 | 4.40625 | 4 | '''
Lógica de programação
Pensando em todos os números naturais inferiores a 10 que são múltiplos de 3 ou 5, temos 3, 5, 6 e 9. Somando esses múltiplos obtemos o valor 23.
Utilize um algorítimo para calcular a soma de todos os múltiplos de 3 ou 5 abaixo de 1000
'''
def e_multiplo(numero=None, multiplos=None):
"""Entrada:
Numero: int
Multiplo: array de int ou um int
Saída esperada:
Boolean se número é multiplo"""
if not (isinstance(numero, int) and isinstance(multiplos, (int, list, tuple))):
raise Exception("'numero' deve ser um int e 'multiplos' deve ser um int ou uma lista/tupla de int")
if isinstance(multiplos, int):
return numero % multiplos == 0
else:
for multiplo in multiplos:
if not isinstance(multiplo, int):
raise Exception("'multiplos' deve ser um int ou uma lista/tupla de int")
if numero % multiplo == 0:
return True
return False
numeros = []
teste_multiplos = (3, 5)
for numero in range(1000):
if e_multiplo(numero, teste_multiplos):
numeros.append(numero)
print(f"A soma de todos os múltiplos de 3 ou 5 abaixo de 1000 é: {sum(numeros)}")
|
71e231d9c5f7155ca2bcf06393f4b8ae8199bf2b | YiHerngOng/leetcode_practice | /python/Longest_Panlindromic_substring.py | 1,278 | 3.625 | 4 | class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
p = 0
ans = ""
# define the start of longest substring
start_of_longest = 0
max_length = 1
# two pointers for both ends of a string
low = 0
high = 0
if len(s) == 0:
return ""
if len(s) == 1:
return s[0]
for p in range(1, len(s)):
# search for even substring
low = p-1
high = p
while low >= 0 and high<len(s) and s[low] == s[high]:
if high - low + 1 > max_length:
start_of_longest = low
max_length = high-low+1
low -= 1
high += 1
# search for odd substring
low = p - 1
high = p + 1
while low >= 0 and high<len(s) and s[low] == s[high]:
if high - low + 1 > max_length:
start_of_longest = low
max_length = high-low+1
low -= 1
high += 1
return s[start_of_longest:start_of_longest+max_length] |
358db80d72bc7e80516cc1b52bd90c7ff67b6375 | vrsilva17/fichas_aula | /fa_3/ex2.py | 152 | 3.9375 | 4 | inicio = int(input('Introduza o inicio do ciclo: '))
fim = int(input('Introduza o fim do ciclo: '))
for item in range(inicio, fim, 1) :
print(item) |
c4b74032ef3283c28fc88850d74061bba4e30405 | alextanhongpin/project-euler | /python/49-prime-permutations.py | 1,523 | 3.640625 | 4 | # 1487, 4817, 8147
# step: 3330
import math
def is_prime (n):
"""
Checks if a number is a prime number
"""
if n <= 1:
return False
elif n == 2:
return True
elif n == 3:
return True
else:
square_root = int(math.ceil(math.sqrt(n)))
for i in range(square_root + 1, 2, -1):
if n % i == 0:
return False
elif n % 2 == 0:
return False
elif n % 3 == 0:
return False
return True
def unique(n):
a = [str(n)[i] for i in range(len(str(n)))]
a.sort()
return int("".join(a))
def main():
s = set()
n = 0
# First, get the primes with 4-digits
primes = filter(lambda x: x is not None, [ i if is_prime(i) else None
for i in range(1000, 9999)])
while len(s) < 3:
for i in range(len(primes)):
a = n * 0 + primes[i]
b = n * 1 + primes[i]
c = n * 2 + primes[i]
if a in primes and b in primes and c in primes:
if a != b and b != c:
if unique(a) == unique(b) and unique(b) == unique(c):
s.add(a)
s.add(b)
s.add(c)
n += 1
print n
if __name__ == '__main__':
import timeit
ITERATIONS = 10
MESSAGE = "Function takes {} s to complete."
print MESSAGE.format(timeit.timeit("main()",
number=ITERATIONS,
setup="from __main__ import main") / ITERATIONS)
|
3e95c1ebd79235cd18ef20d4ba1b441c63fd11cb | JakeTux8/Movie-Trailer-Website | /media.py | 679 | 3.6875 | 4 | import webbrowser # module needed to open url links in browser
class Movie():
""""This class allows the creation of movie objects that include movie
title, synopsis, poster, and trailer"""
# Movie class constructor.
def __init__(self, movie_title, movie_storyline, poster_image,
trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
# Function to show movie trailer
def show_trailer(self):
# opens youtube url in system's default browser
webbrowser.open(self.trailer_youtube_url)
|
7ed2f00c05eb1fe27e686c35fa4d5a8e303b38fb | dheerajs0346/PYPL | /regular_expressions/py/re_special_char_matches.py | 2,326 | 4.21875 | 4 | #!/usr/bin/python
################################################
## matching special characters
## author: vladimir kulyukin
############################################
import re
txt_01 = '12345'
txt_02 = 'abcde'
txt_03 = ' .;!?\\'
txt_04 = ' .;!?\\_'
txt_05 = ' .;!?\\_\n';
txt_lst = (txt_01, txt_02, txt_03, txt_04, txt_05)
def find_digit_char(txt):
if re.search(r'\d', txt):
print 'there is at least one digit char in ' + repr(txt)
else:
print 'there are no digit chars in ' + repr(txt)
def digit_char_tests(txts):
print r'**** \d Tests ****'
for txt in txts: find_digit_char(txt)
def find_nondigit_char(txt):
if re.search(r'\D', txt):
print 'there is at least one nondigit char in ' + repr(txt)
else:
print 'there are no nondigit chars in ' + repr(txt)
def nondigit_char_tests(txts):
print r'**** \D Tests ****'
for txt in txts: find_nondigit_char(txt)
def find_word_char(txt):
if re.search(r'\w', txt):
print 'there is at least one word char in ' + repr(txt)
else:
print 'there are no word chars in ' + repr(txt)
def word_char_tests(txts):
print r'**** \w Tests ****'
for txt in txts: find_word_char(txt)
def find_nonword_char(txt):
if re.search(r'\W', txt):
print 'there is at least one non-word char in ' + repr(txt)
else:
print 'there are no non-word chars in ' + repr(txt)
def nonword_char_tests(txts):
print r'**** \W Tests ****'
for txt in txts: find_nonword_char(txt)
def find_whitespace_char(txt):
if re.search(r'\s', txt):
print 'there is at least one whitespace char in ' + repr(txt)
else:
print 'there are no whitespace chars in ' + repr(txt)
def whitespace_char_tests(txts):
print r'**** \s Tests ****'
for txt in txts: find_whitespace_char(txt)
def find_nonwhitespace_char(txt):
if re.search(r'\S', txt):
print 'there is at least one non-whitespace char in ' + repr(txt)
else:
print 'there are no non-whitespace chars in ' + repr(txt)
def nonwhitespace_char_tests(txts):
print r'**** \S Tests ****'
for txt in txts: find_nonwhitespace_char(txt)
# uncomment to run the tests
#digit_char_tests(txt_lst)
#nondigit_char_tests(txt_lst)
#word_char_tests(txt_lst)
#nonword_char_tests(txt_lst)
#whitespace_char_tests(txt_lst)
#nonwhitespace_char_tests(txt_lst)
|
b2cdda436876d39e4bc01b582ac43b7e579ce1d2 | NivruthaBalaji/guvi11 | /power.py | 213 | 4 | 4 | base=int(raw_input("Enter base: "))
exp=int(raw_input("Enter exponential value: "))
power=1
i=0
if exp==1:
print "Power=",base
else:
for i in range(0,exp):
power=power*base
print"Power=",power
|
7878bf85678ac50926c92721576054df35ace74e | QuaziBit/Python | /demo/user_input.py | 143 | 3.984375 | 4 | name = input("Uer input your name: ")
age = input("Uer input your age: ")
age = int(age)
print("\n%s you are %d years old!\n" % (name, age) ) |
5a44d1307a3166b45ee4523ab9c330e4dbe5f5b1 | Amruta-Pendse/Python_Exercises | /TempCoversion.py | 496 | 4.34375 | 4 | #Program to covert Temperature from/to Celsius to Farenheit
n1=input("Enter 'C' to enter Temperature in Celsius and 'F' for Farenheit:")
if(n1=='C' or n1=='c'):
ctemp= float(input("Enter Temperature in Celsius:"))
ftemp=(ctemp*1.8) +32
print("Temperature in Farenheit is:", ftemp)
elif (n1=='F' or n1=='f'):
ftemp=float(input("Enter Temperature in Farenheit:"))
ctemp=(ftemp-32)/1.8
print("Temperature in Celsius is:",ctemp)
else:
print("Not a valid value") |
5ac52a60fa2924f1751632c69aab8cc16cdbf911 | stephenroche/COMP2041---Software-Construction | /lab08/shortest_path.py | 1,104 | 3.890625 | 4 | #!/usr/bin/env python3
import sys, re
(start, end) = (sys.argv[1], sys.argv[2])
roads = {}
visited = {}
for line in sys.stdin:
matches = re.findall('(\S+)\s+(\S+)\s+(\d+)', line)
frm = matches[0][0]
to = matches[0][1]
length = matches[0][2]
visited[frm] = 0
visited[to] = 0
if (frm not in roads.keys()):
roads[frm] = {}
roads[frm][to] = int(length)
if (to not in roads.keys()):
roads[to] = {}
roads[to][frm] = int(length)
prev = {}
dist = {}
dist[start] = 0
while (1):
curr = sorted(dist, key=dist.get)
curr = sorted(curr, key=visited.get)[0]
visited[curr] = 1
#print("curr = %s" % curr)
for next in roads[curr]:
alt = dist[curr] + roads[curr][next]
if (next not in dist or alt < dist[next]):
dist[next] = alt
prev[next] = curr
if (curr == end):
#print(dist[end])
break
curr = end
route = []
while (curr != start):
route.insert(0, curr)
curr = prev[curr]
route.insert(0, start)
#print(route)
path = " ".join(route)
print("Shortest route is length = %d: %s." % (dist[end], path))
|
f50064774f2f4e86e99689493ef1b888dfcafcfa | pranav165/nasa | /utils/location.py | 785 | 4.09375 | 4 | from enum import Enum
class Direction(Enum):
NORTH = 'N'
SOUTH = 'S'
EAST = 'E'
WEST = 'W'
class Location:
"""
Locations class to define location type object
"""
def __init__(self, latitude=None, longitude=None, name=None):
self.lat = latitude[:-1]
self.lat_direction = Direction(latitude[-1])
self.long_direction = Direction(longitude[-1])
self.long = longitude[:-1]
self.name = name
def __str__(self):
return "{0} with Latitude {1}-{2} and Longitude {3}-{4}".format(self.name, self.lat,
self.lat_direction.name,
self.long, self.long_direction.name)
|
6c142c8780b4e1e89f8e3dbb569e64bb832173ba | Poolfloaty/Python-Projects | /multi_dimensional_array.py | 3,071 | 4.1875 | 4 | #Program: multi_dimensional_array
#Author: Brent Lang
#Date: 09/15/20
#Purpose: Program tests the function main and the functions as commented below.
inStock = []
alpha = []
beta = []
gamma = [11, 13, 15, 17]
delta = [3, 5, 2, 6, 10, 9, 7, 11, 1, 8]
#setZero function initializes any one-dimensional list to 0.
def setZero(num):
list1 = [0] * num
return list1
#inputArray function prompts user to input 20 numbers and stores the numbers into list alpha.
def inputArray(alpha):
print("\n\nEnter 20 integers:")
for i in range(20):
alpha[i] = int(input())
#doubleArray function initializes the elements of beta to two times the corresponding elements in alpha.
def doubleArray(beta,alpha):
for i in range(20):
beta[i] = (alpha[i] * 2)
#copyGamma function sets the elements of the first row of inStock from gamma
#The remaining rows of inStock are set to three times the previous row of inStock.
def copyGamma(gamma,inStock):
for i in range(10):
inStock.append([])
for j in range(4):
if i == 0:
inStock[i].append(gamma[j])
else:
inStock[i].append(inStock[i - 1][j] * 3)
#copyAlphaBeta function stores alpha into the first five rows of inStock.
#beta is stored into the last five rows of inStock.
def copyAlphaBeta(alpha,beta,inStock):
k = 0
l = 0
for i in range(10):
for j in range(4):
if i < 5:
inStock[i][j] = alpha[k]
k += 1
else:
inStock[i][j] = beta[l]
l += 1
#printArray function prints any one-dimensional list using a single loop.
def printArray(array):
for i in range(0, len(array), 10):
print(*array[i:i + 10], sep = '\t')
#setInStock function prompts user to input the elements for the first column of inStock.
#The function then sets the elements in the remaining columns to two times the corresponding element in the previous column
#minus the corresponding element in delta.
def setInStock(inStock,delta):
print("\n\nEnter 10 Integers: ")
for i in range(10):
inStock[i][0] = int(input())
for i in range(1,4):
for j in range(10):
inStock[j][i] = (2 * inStock[j][i - 1]) - (delta[j])
def printColumns(inStock):
for i in range(10):
print(*inStock[i], sep = '\t')
def main():
alpha = setZero(20)
print("Alpha after initialization")
printArray(alpha)
beta = setZero(20)
inputArray(alpha)
print("\n\nAlpha after reading 20 numbers:")
printArray(alpha)
doubleArray(beta,alpha)
print("\n\nBeta after a call to doubleArray:")
printArray(beta)
copyGamma(gamma,inStock)
print("\n\ninStock after call to copyGamma:")
printColumns(inStock)
copyAlphaBeta(alpha,beta,inStock)
print("\n\ninStock after call to copyAlphaBeta:")
printColumns(inStock)
setInStock(inStock,delta)
print("\n\ninStock after call to setInStock:")
printColumns(inStock)
main() |
d271103e3b130a0bf1b5a564fe8b743cbb16f5e7 | kmtos/InsightDataEngineeringCodingChallenge | /src/prescription_drug_class_def.py | 7,735 | 3.890625 | 4 | import csv
import string
class prescription_drug_class(object):
def __init__(self, drug_list, index_last_name, index_first_name, index_drug_name, index_drug_price):
self.full_list = drug_list
self.INDEX_LNAME = index_last_name
self.INDEX_FNAME = index_first_name
self.INDEX_DNAME = index_drug_name
self.INDEX_PRICE = index_drug_price
def MergeSort(self, curr_list, indecies_to_sort, STRorNUM="STR"):
"""
This function follows the basic merge sort technique. It sorts based upon the ordering of the
elements specified in "indecies_to_sort", which are elements in the tuples contained in the list.
It does NOT combine terms if the compared elements are equal, but it is generalized to work with
numbers of strings, as specified in "STRorNUM".
"""
if len(curr_list) > 1:
mid = len(curr_list)//2
left_list = curr_list[:mid]
right_list = curr_list[mid:]
self.MergeSort(left_list, indecies_to_sort, STRorNUM=STRorNUM)
self.MergeSort(right_list, indecies_to_sort, STRorNUM=STRorNUM)
index_l = 0
index_r = 0
index_a = 0
length_l = len(left_list )
length_r = len(right_list)
while index_l < length_l and index_r < length_r:
if STRorNUM == "STR":
name_l = ''
name_r = ''
for i in indecies_to_sort:
name_l += str(left_list[ index_l][i])
name_r += str(right_list[index_r][i])
name_l = "".join(name_l.split())
name_r = "".join(name_r.split())
name_l = name_l.lower()
name_r = name_r.lower()
elif STRorNUM == "NUM":
name_l = 0
name_r = 0
for i in indecies_to_sort:
name_l += float(left_list[ index_l][i])
name_r += float(right_list[index_r][i])
if name_l > name_r:
curr_list[index_a] = right_list[index_r]
index_r += 1
else:
curr_list[index_a] = left_list[index_l]
index_l += 1
index_a += 1
while index_l < length_l:
curr_list[index_a] = left_list[index_l]
index_a += 1
index_l += 1
while index_r < length_r:
curr_list[index_a] = right_list[index_r]
index_a += 1
index_r += 1
def CombineDuplicates(self, indecies_to_check):
"""
This combines prices of like terms based upon the element indecies stated in "indecies_to_check".
"""
list_to_delete = []
for i in range(len(self.full_list)-1):
if i in list_to_delete: continue
j = i + 1
checkIfDiff = False
for ind in indecies_to_check:
if self.full_list[i][ind] != self.full_list[j][ind]:
checkIfDiff = True
while not checkIfDiff:
self.full_list[i] = (self.full_list[i][:self.INDEX_PRICE] +
(float(self.full_list[i][self.INDEX_PRICE]) + float(self.full_list[j][self.INDEX_PRICE]),) +
self.full_list[i][self.INDEX_PRICE+1:])
list_to_delete.append(j)
j += 1
for ind in indecies_to_check:
if self.full_list[i][ind] != self.full_list[j][ind]:
checkIfDiff = True
for i in reversed(list_to_delete):
del self.full_list[i]
def GetDrugPriceAndCountDict(self):
"""
This gets the drug purchase and count itotals in the form of a dict.
"""
curr_dname = self.full_list[0][self.INDEX_DNAME]
curr_dname = curr_dname.replace(" ", "__")
self.drug_totals_dict = {}
self.drug_totals_dict[curr_dname] = [0,0]
for row in self.full_list:
if row[self.INDEX_DNAME] == curr_dname:
self.drug_totals_dict[curr_dname][0] += 1
self.drug_totals_dict[curr_dname][1] += float(row[self.INDEX_PRICE] )
else:
curr_dname = row[self.INDEX_DNAME]
curr_dname = curr_dname.replace(" ", "__")
self.drug_totals_dict[curr_dname] = [1,float(row[self.INDEX_PRICE])]
def GetDrugPriceAndCountList(self):
"""
This gets the drug purchase and count totals in the form of a list.
"""
curr_dname = self.full_list[0][self.INDEX_DNAME]
self.drug_totals_list = []
totalPurchases = 0
countUnique = 0
for row in self.full_list:
if row[self.INDEX_DNAME] == curr_dname:
totalPurchases += float(row[self.INDEX_PRICE] )
countUnique += 1
else:
self.drug_totals_list.append( (curr_dname, countUnique, totalPurchases) )
curr_dname = row[self.INDEX_DNAME]
totalPurchases = float(row[self.INDEX_PRICE])
countUnique = 1
self.drug_totals_list.append( (curr_dname, countUnique, totalPurchases) )
def WriteSortedPersonList(self, outFileName, reverse=False):
"""
Writes out the sorted list of the data provided to a file.
"""
with open(outFileName, 'w') as sortedFile:
wr = csv.writer(sortedFile)
wr.writerow(["id","prescriber_last_name","prescriber_first_name","drug_name","drug_cost"])
if not reverse:
for row in self.full_list: wr.writerow(row)
else:
for row in reversed(self.full_list): wr.writerow(row)
def WriteDrugCountAndTotalDict(self, outFileName, reverse=False, decimals=False):
"""
Writes out the drug_totals_dict to a file specified. To loop
backwards, then enable the boolean option.
"""
with open(outFileName, 'w') as sortedFile:
wr = csv.writer(sortedFile)
wr.writerow(["drug_name","num_prescriber","total_cost"])
if not reverse:
for k,v in self.drug_totals_dict.items():
if decimals: wr.writerow( (str(k.replace("__"," ")), v[0], "{0:.2f}".format(v[1])) )
else: wr.writerow( (str(k.replace("__"," ")), v[0], "{0:.0f}".format(v[1])) )
else:
for k,v in reverse(self.drug_totals_dict.items()):
if decimals: wr.writerow( (str(k.replace("__"," ")), v[0], "{0:.2f}".format(v[1])) )
else: wr.writerow( (str(k.replace("__"," ")), v[0], "{0:.0f}".format(v[1])))
def WriteDrugCountAndTotalList(self, outFileName, reverse=False, decimals=False):
"""
Writes out the drug_totals_list to a file specified. To loop
backwards, then enable the boolean option.
"""
with open(outFileName, 'w') as sortedFile:
wr = csv.writer(sortedFile)
wr.writerow(["drug_name","num_prescriber","total_cost"])
if not reverse:
for row in self.drug_totals_list:
if decimals: wr.writerow( (row[0], row[1], "{0:.2f}".format(row[2])) )
else: wr.writerow( (row[0], row[1], "{0:.0f}".format(row[2])))
else:
for row in reversed(self.drug_totals_list):
if decimals: wr.writerow( (row[0], row[1], "{0:.2f}".format(row[2])) )
else: wr.writerow( (row[0], row[1], "{0:.0f}".format(row[2])) )
def ConvertDrugTotalDictToList(self):
"""
If the drug totals are already in dict form, this function
converts it to a list.
"""
self.drug_totals_list = []
for k,v in self.drug_totals_dict.items():
self.drug_totals_list.append( (k.replace("__"," "), v[0], v[1]) )
|
a424fa6e2522258e80d0284526a841202ed0a2d9 | Vaishnavi02-eng/InfyTQ-Answers | /PROGRAMMING FUNDAMENTALS USING PYTHON/Day2/Exercise7.py | 809 | 3.84375 | 4 | #PF-Exer-7
def calculate_total_ticket_cost(no_of_adults, no_of_children):
total_ticket_cost=0
final=0
#Write your logic here
Rate_per_Adult=37550.0
Rate_per_Child=Rate_per_Adult/3
service_ad = (Rate_per_Adult*7)/100
service_ch = (Rate_per_Child*7)/100
ticket_cost1=Rate_per_Adult + service_ad
ticket_cost2=Rate_per_Child + service_ch
final_cost1 = ticket_cost1-((ticket_cost1*10)/100)
final_cost2 = ticket_cost2-((ticket_cost2*10)/100)
cost1 = no_of_adults*final_cost1
cost2 = no_of_children*final_cost2
total_ticket_cost=cost1+cost2
return total_ticket_cost
#Provide different values for no_of_adults, no_of_children and test your program
total_ticket_cost=calculate_total_ticket_cost(1,2)
print("Total Ticket Cost:",total_ticket_cost)
|
0cb94a6782ceed0709216733f95d1581c5ebc821 | ao9000/tic-tac-toe-ai | /run_game.py | 7,054 | 3.796875 | 4 | """
Pygame based version of tic-tac-toe with minimax algorithm artificial intelligence (AI) game
"""
# UI imports
import pygame
import sys
from game_interface.color import color_to_rgb
from game_interface.templates import game_board, selection_screen, board_information, highlight_win
# Game logic imports
import random
from game.board import create_board, win_check, is_board_full, get_turn_number
from game_interface.helper_functions import bot_move_input_handler, human_move_input_handler, record_draw, record_win, human_input_selection_screen_handler
# Define screen size
width, height = 600, 600
def setup_game():
"""
Setup the pygame game window and tick rate properties
:return: type: tuple
Contains the pygame.surface and pygame.clock objects for the game
pygame.surface class is responsible for the the window properties such as the dimension and caption settings
pygame.clock class is responsible for the frame per second (fps) or tick rate of the game
"""
# Initialize module
pygame.init()
# Define screen dimensions
screen_size = (width, height)
screen = pygame.display.set_mode(screen_size)
# Define game window caption
pygame.display.set_caption("Tic Tac Toe")
# Define game clock
clock = pygame.time.Clock()
return screen, clock
def render_items_to_screen(screen, interface_items):
"""
Renders all the items in interface_items dictionary to the screen
:param screen: type: pygame.surface
The surface/screen of the game for displaying purposes
:param interface_items: type: dict
Dictionary containing all of the user interface (UI) items to be displayed
"""
# List to exclude rendering
exclude_list = [
'game_board_rects'
]
for key, value in interface_items.items():
if key not in exclude_list:
if isinstance(value, list):
for move in value:
if move:
move.draw_to_screen(screen)
else:
value.draw_to_screen(screen)
def post_game_delay():
"""
Forces the screen to update while adding a delay and clearing any events that were added during the delay.
Used for adding a delay between multiple tic-tac-toe games. This is to provide time for the player to react to what
is happening in the game.
"""
# Refresh screen & add delay
pygame.display.update()
# Caution, when wait is active, event gets stored in a queue waiting to be executed.
# This causes some visual input lag. Must clear the event queue after done with pygame.time.wait
pygame.time.wait(2000)
pygame.event.clear()
def main():
"""
The main function of the game.
Responsible for the setup of game window properties, creating players, scheduling scenes in the game, recording
player statistics and looping the game.
"""
# Setup game
screen, clock = setup_game()
# Create list of players
players = []
# Define whose turn
player = None
# Define stats recording
records = {
# Record turn number
'turn_num': 0,
# Record bot wins
'bot_win': 0,
# Record human wins
'human_win': 0,
# Record draws
'draw': 0
}
# Define screen states
intro = True
game = True
# Create a blank Tic Tac Toe board
board = create_board()
# Game loop
while True:
# tick rate
clock.tick(30)
mouse_position = pygame.mouse.get_pos()
mouse_clicked = False
for event in pygame.event.get():
# Break loop if window is closed
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Break loop if ESC key is pressed
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_clicked = True
# White background/clear previous objects
screen.fill(color_to_rgb("white"))
if intro:
# Draw selection screen
interface_items = selection_screen(screen, mouse_position)
render_items_to_screen(screen, interface_items)
# Handle user input
if mouse_clicked:
human_input_selection_screen_handler(interface_items, players, mouse_position)
# Proceed to next screen if user selected a choice & assign players
if players:
# Unpack players
bot, human = players[0], players[1]
# Random starting player
player = random.choice(players)
# Move on to game screen
intro = False
elif game:
# Game scene
# Draw board information
interface_items = board_information(screen, records)
render_items_to_screen(screen, interface_items)
# Draw tic tac toe board
interface_items = game_board(screen, board, players)
render_items_to_screen(screen, interface_items)
# Check if game is finished
if win_check(board):
# Game is finished
# Highlight the winning row
interface_items = highlight_win(interface_items, board)
render_items_to_screen(screen, interface_items)
# Add delay
post_game_delay()
# Record stats
record_win(player, records)
# Reset board
board = create_board()
# Next game, random starting turn again
player = random.choice(players)
elif is_board_full(board):
# Game is finished
# Add delay
post_game_delay()
# Record stats
record_draw(records)
# Reset board
board = create_board()
# Next game, random starting turn again
player = random.choice(players)
else:
# Game not finished
# Make a move (bot/human)
if player.bot:
# Bot turn
bot_move_input_handler(board, bot)
else:
if mouse_clicked:
# Human turn
human_move_input_handler(board, interface_items, mouse_position, human)
# Cycle turns
if get_turn_number(board) != records["turn_num"]:
if not win_check(board) and not is_board_full(board):
# Subsequent turns
player = human if player.bot else bot
records["turn_num"] = get_turn_number(board)
# Update screen
pygame.display.update()
if __name__ == '__main__':
main()
|
aff8ce16d908f8ebbc80cee09b0440206568ff1e | vinod-boga/019-check-key-existence | /build.py | 164 | 3.65625 | 4 | def solution(d1,Key1):
for key in d1:
if key == Key1:
return True
else:
return False
print solution({'abc':20,'efg':10},'efg')
|
27437bc7e6230065b6038d7e962dbd3b959564e5 | mini-monstar/Array-practises | /remove_duplicates.py | 94 | 3.859375 | 4 | A = [1, 2, 1, 2, 3, 4, 5]
B = []
for i in A:
if i not in B:
B.append(i)
print(B)
|
6e1f8b00a781dcafe8be6d0062be68a5712b517b | evorontsova/LeetCode | /028/code.py | 1,418 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 11 2021
@author: Evgeniya Vorontsova
LC Problem 28 Implement strStr()
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0
Constraints:
0 <= haystack.length, needle.length <= 5 * 104
haystack and needle consist of only lower-case English characters.
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
if haystack == "":
return -1
rez = -1
len_needle = len(needle)
len_haystack = len(haystack)
for i in range(0, len_haystack):
if haystack[i: min([i + len_needle, len_haystack])] == needle:
rez = i
break
return rez
# Tests
s1 = "wwwwfaf3"
s2 = "faf"
class_instance = Solution()
rez = Solution.strStr(class_instance, s1, s2)
print(rez)
|
da31e7c75c044753f357a497550740616b68a3e0 | renatanesio/guppe | /heranca.py | 2,002 | 3.921875 | 4 | """
POO - Herança (Inheritance)
A ideia de herança é reaproveitar código, e também extender as classes.
OBS: Com a herança, a partir de uma classe existente, extende-se outra classe
que passa a herdar atributos e métodos da classe herdade.
Cliente
- nome
- sobrenome
- cpf
- renda
Funcionário
- nome
- sobrenome
- cpf
- matrícula
OBS: quando uma classe herda de outra classe, ela herda todos os atributos e
métodos da classe herdada.
Quando uma classe herda de outra classe, a classe herdada é conhecida por:
- Super Classe
- Classe Mãe
- Classe Pai
- Classe Base
- Classe Genérica
Quando uma classe herda de outra classe, ela é chamada:
- Sub Classe
- Classe Filha
- Classe Específica
Sobrescrita de método ocorre quando sobrescrevemos um método presente na super classe
em classes filhas.
"""
class Pessoa:
def __init__(self, nome, sobrenome, cpf):
self.__nome = nome.title()
self.__sobrenome = sobrenome.title()
self.__cpf = cpf
def nome_completo(self):
return f'{self.__nome} {self.__sobrenome}'
class Cliente(Pessoa):
"""Cliente herda de Pessoa"""
def __init__(self, nome, sobrenome, cpf, renda):
Pessoa.__init__(self, nome, sobrenome, cpf) # Forma incomum de acesso
self.__renda = renda
class Funcionario(Pessoa):
"""Funcionário herda de Pessoa"""
def __init__(self, nome, sobrenome, cpf, matricula):
super().__init__(nome, sobrenome, cpf)
self.__matricula = matricula
def nome_completo(self):
print(super().nome_completo())
return f'Funcionário: {self.__matricula}. Nome: {self._Pessoa__nome}'
cliente1 = Cliente('Angelina', 'Jolie', '123.456.789-10', 5000.00)
funcionario1 = Funcionario('Brad', 'Pitt', '987.654.321-00', 1234)
print(cliente1.nome_completo())
print(funcionario1.nome_completo())
print(cliente1.__dict__)
print(funcionario1.__dict__)
# Sobrescrita de método |
a8357393cad296fb8be3c7b041a90209e7a65301 | nathanlo99/dmoj_archive | /done/ccc12j2.py | 313 | 3.78125 | 4 | import sys
data = []
for _ in range(4):
data.append(int(input()))
if data[0] > data[1] > data[2] > data[3]:
print("Fish Diving")
elif data[0] < data[1] < data[2] < data[3]:
print("Fish Rising")
elif data[0] == data[1] == data[2] == data[3]:
print("Fish At Constant Depth")
else:
print("No Fish") |
e690e2ca91eb042557c0d36e8a67cc181aa4842a | vitdanilov/python_devops | /dev/4/task4_6.py | 1,344 | 4.03125 | 4 | # 6. Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
#
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечным.
# Необходимо предусмотреть условие его завершения.
#
# Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл.
# Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено.
from itertools import count, cycle
first_list =[]
for el in count(3):
if el > 10:
break
else:
first_list.append(el)
print(first_list)
с = 0
second_list =[]
for el in cycle(first_list):
if с > 20:
break
с += 1
second_list.append(el)
print(second_list)
|
8083cd108e9d0bfe05c9b3fd8c37fbcfb151b590 | Akhilesh09/MS_Projects | /Deep Learning - Individual Projects/DL_HW2/ResNet/Network.py | 8,381 | 3.5625 | 4 | import tensorflow as tf
"""This script defines the network.
"""
class ResNet(object):
def __init__(self, resnet_version, resnet_size, num_classes,
first_num_filters):
"""Define hyperparameters.
Args:
resnet_version: 1 or 2. If 2, use the bottleneck blocks.
resnet_size: A positive integer (n).
num_classes: A positive integer. Define the number of classes.
first_num_filters: An integer. The number of filters to use for the
first block layer of the model. This number is then doubled
for each subsampling block layer.
"""
self.resnet_version = resnet_version
self.resnet_size = resnet_size
self.num_classes = num_classes
self.first_num_filters = first_num_filters
def __call__(self, inputs, training):
"""Classify a batch of input images.
Architecture (first_num_filters = 16):
layer_name | start | stack1 | stack2 | stack3 | output
output_map_size | 32x32 | 32×32 | 16×16 | 8×8 | 1x1
#layers | 1 | 2n/3n | 2n/3n | 2n/3n | 1
#filters | 16 | 16(*4) | 32(*4) | 64(*4) | num_classes
n = #residual_blocks in each stack layer = self.resnet_size
The standard_block has 2 layers each.
The bottleneck_block has 3 layers each.
Example of replacing:
standard_block conv3-16 + conv3-16
bottleneck_block conv1-16 + conv3-16 + conv1-64
Args:
inputs: A Tensor representing a batch of input images.
training: A boolean. Used by operations that work differently
in training and testing phases.
Returns:
A logits Tensor of shape [<batch_size>, self.num_classes].
"""
outputs = self._start_layer(inputs, training)
if self.resnet_version == 1:
block_fn = self._standard_block_v1
else:
block_fn = self._bottleneck_block_v2
for i in range(3):
filters = self.first_num_filters * (2**i)
strides = 1 if i == 0 else 2
outputs = self._stack_layer(outputs, filters, block_fn, strides, training)
outputs = self._output_layer(outputs, training)
return outputs
################################################################################
# Blocks building the network
################################################################################
def _batch_norm_relu(self, inputs, training):
"""Perform batch normalization then relu."""
### YOUR CODE HERE
x_norm = tf.layers.batch_normalization(inputs, training=training)
outputs=tf.nn.relu(x_norm)
### END CODE HERE
return outputs
def _start_layer(self, inputs, training):
"""Implement the start layer.
Args:
inputs: A Tensor of shape [<batch_size>, 32, 32, 3].
training: A boolean. Used by operations that work differently
in training and testing phases.
Returns:
outputs: A Tensor of shape [<batch_size>, 32, 32, self.first_num_filters].
"""
### YOUR CODE HERE
# initial conv1
initial_conv1=tf.layers.Conv2D(filters=self.first_num_filters, kernel_size=(3,3), strides=(1,1),padding="same")
outputs=initial_conv1(inputs)
### END CODE HERE
# We do not include batch normalization or activation functions in V2
# for the initial conv1 because the first block unit will perform these
# for both the shortcut and non-shortcut paths as part of the first
# block's projection.
if self.resnet_version == 1:
outputs = self._batch_norm_relu(outputs, training)
return outputs
def _output_layer(self, inputs, training):
"""Implement the output layer.
Args:
inputs: A Tensor of shape [<batch_size>, 8, 8, channels].
training: A boolean. Used by operations that work differently
in training and testing phases.
Returns:
outputs: A logits Tensor of shape [<batch_size>, self.num_classes].
"""
# Only apply the BN and ReLU for model that does pre_activation in each
# bottleneck block, e.g. resnet V2.
if self.resnet_version == 2:
inputs = self._batch_norm_relu(inputs, training)
### YOUR CODE HERE
out_pool=tf.layers.average_pooling2d(inputs,pool_size=8,strides=1)
out_conv=tf.layers.Conv2D(filters=self.num_classes, kernel_size=(1,1), strides=(1,1))
outputs=out_conv(out_pool)
outputs=tf.reshape(outputs,[-1,self.num_classes])
### END CODE HERE
return outputs
def _stack_layer(self, inputs, filters, block_fn, strides, training):
"""Creates one stack of standard blocks or bottleneck blocks.
Args:
inputs: A Tensor of shape [<batch_size>, height_in, width_in, channels].
filters: A positive integer. The number of filters for the first
convolution in a block.
block_fn: 'standard_block' or 'bottleneck_block'.
strides: A positive integer. The stride to use for the first block. If
greater than 1, this layer will ultimately downsample the input.
training: A boolean. Used by operations that work differently
in training and testing phases.
Returns:
outputs: The output tensor of the block layer.
"""
filters_out = filters * 4 if self.resnet_version == 2 else filters
def projection_shortcut(inputs):
### YOUR CODE HERE
shortcut_out=tf.layers.Conv2D(filters=filters_out, kernel_size=(1,1), strides=strides)
result= shortcut_out(inputs)
return result
### END CODE HERE
### YOUR CODE HERE
# Only the first block per stack_layer uses projection_shortcut
block_input=inputs
for i in range(self.resnet_size):
if(i==0):
block_input=block_fn(block_input,filters,training,projection_shortcut,strides)
else:
block_input=block_fn(block_input,filters,training,None,1)
outputs=block_input
### END CODE HERE
return outputs
def _standard_block_v1(self, inputs, filters, training, projection_shortcut, strides):
"""Creates a standard residual block for ResNet v1.
Args:
inputs: A Tensor of shape [<batch_size>, height_in, width_in, channels].
filters: A positive integer. The number of filters for the first
convolution.
training: A boolean. Used by operations that work differently
in training and testing phases.
projection_shortcut: The function to use for projection shortcuts
(typically a 1x1 convolution when downsampling the input).
strides: A positive integer. The stride to use for the block. If
greater than 1, this block will ultimately downsample the input.
Returns:
outputs: The output tensor of the block layer.
"""
shortcut = inputs
if projection_shortcut is not None:
### YOUR CODE HERE
shortcut=projection_shortcut(shortcut)
### END CODE HERE
### YOUR CODE HERE
block_1=tf.layers.Conv2D(filters=filters, kernel_size=(3,3), strides=strides,padding="same")
batch_norm_relu_out=self._batch_norm_relu(block_1(inputs),training)
block_2=tf.layers.Conv2D(filters=filters, kernel_size=(3,3),padding="same")
batch_norm_out = tf.layers.batch_normalization(block_2(batch_norm_relu_out), training=training)
batch_norm_out=tf.add(shortcut,batch_norm_out)
outputs=tf.nn.relu(batch_norm_out)
### END CODE HERE
return outputs
def _bottleneck_block_v2(self, inputs, filters, training, projection_shortcut, strides):
"""Creates a bottleneck block for ResNet v2.
Args:
inputs: A Tensor of shape [<batch_size>, height_in, width_in, channels].
filters: A positive integer. The number of filters for the first
convolution. NOTE: filters_out will be 4xfilters.
training: A boolean. Used by operations that work differently
in training and testing phases.
projection_shortcut: The function to use for projection shortcuts
(typically a 1x1 convolution when downsampling the input).
strides: A positive integer. The stride to use for the block. If
greater than 1, this block will ultimately downsample the input.
Returns:
outputs: The output tensor of the block layer.
"""
### YOUR CODE HERE
shortcut = inputs
if projection_shortcut is not None:
### YOUR CODE HERE
shortcut=projection_shortcut(shortcut)
batch_norm_relu_out=self._batch_norm_relu(inputs,training)
block_1=tf.layers.Conv2D(filters, (1,1), strides=strides,padding="same")
batch_norm_relu_out=self._batch_norm_relu(block_1(batch_norm_relu_out),training)
block_2=tf.layers.Conv2D(filters, (3,3), strides=1,padding="same")
batch_norm_relu_out=self._batch_norm_relu(block_2(batch_norm_relu_out),training)
block_3=tf.layers.Conv2D(filters*4, (1,1), strides=1,padding="same")
outputs=tf.add(shortcut,block_3(batch_norm_relu_out))
### END CODE HERE
return outputs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.