blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b4140e40ffe4ca4da77c3549db94e5b156d85ed1 | AlirezaTeimoori/Assignment_3b | /pizza_price_calculator.py | 2,264 | 4.0625 | 4 | #Created by: Alireza Teimoori
#Created on: 6 Oct 2017
#Created for: ICS3UR-1
#Lesson: Asssignment 3b
# This program calculates pizza price
# user is allowed to choose from 2 size
# of pizzas and 1 to 4 toppings
# app calculates sub total, HST, Final Total
import ui
### Variables and Constants
pizza_size = None
#print(pizza_size)
topping_number = 0
#print(topping_number)
HST = 1.13
sub_total = 0
added_hst = 0
final_total = 0
pizza_cost = 0
topping_cost = 0
if pizza_size == 'Large':
pizza_cost = 6
elif pizza_size == 'Extra Large':
pizza_cost = 10
def large_button_touch_up_inside(sender):
#changes pizza_size variable to Large
global pizza_size
global pizza_cost
pizza_size = 'Large'
pizza_cost = 6
#print(pizza_size)
view['checking_label'].text = "Your pizza is "+ pizza_size
def extra_large_button_touch_up_inside(sender):
#changes pizza_size variable to Extra Large
global pizza_size
global pizza_cost
pizza_size = 'Extra Large'
pizza_cost = 10
#print(pizza_size)
view['checking_label'].text = "Your pizza is "+ pizza_size
def confirm_touch_up_inside(sender):
# changes topping_number value to what ever user has entred
global topping_number
topping_number = int(view['topping_textfield'].text)
#print(topping_number)
if 0 <= topping_number <= 4:
view['checking_label'].text = "Your pizza is "+ pizza_size +" with "+str(topping_number)+" topping(s)"
else:view['checking_label'].text = "You can only choose a number between 0 and 4"
def calculate_button_touch_up_inside(sender):
global sub_total
global added_hst
global final_total
if 0 < topping_number <= 4 :
global topping_cost
topping_cost = 1+((topping_number-1)*0.75)
elif topping_number == 0:
topping_cost = 0
sub_total = pizza_cost+topping_cost
added_hst = (HST*(sub_total))-sub_total
final_total = HST*(sub_total)
view['sub_total_answer_label'].text = "${:,.2f}".format(sub_total)
view['hst_answer_label'].text = "${:,.2f}".format(added_hst)
view['final_total_answer_label'].text = "${:,.2f}".format(final_total)
view = ui.load_view()
view.present('sheet')
|
6073062969ef14f41dcad4e40440fc09395f8690 | ermeksnow/geekbrains-python-homework | /example4-06.py | 769 | 3.59375 | 4 | #задача 6.1
def int_1(i):
from itertools import count
list_one = []
print('число начала списка',i)
for x in count(i):
if x > 10:
break
else:
list_one.append(x)
print(list_one)
int_1(6)
#задача 6.2
def int_2(repeat):
from itertools import cycle
lisi_int_2=[1,2,3,4,5,6,7,8,9,0]
list_final=[]
i=1
print(repeat,'количество повторений цикла')
for x in cycle(lisi_int_2):
if i< repeat*len(lisi_int_2)+1: # +1 добавлена чтобы уровнять количестро индксов в len(lisi_int_2)
list_final.append(x)
i+=1
else:
break
print(list_final)
int_2(3)
|
6b73359237accf47bfed47a7e42c90e828da44af | skinan/Competative-Programming-Problems-Solutions-Using-Python | /141A.py | 570 | 4 | 4 | # CodeForces
# 141A - Amusing Joke
def main():
s1 = input() # First String.
s2 = input() # Second String.
s3 = input() # Third String.
z = []
for i in s1:
z.append(ord(i)) # Make a list with ASCII code of each character of string.
for i in s2:
z.append(ord(i)) # Append to that list with ASCII code of each character of string.
z.sort()
check = []
for i in s3:
check.append(ord(i))
check.sort()
if z == check:
print("YES")
else:
print("NO")
if __name__ == "__main__":
main()
|
eddf351952407920d8f57caf5bcebc1092a95e3c | Piyush-Ranjan-Mishra/python | /Machine Learning & AI/randomForrest.py | 1,234 | 3.8125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Next, download the iris dataset from its weblink as follows −
path = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
# assign column names to the dataset
headernames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']
# dataset
dataset = pd.read_csv(path, names=headernames)
dataset.head()
# Data Preprocessing
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
# training data and testing data −
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)
# train the model
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators=50)
classifier.fit(X_train, y_train)
# prediction.
y_pred = classifier.predict(X_test)
# print the results
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
result = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(result)
result1 = classification_report(y_test, y_pred)
print("Classification Report:",)
print (result1)
result2 = accuracy_score(y_test,y_pred)
print("Accuracy:",result2) |
9f82c6f05b1c96c177c2da4294f991b6b945d5c7 | Piyush-Ranjan-Mishra/python | /Machine Learning & AI/logisticRegression.py | 690 | 3.625 | 4 | Import sklearn
from sklearn import datasets
from sklearn import linear_model
from sklearn import metrics
from sklearn.model_selection import train_test_split
# load dataset
digits = datasets.load_digits()
# the feature matrix(X) and response vector(y)
X = digits.data
y = digits.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)
# object of logistic regression
digreg = linear_model.LogisticRegression()
# train the model by using the training sets as follows −
digreg.fit(X_train, y_train)
print the accuracy of the model as follows −
print("Accuracy of Logistic Regression model is:",
metrics.accuracy_score(y_test, y_pred)*100)
|
98b52e2171f3e4c8eb0da9df7e4e7130aa78169e | Gisset/Python-Essential | /Ejercicio 2 28-06-2021.py | 274 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 28 18:31:37 2021
@author: Gissela
"""
contar=input("Ingrese el # al que debo contar")
contar=int(contar)
contador=1
while True:
print(contador)
contador+=1
if contador>contar:
break
|
3603a3f0cb0129699c8d158756cebde3a860fa1c | obrunet/green_garden | /various_tests/test_config.py | 2,713 | 3.515625 | 4 | import configparser
import os.path
import requests
from requests.exceptions import HTTPError
CONFIG_FILE = 'config.ini'
GITHUB_BASE_URL = 'https://github.com/'
def get_user_infos():
"""Ask user for his/her username, name of the repo, and password"""
username = input('Enter your GitHub username: ')
repo = input('Enter the name of the repository where commits will be made: ')
return username, repo
def request_web_page(url):
"""Make a request for a specific URL, returns False if the web page doesn't exist"""
try:
req_response = requests.get(url)
req_response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
return False
except Exception as err:
print(f'Other error occurred: {err}')
return False
else:
return True
def verify_user_repo(username, repo):
"""Check if the username exists, and if repo is public or private"""
if request_web_page(GITHUB_BASE_URL + username):
if request_web_page(GITHUB_BASE_URL + username + '/' + repo):
print("This repository seems to be public. Advice: make it private so that commits can't be seen...")
return True
else:
print("This username doesn't exist... Recreating a config file")
return False
def create_config():
"""Create a configuration file based on the user inputs (username, repo's name"""
username, repo = get_user_infos()
verify_user_repo(username, repo)
config = configparser.ConfigParser()
config['Github'] = {'Username': username, 'Repo': repo}
with open(CONFIG_FILE, 'w') as configfile:
config.write(configfile)
print("Warning: do not share or release this configuration file publicly as it contents sensitive infos !")
def read_config():
"""Read the configuration file and return the infos it holds"""
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
if 'Github' not in config.sections():
print('No configuration for GitHub... The config file is malformed... Recreating it !')
return False, False
username, repo = config['Github']['Username'], config['Github']['Repo']
return username, repo
def main():
# if no configuration file, creates it
if not os.path.isfile(CONFIG_FILE):
create_config()
############################## add startup method to launch script
# check if the configuration is correct
username, repo = read_config()
if not username or not verify_user_repo(username, repo):
create_config()
# check if commits have already been made today, if not make some:
if __name__ == '__main__':
main()
|
3ad5b60af0b9b5b922b220daf75fb8ed95f85909 | pythondevelope/input | /input.py | 294 | 3.671875 | 4 | x = input("Your Name : ")
print("Welcome",x)
x = input("Years : ")
print("Your Years Is",x)
x = input("Do you like program? 0-10 :")
print("Thanks for rating")
print("Your Rating is",x)
x = input("End? : ")
print("Your answer is",x)
print("© 2018")
print("Thanks For Using my python app.")
|
f796dc8a77915b9bb581228ff929d80ac9198bab | RuiqingQiu/InterviewQuestions | /ZeroMatrix.py | 746 | 4.09375 | 4 | # 1.8 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0
def ZeroMatrix(matrix, M, N):
row_zero = []
column_zero = []
for i in range(0, M):
for j in range(0, N):
if matrix[i][j] == 0:
row_zero.append(j)
column_zero.append(i)
for i in row_zero:
zero_row(matrix,i)
for i in column_zero:
zero_column(matrix,i)
return matrix
def zero_row(matrix, row):
for i in range(0, len(matrix)):
matrix[i][row] = 0
def zero_column(matrix, column):
for i in range(0, len(matrix[0])):
matrix[column][i] = 0
testMatrix = [[1,2,3,4], [5,6,7,8],[9,10,11,0]]
print ZeroMatrix(testMatrix, 3, 4)
|
6ce4266cb2b1aca3b353b7c7a2de472418baad02 | alex-coupe/battleships | /src/board.py | 636 | 3.65625 | 4 |
class Board:
ROWS = ['A','B','C','D','E','F','G','H']
COLS = ['1','2','3','4','5','6','7','8']
board = list()
def init_board(self):
for x in self.COLS:
position = 0
for _y in range(8):
self.board.append(self.ROWS[position] + x)
position+=1
def print_board(self):
characters = 0
print(self.board[8])
for x in self.board:
if characters < 7:
print(x + ' ',end='')
characters+=1
else:
print(x)
characters = 0
|
735e48d42709bde3c0c662b1476feecd78976f6e | codejunkiekenya/andelabootcamp17 | /max_min.py | 225 | 3.78125 | 4 | def max_min():
old_list = []
for num in old_list:
new_list = []
min_value = min(old_list)
max_value = max(old_list)
new_list = new_list.append(min_value)
new_list = new_list.append(max_value)
return new_list
|
3d3f2208767ceb12d67aeeba29fe84adf605a6ee | marthaluka/Python4Bioinformatics2019 | /Scripts/lec07_ex03.py | 322 | 4.03125 | 4 | #!/usr/bin/python
import sys
def validSequence(infile):
valid = ['A','C','T','G']
isValid=True
for letter in infile:
if letter not in valid:
isValid = False
print("This DNA file contains non-convetional bases")
return isValid
infile = sys.argv[1]
validSequence(infile) |
63c6381dc1c727e69ba1d2d858d50ffa5c14ed92 | kateleecheng/Python-for-Everybody-Specialization | /1_Getting Started with Python/Week_7_Class.py | 381 | 3.78125 | 4 | #Week_7_Class.py
n=5
while n>0:
print(n)
n=n-1
print('Blastoff')
print(n)
while True:
line=input('>')
if line == 'done':
break
print(line)
print('Done!')
while True:
line=input('> ')
if line[0] == '#':
continue #back to while loop
if line =='done':
break #end the loop
print(line)
print('Done!')
|
8f98cdccca903730bcc7bea751d011e854b6bfae | kateleecheng/Python-for-Everybody-Specialization | /2_Python Data Structures/Week_1_Class2.py | 1,119 | 3.8125 | 4 | #Week_1_Class2.py
a='Hello'
b=a+'There'
print(b) #no space
c=a+' '+'There'
print(c) #have space
fruit='banana'
'n'in fruit
'm'in fruit
'nan'in fruit
if 'a' in fruit:
print('Found it')
greet='Hello Bob'
zap=greet.lower() #a lowercase copy wont change the original
print(zap)
print(greet)
print('Hi There'.lower())
fruit='banana'
pos=fruit.find('na')
print(pos)
#2 (start from 0)
aa=fruit.find('z')
print(aa)
#not found = -1
greet='Hello Bob'
nnn=greet.upper()
print(nnn)
www=greet.lower()
print(www)
greet="Hello Bob"
nstr=greet.replace('Bob','Jane')
print(nstr)
nstr=greet.replace('o','X')
print(nstr)
greet=' Hello Bob '
print(greet.lstrip()) #remove space from left
print(greet.rstrip()) #remove space from right
print(greet.strip()) #remove space from both side
line='Please have a nice day'
line.startswith('Please')
#True
line.startswith('p')
#False
data='From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
atpos=data.find('@')
print(atpos) #21
sppos=data.find(' ',atpos) #data behind atpos
print(sppos) #31
host=data[atpos+1:sppos]
print(host)
|
d11903a89fb0387d128b95424184ea7c9748ab22 | kateleecheng/Python-for-Everybody-Specialization | /1_Getting Started with Python/Week_6_Asm.py | 306 | 3.671875 | 4 | #Week_6_Asm.py
hrs=input('Enter Hours:')
rate=input('Enter Rate:')
f_hrs=float(hrs)
f_rate=float(rate)
def computepay(f_hrs,f_rate):
if f_hrs>40:
Pay=40*f_rate+(f_hrs-40)*f_rate*1.5
else:
Pay=f_hrs*f_rate
return Pay
p=computepay(f_hrs,f_rate)
print("Pay", p)
|
8d8b1094ecc52d64728c656aea268e70968616ad | kateleecheng/Python-for-Everybody-Specialization | /2_Python Data Structures/Week_5_Class3.py | 678 | 4 | 4 | #Week_5_Class3.py
counts=dict()
print('Enter a line of the text')
line=input('')
words=line.split() #split into list of words
print('Words:', words)
print('Counting...')
for word in words:
counts[word]=counts.get(word,0)+1
print('Counts',counts)
counts={'chuck':1, 'fred':42,'jan':100}
for key in counts:
print(key,counts[key])
jjj={'chuck':1, 'fred':42,'jan':100}
print(list(jjj))
#['chuck', 'fred', 'jan']
print(jjj.keys())
#dict_keys(['chuck', 'fred', 'jan'])
print(jjj.values())
#dict_values([1, 42, 100])
print(jjj.items())
#dict_items([('chuck', 1), ('fred', 42), ('jan', 100)])
for aaa,bbb in jjj.items():
print(aaa,bbb)
|
c5eae2e88f6e8e9173e11e533822cdcadff1ce17 | w50103/python | /demo/mydef.py | 1,019 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
import math
def myfunction(param1, param2):
print("param1 is %s, param2 is %s" %(param1,param2))
return 'nb';
def my_abs( n):
if not isinstance(n, (float,int)):
raise TypeError("bad opend type")
if n >=0:
return n
else:
return -n
def checkType(n, type):
if ((type == 'string' )or (type == 'str')):
if not isinstance(n, str):
raise TypeError("you should user str")
elif (type == "number" or type == "num"):
if not isinstance(n, (float,int)):
raise TypeError("you shoule use num")
else:
print(" param n is checkparma, type: [str,string,num,number]")
return 'success';
def quadratic(a,b,c):
if(checkType(a, 'num') and checkType(b, 'num') and checkType(c, 'num')):
print("%sx + %sx + %s" % (a,b,c))
sqNum = b*b - 4*a*c;
x1 = (-b + math.sqrt(sqNum))
x2 = -b - math.sqrt(sqNum)
return x1,x2
else:
pass
|
437b78f280905868807dcad17e3f04bfdb4b7ce1 | w50103/python | /demo/if.py | 385 | 3.84375 | 4 | #!/bin/usr/env python3
# -*- coding: utf-8 -*-
weight = float(input("体重(KG): "))
height = float(input("身高(M): "))
res = weight/(height * height)
if res > 38:
mes = "太重了"
elif res > 25:
mes = "还好"
elif res > 18:
mes = "管肚子"
else:
mes = '不错'
print('身高: %s ,\n体重: %s ,\nBMI: %s, 测算结果是: %s\n' % (height, weight, res, mes)); |
657084794be0f8aaa92b09c0c79d4d301db245e8 | esbullington/cct | /cct/wifi.py | 3,102 | 3.5 | 4 | import time
import network
# the class starts a WiFi access point
class AccessPoint:
"""
Initialize a new WiFi access point
Notes:
Make sure that the password is not too short. Otherwise, an
OSError may occur while staring the access point.
"""
def __init__(self, access_point_ssid, access_point_password):
self.access_point_ssid = access_point_ssid
"""SSID string for access point"""
self.access_point_password = access_point_password
"""Password for access point"""
self.access_point = None
def start(self):
"""
Start the access point
"""
self.access_point = network.WLAN(network.AP_IF)
self.access_point.active(True)
self.access_point.config(essid=self.access_point_ssid,
password=self.access_point_password,
authmode=network.AUTH_WPA_WPA2_PSK)
def ip(self):
"""
returns an IP address of the access point
"""
if self.access_point is None:
raise Exception('Access point has not started!')
return self.access_point.ifconfig()[0]
class Connection:
"""
Initializes a connection to a WiFi network
..code-block::
from cct.wifi import Connection
wifi = Connection("ssid", "password")
wifi.connect()
"""
def __init__(self, ssid, password=None):
# check if ssid and password are specified
if not ssid:
raise Exception('ssid not set')
self.ssid = ssid
"""SSID for connection"""
self.password = password
"""Password for connection"""
self.nic = network.WLAN(network.STA_IF)
"""Connection NIC"""
def connect(self):
"""
Connect to the previously specified wi-fi network
"""
print('connecting to network: %s' % self.ssid)
self.nic.active(True)
if self.password is not None:
self.nic.connect(self.ssid, self.password)
else:
self.nic.connect(self.ssid)
attempt = 0
while attempt < 30 and not self.nic.isconnected():
time.sleep(1)
attempt = attempt + 1
print('still connecting ...')
if self.nic.isconnected():
print('connected')
else:
print('could not connect to WiFi')
def is_connected(self):
"""
Check if the connection is active
Returns:
bool: `True` if connection active, otherwise `False`
"""
return self.nic is not None and self.nic.active() and self.nic.isconnected()
def reconnect_if_necessary(self):
"""
Reconnect if necessary
"""
while not self.is_connected():
self.connect()
def disconnect(self):
"""
Disconnect
"""
print('disconnecting ...')
self.nic.disconnect()
self.nic.active(False)
def reconnect(self):
"""
Reconnect
"""
self.disconnect()
self.connect()
|
5c7188d2152ef27af0f67a29a65970031a4fabb2 | EchoSlam/data_structure | /chr03.py | 6,907 | 3.703125 | 4 | # -*- coding:utf-8 -*-
# !/usr/bin/python
"""
@author:yyx
@version: 1.0
@file: chr03.py
@time: 2019/4/30 16:20
"""
class ListNode:
def __init__(self, data=None, pred=None, succ=None):
self.data = data
self.pred = pred # 前
self.succ = succ # 后
class List:
def __init__(self):
self.header = ListNode() # 创建头部哨兵节点
self.trailer = ListNode() # 创建尾部哨兵节点
self.header.succ = self.trailer
self.header.pred = None
self.trailer.pred = self.header
self.trailer.succ = None
self._size = 0
def first(self):
if self._size:
return self.header.succ
else:
return None
def last(self):
if self._size:
return self.trailer.pred
else:
return None
def insertAsFirst(self, e):
self.insertAsSucc(self.header, e)
def insertAsLast(self, e):
self.insertAsPred(self.trailer, e)
def insertAsPred(self, p, e): # 作为前驱节点插入
n = ListNode(data=e, pred=p.pred, succ=p)
p.pred.succ = n
p.pred = n
self._size += 1
def insertAsSucc(self, p, e): # 作为后继节点插入
n = ListNode(data=e, pred=p, succ=p.succ)
p.succ.pred = n
p.succ = n
self._size += 1
def __contains__(self, item):
p = self.header.succ
while p != self.trailer:
if p == item:
return True
else:
p = p.succ
return False
def __getitem__(self, r):
p = self.first()
if not 0 <= r < self._size - 1:
raise ValueError('index error')
while r > 0:
p = p.succ
r -= 1
return p.data
def __len__(self):
return self._size
def size(self):
return self._size
def remove(self, p):
if p not in self:
raise ValueError('p not in List')
p.pred.succ = p.succ
p.succ.pred = p.pred
self._size -= 1
return p.data
def disordered(self): # 逆序对
n = 0
p = self.header.succ
while p != self.trailer.pred:
if p.succ.data >= p.data:
n += 1
p = p.succ
return n
def find(self, e, n, p): # 在无序列表内节点p(可能是trailer)的n个真前驱中,找到等于e的最后者
p = p.pred
while n > 0 and p != self.header:
if p.data == e:
return p
else:
p = p.pred
n -= 1
return None
def copyNodes(self, p, n): # 从p节点开始,往后复制n个节点
self.trailer.pred = self.header
self.header.succ = self.trailer
self._size = 0
while n:
if p.succ is None: # p为尾哨兵则退出
import warnings
warnings.warn('节点数量不足', DeprecationWarning)
break
self.insertAsLast(p.data)
p = p.succ
n -= 1
def clear(self):
self.trailer.pred = self.header
self.header.succ = self.trailer
self._size = 0
def deduplicate(self): # 无序链表去重
if self._size < 2:
return 0
old_size = self._size
p = self.header.succ
r = 0
while p != self.trailer:
q = self.find(p.data, r, p)
if q:
self.remove(q)
else:
r += 1
p = p.succ
return old_size - self._size
def traverse(self, visit=print): # 遍历
p = self.header.succ
while p != self.trailer:
visit(p.data)
p = p.succ
def uniquify(self): # 有序链表去重
if self._size < 2:
return 0
oldsize = self._size
p = self.first()
q = p.succ
while q != self.trailer:
if p.data != q.data:
p = q
else:
self.remove(q)
q = p.succ
return oldsize - self._size
def search(self, e, n, p): # 在有序列表内节点p(可能是trailer)的n个(真)前驱中,找到不小于e的最后者
assert 0 <= n < self._size
p = p.pred
while n >= 0:
if p == self.header:
break
if p.data <= e:
break
else:
p = p.pred
n -= 1
return p
def sort(self, p, n):
import random
s = [self.insertionSort, self.selectionSort, self.mergeSort]
f = random.choice(s)
f(p, n)
def insertionSort(self, p, n): # 对起始于位置p的n个元素排序
r = 0
assert 0 <= n <= self._size
while r < n:
temp = self.search(p.data, r, p)
self.insertAsSucc(temp, p.data)
p = p.succ
self.remove(p.pred)
r += 1
def seleectMax(self, p, n): # 从起始于位置p的n个元素中选出最大者
max_p = p
cur = p
while n > 0:
if cur == self.trailer:
break
if cur.data > max_p.data:
max_p = cur
cur = cur.succ
n -= 1
return max_p
def selectionSort(self, p, n): # :对起始于位置p癿n个元素排序
assert 0 <= n <= self._size
head = p.pred
tail = p
for i in range(n):
tail = tail.succ
while n > 0:
max_p = self.seleectMax(head.succ, n)
print(max_p.data, n)
self.insertAsPred(tail, self.remove(max_p))
tail = tail.pred
n -= 1
def merge(self, p, n, q, m): # 当前列表中自p起的n个元素,与列表中自q起的m个元素归并
pp = p.pred
while m > 0:
if n > 0 and p.data <= q.data: # p较小,则当前p位置不需要调整,直接后移到下一位置
p = p.succ
if q == p: # 前列表耗尽,直接退出
break
n -= 1
else:
q = q.succ # q较小,需要将q插入到p之前,q后移
self.insertAsPred(p, self.remove(q.pred))
if q.succ is None: # q到哨兵节点则退出
break
m -= 1
return pp.succ
def mergeSort(self, p, n): # 节点位置变化,直接按节点、节点数量去调用会导致排序失败,每次归并后更新节点位置,会多一个返回值,暂时不处理
if n < 2: return p
m = n >> 1
q = p
for i in range(m):
q = q.succ
p = self.mergeSort(p, m)
q = self.mergeSort(q, n - m)
return self.merge(p, m, q, n - m)
|
cac134a11deff81aac536108a181b2c44ca60471 | EchoSlam/data_structure | /chr05.py | 8,931 | 3.640625 | 4 | # -*- coding:utf-8 -*-
# !/usr/bin/python
"""
@author:yyx
@version: 1.0
@file: chr05.py
@time: 2019/5/30 15:30
"""
from chr04 import Stack, Queue
class BinNode:
def __init__(self, data=None, parent=None, lc=None, rc=None, height=0, color='R'):
self.data = data
self.parent = parent
self.lc = lc
self.rc = rc
self.height = height
self.npl = height
self.color = color
def size(self):
pass
def insertAsLC(self, e):
"""将数据e作为左节点插入"""
self.lc = BinNode(data=e, parent=self)
def insertAsRc(self, e):
"""将数据e作为右节点插入"""
self.rc = BinNode(data=e, parent=self)
def succ(self):
"""返回当前节点中序遍历的直接后继"""
s = self
if s.rc:
s = s.rc
while s.HasLChild():
s = s.lc
else:
while s.IsRChild():
s = s.parent
s = s.parent
return s
def travLevel(self, visit=print):
Q = Queue()
Q.enqueue(self)
while Q.size() != 0:
x = Q.dequeue()
visit(x.data)
if x.HasLChild(): Q.enqueue(x.lc)
if x.HasRChild(): Q.enqueue(x.rc)
def travPre(self, visit=print): # 递归版本先序遍历
S = Stack()
x = self
while True:
while x:
visit(x.data)
S.push(x.rc)
x = x.lc
if S.empty(): break
x = S.pop()
def travPreR(self, visit=print): # 递归版本先序遍历
if not self: return
visit(self.data)
if self.lc:
self.lc.travPreR(visit)
if self.rc:
self.rc.travPreR(visit)
def travIn(self, visit=print): # 递归版中序遍历
S = Stack()
x = self
while True:
while x:
S.push(x)
x = x.lc
if S.empty(): break
x = S.pop()
visit(x.data)
x = x.rc
def travIn2(self, visit=print): # 递归版中序遍历
S = Stack()
x = self
while True:
if x:
S.push(x)
x = x.lc
elif not S.empty():
x = S.pop()
visit(x.data)
x = x.rc
else:
break
def travIn3(self, visit=print): # 递归版中序遍历
backtrack = False # 标识是否需要回退
x = self
while True:
if not backtrack and x.HasLChild(): # 一直往左
x = x.lc
else:
visit(x.data)
if x.HasRChild():
x = x.rc
backtrack = False
else:
x = x.succ()
if not x: break
backtrack = True
def travInR(self, visit=print): # 递归版本中序遍历
if not self: return
if self.lc:
self.lc.travInR(visit)
visit(self.data)
if self.rc:
self.rc.travInR(visit)
def travPost(self, visit=print): # 递归版本后序遍历
S = Stack()
x = self
if x:
S.push(x)
while not S.empty():
if x.parent and S.top() != x.parent:
x = S.top()
while x:
if x.HasLChild:
if x.HasRChild: S.push(x.rc)
S.push(x.lc)
else:
S.push(x.rc)
x = S.top()
S.pop()
x = S.pop()
visit(x.data)
def travPostR(self, visit=print): # 递归版本后序遍历
if not self: return
if self.lc:
self.lc.travPostR(visit)
if self.rc:
self.rc.travPostR(visit)
visit(self.data)
def __lt__(self, other):
return self.data > other.data
def __eq__(self, other):
return self.data == other.data
def IsRoot(self):
"""是否是根节点"""
return not self.parent
def IsLChild(self):
"""是否是父节点的左孩子"""
return not self.IsRoot() and (self == self.parent.lc)
def IsRChild(self):
"""是否是父节点的右孩子"""
return not self.IsRoot() and (self == self.parent.rc)
def HasParent(self):
"""是否有父节点"""
return not self.IsRoot()
def HasLChild(self):
"""左节点是否存在"""
return self.lc
def HasRChild(self):
"""右节点是否存在"""
return self.rc
def HasChild(self):
"""是否还有子节点"""
return self.HasLChild() or self.HasRChild()
def HasBothChild(self):
"""是否有两个子节点"""
return self.HasLChild() and self.HasRChild()
def IsLead(self):
"""是否为叶结点"""
return not self.HasChild()
def sibling(self):
"""返回兄弟节点"""
return self.parent.rc if self.IsLChild() else self.parent.lc
def uncle(self):
"""返回叔叔节点"""
return self.parent.parent.rc if self.parent.IsLChild() else self.parent.parent.lc
def FromParentTo(self):
"""来自父亲的引用,即自己"""
if self.IsRoot():
return self
else:
if self.IsLChild():
return self.parent.lc
else:
return self.parent.rc
def tallerChild(self):
"""返回两颗子树中较高的子树"""
return self.lc if stature(self.lc) >= stature(self.rc) else self.rc
def stature(x: BinNode):
"""返回节点规模"""
if x:
return x.height
else:
return -1
class BinTree:
def __init__(self):
self._size = 0
self._root = None
@staticmethod
def updateHeight(x: BinNode):
x.height = 1 + max(stature(x.lc), stature(x.rc))
return x.height
@staticmethod
def updateHeightAbove(x: BinNode):
while x:
old = x.height
n = BinTree.updateHeight(x)
if old == n: # 节点高度无变化则该节点的父节点不再需要更新
break
x = x.parent
def size(self):
return self._size
def empty(self):
return not self._root
def root(self):
return self._root
def insertAsRoot(self, e):
self._size = 1
self._root = BinNode(data=e)
return self._root
def insertAsLC(self, x: BinNode, e): # 假设x的lc为空
self._size += 1
x.insertAsLC(e)
self.updateHeightAbove(x)
return x.lc
def insertAsRC(self, x, e):
self._size += 1
x.insertAsRc(e)
self.updateHeightAbove(x)
return x.rc
def attachAsLC(self, x: BinNode, T):
x.lc = T.root()
x.lc.parent = x
self._size += T.size()
self.updateHeightAbove(x)
T._root = None
return x
def attachAsRC(self, x, T):
x.rc = T.root()
x.rc.parent = x
self._size += T.size()
self.updateHeightAbove(x)
T._root = None
return x
def remove(self, x: BinNode):
if x.IsRoot():
x = None
else:
if x.IsLChild():
x.parent.lc = None
else:
x.parent.rc = None
self.updateHeightAbove(x.parent)
n = self.removeAt(x)
self._size -= n
return n
@staticmethod
def removeAt(x): # 计算删除的节点数
if not x:
return 0
n = 1 + BinTree.removeAt(x.lc) + BinTree.removeAt(x.rc)
return n
def secede(self, x):
if x.IsRoot():
x = None
else:
if x.IsLChild():
x.parent.lc = None
else:
x.parent.rc = None
self.updateHeightAbove(x.parent)
S = BinTree()
S._root = x
x.parent = None
S._size = x.size()
self._size -= S._size
return S
def travLevel(self):
if self._root:
self._root.travLevel()
def travPre(self):
if self._root:
self._root.travPre()
def travIn(self):
if self._root:
self._root.travIn()
def travPost(self):
if self._root:
self._root.travPostR()
def __eq__(self, other):
return self._root and other.root() and (self._root == other.root())
def __lt__(self, other):
return self._root and other.root() and (self._root > other.root())
def test():
bt = BinTree()
bt.insertAsRoot(1)
lc = bt.insertAsLC(bt.root(), 2)
lc = bt.insertAsLC(lc, 7)
rc = bt.insertAsRC(bt.root(), 3)
rc = bt.insertAsRC(rc, 3)
|
2239f466399276fa8976e0512fb4a956918fa661 | BRamamohan/python-notes | /python_practice/swap1.py | 709 | 3.5625 | 4 | #!/usr/bin/python
list1, list2 = [123, 'xyz'], [456, 'abc']
'''
print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
print (list1)
print (list2)
list3 = list2 + list1;
print (len(list3))
print (max(list3))
print (min(list3))
c=1,2,3
print (list(c))
list1.extend(list2)
print (list1.count(123))
list1.insert(1,556)
print (list1)
print (list1.pop())
list1.remove(123)
print (list1)
list1.reverse()
print (list1)
'''
list4=list1.copy()
print (list4)
tuple1=1,2,3
tuple2=4,5,6
#print (cmp(tuple1,tuple2))
dict1={'name':'ramu','age':12}
print (dict1)
dict1.clear()
print (dict1)
print (dict1.fromkeys(tuple1,10))
print (dict1.get('tr',"nver"))
print (dict.has_key(name))
|
4be76caa3f17cfb1385ec756d3187de5a9fc9bc7 | yaronlev9/Nand2Tetris-projects | /Jack-compiler/SymbolTable.py | 1,263 | 3.640625 | 4 | class SymbolTable:
"""
Symbol table for classes/subroutines
"""
def __init__(self, class_table=None):
"""
Ctor
_class_table: a list of all the symbol in the class
_symbols: a list of all the symbols in the subroutine
_counters: the counters of the different kinds
"""
self._class_table = class_table
self._symbols = []
self._counters = {'static': 0, 'field': 0, 'argument': 0, 'local': 0}
def get_counters(self):
"""
returns the counters
:return: self._counters
"""
return self._counters
def get_symbol(self, name):
"""
returns the symbol based on the name
:param name:
:return: symbol
"""
for symbol in self._symbols:
if symbol.get_name() == name:
return symbol
if self._class_table:
for symbol in self._class_table:
if name == symbol.get_name():
return symbol
def add_symbol(self, symbol):
"""
appends the symbol to the list of symbols
:param symbol:
:return:
"""
self._symbols.append(symbol)
|
27e5aa42643b7502884b3d46fe79354acf3e1d1c | tt-n-walters/saturday-advanced-python | /functional_programming/artist_labels_functional.py | 1,307 | 3.75 | 4 | import csv
import operator
from functools import reduce
def open_file(filename):
return open(filename, "r")
def create_tsv_reader(file):
return csv.reader(file, dialect="excel-tab")
def replace_hyphens(string):
if string == "-":
return "2020"
else:
return string
# return "2020" if string == "-" else string
# predicate function to keep the years in the data
def check_numbers(value):
return value.isdigit()
def reverse(a, b):
return b, a
def calculate_age(artist):
a = map(replace_hyphens, artist)
b = filter(check_numbers, a)
c = map(int, b)
d = reverse(*c)
e = reduce(operator.sub, d)
return e
def get_nationality(artist):
return artist[3]
def get_first(value):
return value[0]
def apply(function, value):
return function(value)
artists = create_tsv_reader(open_file("artists.tsv"))
column_names = next(artists)
ages = map(calculate_age, artists)
artists = create_tsv_reader(open_file("artists.tsv"))
column_names = next(artists)
nationalities = map(get_nationality, artists)
letters = map(get_first, nationalities)
letters = map(str.upper, letters)
labels = map(operator.add, *zip(map(str, ages), letters))
for label in labels:
print(label)
print(ages)
# currying -> partial functions |
d949a6cc812e77ab66ae356915dfc0ba2b0c866b | sane-nature/Basics | /nth_prime.py | 352 | 3.734375 | 4 | count=0
x=1
n=5
def prime(x):
c=0
for i in range (1,x+1):
if x%i==0:
c=c+1
if c==2:
return 1
else:
return 0
while count<=n:
count=count+prime(x)
if count==n:
break
x=x+1
print(count)
print("The",n,"th prime number is", x)
|
9563b2aeffb31ec541ac52870b7cb3e041662861 | gavinbarrett/Star_Solver | /src/reader.py | 870 | 3.6875 | 4 | import os
import sys
class Reader:
def __init__(self, f):
self.fileObj = self.open_file(f)
self.maze = self.read(self.fileObj)
#print(self.maze)
def valid(self, c):
''' Return true if character is valid '''
if c == '0' or c == '1':
return True
else:
return False
def open_file(self, f):
''' Return open file object '''
if os.path.isfile(f):
fObj = open(f, "r")
return fObj
else:
print('Could not open maze file ' + f)
sys.exit(1)
def read(self, fObj):
row = []
col = []
for line in fObj:
for c in line:
if self.valid(c):
row.append(int(c))
col.append(row)
row = []
fObj.close()
return col
|
bcb33f9ec9c08c28536d999a23a16632afd2da84 | Bearsintours/CS50 | /PSET6/crack.py | 773 | 3.875 | 4 | # import
import crypt
import sys
# prompt user for hashed password
if len(sys.argv) != 2:
print("Please enter valid password")
exit(code=1)
# store hashed password
hashed = sys.argv[1]
# create string with every letters of the alphabet lowercase and uppercase
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# iterate over letters in 4 loops to get all combination possible
for i in letters:
str = i
for j in letters:
str = i + j
for k in letters:
str = i + j + k
for l in letters:
str = i + j + k + l
# print password if found
if hashed == crypt.crypt(str, "50"):
print(f"Password: {str}")
exit(code=0)
|
df619117f7e0c33580fee5d1fe489f990419243d | YonatanEizenberg/Catan_Project | /client/Road.py | 2,215 | 3.890625 | 4 | import pygame
class Road(pygame.sprite.Sprite): # class for the Roads of the game
def __init__(self, p1, p2): # initialises the Road Object
pygame.sprite.Sprite.__init__(self)
x1, y1 = p1.location
x2, y2 = p2.location
location = ((x1 + x2) / 2, (y1 + y2) / 2)
self.location = location
self.id = (p1.id + p2.id) / 2
self.pointsId = [p1.id, p2.id]
self.canBuild = True
if x1 == x2:
self.slope = 4 # the slope will be used to choose the image of the road, there are 3 images
else:
s = (y1 - y2) / (x1 - x2)
if s > 0:
self.slope = 2
else:
self.slope = 3
self.image = pygame.image.load("../imgs/circle.png").convert_alpha() # In the beginning, there is an image
self.rect = self.image.get_rect(center=location) # of a circle instead of the Road
def build(self, sprites_group, roadsToBuild, color): # Builds a Road on the Road's Object for the Player
roadsToBuild.remove(self)
self.canBuild = False
print("changed image of road")
self.image = pygame.image.load(f"../imgs/{color}road{self.slope}.png").convert_alpha()
self.rect = self.image.get_rect(center=self.location)
sprites_group.add(self)
def build_opp(self, sprites_group, color): # Builds a Road on the Road's Object for an Opponent
self.image = pygame.image.load(f"../imgs/{color}road{self.slope}.png").convert_alpha()
self.rect = self.image.get_rect(center=self.location)
sprites_group.add(self)
self.canBuild = False
def find_close_available_points(self, points): # the function is receiving a list of all points
settsToBuild = [] # and returns a list of the neighbouring points
for point in points: # to the Road by their POINT ID that you can build on
if point.id in self.pointsId and point.canBuild and point not in settsToBuild:
settsToBuild += [point]
return settsToBuild |
f0edf436e1ca4e445f1b975f97c8a0348740b224 | Alekhyo/InfyTQ-Assignment | /Assignment 4: Mandatory - Level 2.py | 2,604 | 4 | 4 | #DSA-Assgn-4
# The Indian Cricket Board has decided to send its best players to ICC World Cup. They have chosen the best 11 players for the match.
# The players should be sent in for the batting based on their experience, i.e. the priority would be given to the player who has got the highest experience.
# At the last moment, the captain has decided that the player who has got the highest experience should bat at the 4th position.
# Use the Player class and players_list provided to implement the class Game as given in the class diagram.
# In the constructor of Game class, initialize players_list with list of players
# Display the name and experience of the players after sorting the players based on their experience(descending order)
# Display the name and experience of the players after moving the first player (0 index position) to the 4th (3 index position) position.
class Player:
def __init__(self,name,experience):
self.__name=name
self.__experience=experience
def get_name(self):
return self.__name
def get_experience(self):
return self.__experience
def __str__(self):
return(self.__name+" "+(str)(self.__experience))
#Implement Game class here
class Game:
def __init__(self,players_list):
self.__players_list=players_list
def sort_players_based_on_experience(self):
try:
self.__players_list.sort(key=lambda x:x.get_experience())
except:
return None
def shift_player_to_new_position(self, old_index_position, new_index_position):
try:
self.__players_list[old_index_position],self.__players_list[new_index_position]=self.__players_list[new_index_position],self.__players_list[old_index_position]
except:
return None
def display_player_details(self):
for player in self.__players_list:
print(player.get_name(),':',player.get_experience(),end='\n')
player1=Player("Dhoni",15)
player2=Player("Virat",10)
player3=Player("Rohit",12)
player4=Player("Raina",11)
player5=Player("Jadeja",13)
player6=Player("Ishant",9)
player7=Player("Shikhar",8)
player8=Player("Axar",7.5)
player9=Player("Ashwin",6)
player10=Player("Stuart",7)
player11=Player("Bhuvneshwar",5)
#Add different values to the list and test the program
players_list=[player1,player2,player3,player4,player5,player6,player7,player8,player9,player10,player11]
#Create object of Game class, invoke the methods and test your program
p=Game(players_list)
p.display_player_details()
|
69b8d384aa8dfe0b29e69e63ad7531e53faeef9d | catalindoja/Doja_Castro_Aqueducte_Prac2 | /aqueducte_greedy_iterative.py | 1,776 | 3.703125 | 4 | #!/usr/bin/env python3
'''Practica Aqueducte 1. David Castro i Catalin Doja'''
# encoding: utf-8
from __future__ import print_function
import aux_functions
def greedy_iterative(data_x, data_y, data_header):
'''Algorisme iteratiu que implementa greedy'''
total = 0
cost_mes_baix = 0
index_cost_baix = 0
for pos, _ in enumerate(data_x):
pos = index_cost_baix
for index, _ in enumerate(data_x):
# Si index > pos sabem que son els fills que s'han de visitar al arbre.
if index > pos:
if aux_functions.checks(data_x, data_y, data_header, pos, index, 1) is False:
# calculs dels costos.
cost_x = abs(data_x[pos] - data_x[index])
cost_y = (int(data_header[1]) - data_y[index])
cost_punt = int(data_header[3]) * cost_x * cost_x + cost_y * int(data_header[2])
# comprovacio cost mes baix
if cost_mes_baix > cost_punt or cost_mes_baix == 0:
cost_mes_baix = cost_punt
index_cost_baix = index
# suma dels costos i resetejar el cost mes baix per la seguent volta
if cost_mes_baix == 0 and pos != (len(data_x)-1):
return None
total = total + cost_mes_baix
cost_mes_baix = 0
cost_y = (int(data_header[1]) - data_y[0])
cost_primera_columna = cost_y * int(data_header[2])
total = cost_primera_columna + total
return total
if __name__ == "__main__":
DATA_HEADER = []
DATA_X = []
DATA_Y = []
aux_functions.load_file(DATA_HEADER, DATA_X, DATA_Y)
TEMP = greedy_iterative(DATA_X, DATA_Y, DATA_HEADER)
if TEMP is None:
print("impossible")
else:
print(TEMP)
|
9f84598c8ac6b52a6fbc29741fc3a40d32732897 | dmpark135/OOP-phrase-hunter-game | /phrase.py | 632 | 3.6875 | 4 |
class Phrase:
def __init__(self, phrase):
self.phrase = phrase.lower()
def display(self, guesses):
for letter in self.phrase:
if letter in guesses:
print(f"{letter} ", end = "")
else:
print('_', end= "")
def check_guess(self, guess):
return guess in self.phrase
def check_complete(self, gx):
won = True
for letter in self.phrase.replace(' ',''):
if letter not in gx:
won = False
return won
|
80977b223bc9a3e2f5b13b49d1c8af84add23b89 | af1-tech/Python-equation | /Ecuatii_ro.py | 6,233 | 4.09375 | 4 | print("Ecuatii si inecuatii ver 1.0")
import math
loop1 = 10
optiune1 = 10
def ecgr1():
a = 0
b = 0
c = 0
x = 0
z = 1
while z != 0:
a = float(input("Introduceti pe a: "))
if a == 0:
print("Valoarea lui a trebuie sa fie diferita de zero!")
elif a != 0:
z = 0;
b = float(input("Introduceti pe b: "))
c = float(input("Introduceti pe c: "))
x = (c - b) / a
return (x)
def ecgr2():
a = 0
b = 0
c = 0
d = 0
delta = 0
x1 = 0
x2 = 0
z = 1
deltac = 0
xa = 0
xb = 0
while z != 0:
a = float(input("Introduceti pe a: "))
if a == 0:
print("Valoarea lui a trebuie sa fie diferita de zero!")
elif a != 0:
z = 0;
b = float(input("Introduceti pe b: "))
c = float(input("Introduceti pe c: "))
d = float(input("Introduceti pe d: "))
delta = ((b * b) - 4 * a * (c - d))
if delta >= 0:
x1 = (-1 * b - math.sqrt(delta)) / (2 * a)
x2 = (-1 * b + math.sqrt(delta)) / (2 * a)
elif delta < 0:
deltac = -1 * delta
xa = (-1 * b) / (2 * a)
xb = (math.sqrt(deltac)) / (2 * a)
return (delta, x1, x2, xa, xb)
while loop1 != 0:
print("Alege o optiune: ")
print("1) Ecuatii")
print("2) Inecuatii")
print("0) Iesire")
optiune1 = int(input("Introduceti optiunea: "))
if optiune1 == 1:
loop2 = 10
optiune2 = 10
while loop2 != 0:
print("1) Ecuatii de gradul I")
print("2) Ecuatii de gradul II")
print("0) Iesire")
optiune2 = int(input("Introduceti optiunea: "))
if optiune2 == 1:
print("Model: aX + b = c")
print("X = ", ecgr1())
elif optiune2 == 2:
print("Model: aX", str(chr(178)), " + bX + c = d")
delta, x1, x2, xa, xb = ecgr2()
if delta < 0:
print("Ecuatia nu are solutii care sa apartina multimii numerelor reale (R)")
print("X1 = ", xa, " - ", xb, "i")
print("X2 = ", xa, " + ", xb, "i")
elif delta >= 0:
print("delta este:", delta)
print("X1 = ", x1)
print("X2 = ", x2)
elif optiune2 == 0:
loop2 = 0
elif optiune1 == 2:
loop3 = 10
optiune3 = 10
while loop3 != 0:
print("1) Inecuatii de gradul I")
print("2) Inecuatii de gradul II")
print("0) Iesire")
optiune3 = int(input("Introduceti optiunea: "))
if optiune3 == 1:
loop4 = 10
optiune4 = 10
while loop4 != 0:
print("1) Model aX + b < c")
print("2) Model aX + b <= c")
print("3) Model aX + b >= c")
print("4) Model aX + b > c")
print("0) Iesire")
optiune4 = int(input("Introduceti optiunea: "))
if optiune4 == 1:
print("x apartine intervalului ( - inf , +", ecgr1(), " )")
elif optiune4 == 2:
print("x apartine intervalului ( - inf , +", ecgr1(), " ]")
elif optiune4 == 3:
print("x apartine intervalului [ ", ecgr1(), " , inf )")
elif optiune4 == 4:
print("x apartine intervalului ( ", ecgr1(), " , inf )")
elif optiune4 == 0:
loop4 = 0
elif optiune3 == 2:
loop5 = 10
optiune5 = 10
while loop5 != 0:
print("1) Model aX", str(chr(178)), " + bX +c < d")
print("2) Model aX", str(chr(178)), " + bX +c <= d")
print("3) Model aX", str(chr(178)), " + bX +c >= d")
print("4) Model aX", str(chr(178)), " + bX +c > d")
print("0) Iesire")
optiune5 = int(input("Introduceti optiunea: "))
if optiune5 == 1:
delta, x1, x2 = ecgr2()
if delta < 0:
print("Inecuatia nu are solutii care sa apartina multimii numerelor reale (R)")
elif delta >= 0:
print("x apartine intervalului ( ", x1, " , ", x2, " )")
elif optiune5 == 2:
if delta < 0:
print("Inecuatia nu are solutii care sa apartina multimii numerelor reale (R)")
elif delta >= 0:
print("x apartine intervalului [ ", x1, " , ", x2, " ]")
elif optiune5 == 3:
if delta < 0:
print("Inecuatia nu are solutii care sa apartina multimii numerelor reale (R)")
elif delta >= 0:
if x1 <= x2:
print("x apartine intervalului ( - inf, ", x1, "] U [ ", x2, " )")
elif x1 > x2:
print("x apartine intervalului ( - inf, ", x2, "] U [ ", x1, " )")
elif optiune5 == 4:
if delta < 0:
print("Inecuatia nu are solutii care sa apartina multimii numerelor reale (R)")
elif delta >= 0:
if x1 <= x2:
print("x apartine intervalului ( - inf, ", x1, ") U ( ", x2, " )")
elif x1 > x2:
print("x apartine intervalului ( - inf, ", x2, ") U ( ", x1, " )")
elif optiune5 == 0:
loop5 = 0
elif optiune3 == 0:
loop3 = 0
elif optiune1 == 0:
loop1 = 0
print("La revedere!") |
0bca93ef94e7f35e959941e7dbb8e7dd6d2129e6 | pablomartinez/dailyprogrammer | /353/easy/closest_string.py | 317 | 3.546875 | 4 | def distance(s1, s2):
d = 0
for c1, c2 in zip(s1, s2):
if c1 != c2:
d += 1
return d
def closest(items):
distances = list()
for item in items:
distances.append([item, sum([distance(item, i) for i in items])])
c = min(distances, key=lambda d: d[1])
return c[0]
|
86405915fec857d56f34a713028b8a2638f88b2b | JulianPL/Non-Rectangular_Convolution | /nrconv/primes.py | 1,781 | 3.96875 | 4 | #!/usr/bin/python3
"""A module to create suitable primes for the NTT.
"""
from typing import List
import sympy
def create_power_of_two(number: int) -> int:
"""Creates the smallest power of two which is at least number."""
power = 1
while power < number:
power = power * 2
return power
def create_mod_prime(base: int, mod: int, min_prime: int = 0) -> int:
"""Creates a prime >= min_prime with prime % base == mod.
This algorithm might be improvable with an adapted sieve
of Eratosthenes: For details see the appendix of:
https://drops.dagstuhl.de/opus/volltexte/2020/11891/pdf/LIPIcs-STACS-2020-30.pdf
Also, random numbers might be helpful. For details see section 2.3 of:
https://epubs.siam.org/doi/pdf/10.1137/100811167
"""
prime_candidate = base + mod
if prime_candidate < min_prime:
diff_number_bases = (min_prime - prime_candidate + base - 1) // base
prime_candidate = prime_candidate + diff_number_bases * base
while not sympy.ntheory.primetest.isprime(prime_candidate):
prime_candidate = prime_candidate + base
return prime_candidate
def create_ntt_prime(list1: List[int], list2: List[int]) -> int:
"""Creates a suitable prime for the NTT.
The prime is of the form m*2^k + 1, where 2^k is the length of the NTT.
Furthermore, the prime is guaranteed to be big enough in order to
prevent underflows and overflows in the NTT.
"""
ntt_length = 2 * create_power_of_two(max(len(list1), len(list2)))
max_list1_abs = max(abs(max(list1)), abs(min(list1)))
max_list2_abs = max(abs(max(list2)), abs(min(list2)))
max_value = max_list1_abs * max_list2_abs * ntt_length + 1
prime = create_mod_prime(ntt_length, 1, max_value)
return prime
|
581ada565596befba44b95249a95a7c145f6385e | KristianMariyanov/PythonPlayground | /hack-bulgaria-course/python01/week1/n_dice_more.py | 577 | 4 | 4 | from random import randint as rand
def roll_dice():
print('Please enter number of dice sides:')
n = int(input())
sum = 0
print('Your first number is:')
first_number = rand(1, n)
sum += first_number
print(first_number)
print('Your second number is:')
second_number = rand(1, n)
sum += second_number
print(second_number)
print('Your third number is:')
third_number = rand(1, n)
sum += third_number
print(third_number)
print('Sum of all dice trows is:')
print(sum)
if __name__ == '__main__':
roll_dice()
|
326530c9ad4e37337ff0dc50f80a9084cb132cae | KristianMariyanov/PythonPlayground | /softuni-course/Lecture01/draw_chess_desk.py | 469 | 3.703125 | 4 | import turtle
side = 20
turtle.speed('fastest')
size = int(input())
for row in range(size):
for col in range(size):
if (col % 2 == 1 and row % 2 == 0) or (col % 2 == 0 and row % 2 == 1):
turtle.begin_fill()
for _ in range(4):
turtle.forward(side)
turtle.left(90)
turtle.end_fill()
turtle.forward(side)
turtle.up()
turtle.goto(0, row*20 + 20)
turtle.down()
turtle.exitonclick()
|
563976bc89231207545cadbea2b9ccf053d7c903 | MyHackInfo/My-Project | /Talk_To_Me.py | 325 | 3.796875 | 4 | #Hey i am narsi and you
print('Hey i am narsi ')
you=input('And you :')
print('\nNice to meet you {0}'.format(you))
age=int(input('How old are you?: '))
print('\nyou born in {0} its good'.format((2018-age)))
city=input('Where are you form ')
print('\nohh {0} i love it '.format(city))
a=input('\nok bye ')
print('ok bye ')
|
fe7e07d50bce5bfd98da40c4dd667a4a5280ffea | greenmoon55/robotics | /test2.py | 2,078 | 3.53125 | 4 | # % matplotlib inline
import scipy
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import spline
from math import *
def get_point(x, y, theta, steering, distance):
length = 20.
turn = tan(steering) * distance / length
radius = distance / turn
cx = x - (sin(theta) * radius)
cy = y + (cos(theta) * radius)
theta = (theta + turn) % (2.0 * pi)
x2 = cx + (sin(theta) * radius)
y2 = cy - (cos(theta) * radius)
return x2, y2, theta, steering, distance
def smoothly_print_points(x, y):
print "points:"
print x
print y
x = np.array(x)
y = np.array(y)
# xnew = np.linspace(x.min(), x.max(), 100)
# power_smooth = spline(x, y, xnew)
#
# print xnew
# print power_smooth
plt.plot(x, y)
# plt.show()
def print_path(x1, y1, theta1, steering, x2, y2, d, delta=0.1):
distance = 0
x, y, theta = x1, y1, theta1
x_print = [x1]
y_print = [y1]
while distance < d:
distance += delta
newx, newy, theta, steering, distance = get_point(x, y, theta1, steering, distance)
print newx, newy, theta, steering, distance
x_print.append(newx)
y_print.append(newy)
if x2 != x_print[-1] and y2 != y_print[-1]:
x_print.append(x2)
y_print.append(y2)
smoothly_print_points(x_print, y_print)
x, y, theta, steering, distance = 0., 0., 0., 0.2, 10.
x, y, theta = 0., 0., 0.
actions = [(0.2, 10.), (0.8, 40.), (-0.9, 20), (-0.5, 20), (-0.1, 30)]
# print_path(x, y, theta, steering, 29.5398545262, 4.52594328886, 20)
# for i in range(10):
# x, y, theta, steering, distance = get_point(x, y, theta, steering, distance)
# print x, y, theta, steering, distance
if __name__ == "__main__":
for action in actions:
x2, y2, theta2, steering, distance = get_point(x, y, theta, action[0], action[1])
print 'np'
print x2, y2, theta2, steering, distance
print_path(x, y, theta, action[0], x2, y2, distance)
x, y, theta = x2, y2, theta2
# plt.plot(args)
plt.show()
|
d202ee1b2a40990f05daa809841df5bab91c8c9e | sharatss/python | /techgig_practice/age.py | 1,547 | 4.15625 | 4 | """
Decide yourself with conditional statement (100 Marks)
This challenge will help you in clearing your fundamentals with if-else conditionals which are the basic part of all programming languages.
Task:
For this challenge, you need to read a integer value(default name - age) from stdin, store it in a variable and then compare that value with the conditions given below -
- if age is less than 10, then print 'I am happy as having no responsibilities.' to the stdout.
- if age is equal to or greater than 10 but less than 18, then print 'I am still happy but starts feeling pressure of life.' to the stdout.
- if age is equal to or greater than 18, then print 'I am very much happy as i handled the pressure very well.' to the stdout.
Input Format:
A single line to be taken as input and save it into a variable of your choice(Default name - age).
Output Format:
Print the sentence according to the value of the integer which you had taken as an input.
Sample Test Case:
Sample Input:
10
Sample Output:
I am still happy but starts feeling pressure of life.
Explanation:
The value of the variable is 10 and it comes under the condition that it equal to or greater than 10 but less than 18.
"""
def main():
# Write code here
age = int(input())
if age < 10:
print("I am happy as having no responsibilities.")
elif (age >=10 and age < 18):
print("I am still happy but starts feeling pressure of life.")
else:
print("I am very much happy as i handled the pressure very well.")
main()
|
d2b5c0a27b01ac2f63d6495436d9816453bd6241 | sharatss/python | /python_basics/decorators.py | 247 | 3.546875 | 4 | def my_decorator(func):
def func_wrapper(x):
print("If this is called, then the function is decorated")
res = func(x)
print(res)
return func_wrapper
@my_decorator
def next_number(x):
return x+1
next_number(1)
|
a9786b118e8755d0b94e2318f514f27d7eeaa263 | sharatss/python | /techgig_practice/special_numbers.py | 1,070 | 4.125 | 4 | """
Count special numbers between boundaries (100 Marks)
This challenge will help you in getting familiarity with functions which will be helpful when you will solve further problems on Techgig.
Task:
For this challenge, you are given a range and you need to find how many prime numbers lying between the given range.
Input Format:
For this challenge, you need to take two integers on separate lines. These numbers defines the range.
Output Format:
output will be the single number which tells how many prime numbers are there between given range.
Sample Test Case:
Sample Input:
3
21
Sample Output:
7
Explanation:
There are 7 prime numbers which lies in the given range.
They are 3, 5, 7, 11, 13, 17, 19
"""
def main():
# Write code here
lower_bound = int(input())
upper_bound = int(input())
count = 0
for number in range(lower_bound, upper_bound+1):
if number > 1:
for i in range(2, number):
if (number % i) == 0:
break
else:
count = count + 1
print(count)
main()
|
d571802de24c04e1e42fcb455f9daf3645703383 | sharatss/python | /python_basics/iterator.py | 166 | 3.890625 | 4 | cities = ["Berlin", "Vienna", "Zurich"]
iterator_obj = iter(cities)
print(iterator_obj)
print(next(iterator_obj))
print(next(iterator_obj))
print(next(iterator_obj))
|
7aeeb6b21cfb8a8f208af19d3eaf098be947d230 | dandani-cs/dotnetfdnchallenge | /codingchallenge2.py | 1,494 | 3.875 | 4 | # YOUTUBE LIVE CODING SESSION VID: https://youtu.be/D7w6_i5QwRY
class Student:
def __init__(self):
self.first_name = None
self.last_name = None
self.scores = []
def get_ave(self):
return sum(self.scores) / test_amt
def translate_grade(numeric_grade):
if numeric_grade >= 90:
return "A"
elif numeric_grade >= 80:
return "B"
elif numeric_grade >= 70:
return "C"
elif numeric_grade >= 60:
return "D"
else:
return "F"
students_list = []
student_amt = int(input("Enter number of students: "))
test_amt = int(input("Enter number of tests: "))
for i in range(student_amt):
student = Student()
student.last_name = input("Enter student {}'s last name: ".format(i + 1))
student.first_name = input("Enter student {}'s first name: ".format(i + 1))
for i in range(test_amt):
student.scores.append(int(input("Enter {} test {} score: ".format(
student.first_name + " " + student.last_name,
i + 1))))
students_list.append(student)
for student in students_list:
ave = student.get_ave()
print("{first} {last}: {average:.2f} - {letter}".format(
first = student.first_name,
last = student.last_name,
average = ave,
letter = translate_grade(ave)
))
|
43dfc72f955053bd2ffb7e44a0b0d2e32776c24f | alyhhbrd/CTI110- | /P2T1_SalesPrediction_AaliyahHubbard.py | 327 | 3.671875 | 4 | # Programming Exercise 2 - Sales Prediction
# 02162019
# CTI-110 P2T1 - Sales Prediction
# Aaliyah Hubbard
#
# get projected total sales:
total_sales = float(input('Enter the projected total sales: '))
# calculate profit as 23% of total:
profit = total_sales * 0.23
# display profit:
print('The profit is $', format(profit, ',.2f'))
|
e6c0effb856be274dabe3f6fc6913cf9a5d1440b | alyhhbrd/CTI110- | /P3HW1_ColorMixer_HubbardAaliyah.py | 1,225 | 4.3125 | 4 | # CTI-110
# P3HW1 - Color Mixer
# Aaliyah Hubbard
# 03032019
#
# Prompt user to input two of three primary colors; output as error code if input color is not primary
# Determine which secondary color is produced of two input colors
# Display secondary color produced as output
# promt user for input
print('LET`S MIX COLORS!')
print('We can make two primary colors into a secondary color.')
print('')
first_prime = input('Please enter first color: ')
sec_prime = input('Please enter second color: ')
print('')
# determine primary and secondary color values
sec_color1 = 'orange'
sec_color2 = 'purple'
sec_color3 = 'green'
# display output
if first_prime == 'red' and sec_prime == 'yellow' or first_prime == 'yellow' and sec_prime == 'red':
print('Hooray! We`ve made',sec_color1+'!')
print('')
elif first_prime == 'red' and sec_prime == 'blue' or first_prime == 'blue' and sec_prime == 'red':
print('Hooray! We`ve made',sec_color2+'!')
print('')
elif first_prime == 'blue' and sec_prime == 'yellow' or first_prime == 'yellow' and sec_prime == 'blue':
print('Hooray! We`ve made',sec_color3+'!')
print('')
else:
print('Oops! You did not enter a primary color... /: Please try again.')
print('')
|
3df487f269f633fcc9dcc27046ace41fc0c67209 | HenryCWong/MoDataNotebooks | /nobelPrize/untitled1.py | 580 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 19 12:35:55 2019
@author: cywon
"""
#given a pool of numbers create an 11 digit ID
def numOfIds(pool):
if len(pool) < 11:
return(0)
possible = int(len(pool)/11) #round down number of possible based on characters
numOfEights = findNumOfEights(pool)
print(numOfEights)
return(min([possible,numOfEights]))
# Write your code here
def findNumOfEights(pool):
eights = 0
for i in pool:
if i == "8":
eights += 1
return(eights)
print(numOfIds("888888555555555555555")) |
f2217abfe2d3051b8a38ec70597b86c68dcbb4bd | skinnyporkbun/cs114 | /greeting.py | 494 | 4.0625 | 4 | # Ask user to input name and age
from time import sleep
print("Hey stranger... Whats your name?")
sleep( 2 )
name = input("What is it? Tell me...hehe...:")
sleep( 1 )
#Ask user to input age
print("And how old are you?")
sleep( 1 )
age = int(input("Tell me, Tell me, I won't hurt you..."))
print("So you're called " + name + " and you're " + str(age) + " years old?")
sleep( 1 )
print("You'll be " + str((age +1)) + " next year then, won'tcha.")
sleep(10)
print("Why are you still here?")
|
b3be7d3a37103efc4b90ec491a65a6e196199a91 | skinnyporkbun/cs114 | /hello_list.py | 795 | 4.0625 | 4 | from time import sleep
print ("Hello world")
sleep( 2 )
print ("How are you feeling today from 1 to 10? 1 being bad and 10 being good.")
feeling = input("Tell me here: ")
# if feeling == "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" or "10":
if feeling == "skip":
print("Oh, okay. I won't ask you again then")
elif 0 < int(feeling) <= 5:
print ("Aww, well that sucks. Hope you feel better")
elif 6 <= int(feeling) <= 10:
print ("Well you seem be having a wonderful day! Hope it stays that way!")
# if feeling == "skip":
# print("Oh, okay. I won't ask you again then")
sleep( 3 )
print ("Unfortunately, I'll be shutting down now so I'll be seeing you around!")
sleep( 5 )
print("HELLO FUTURE ME :D - Voicemail left on Thursday, July 20th, 2017")
|
e310fbcbbeda57e3ad8e0575fc54d3e7038b9cf8 | s5046838/python | /test_ladder.py | 1,741 | 4 | 4 | import unittest # module for testing purposes
import word_ladder as wordladder # imports word_ladder.py files as wordladder
class testWord(unittest.TestCase): #creates a unittest class to initiate unit testing of functions
def test_file(self,file): # Tests whether the dictionary.txt file works
result = wordladder.file("dictionary.txt").read()
self.assertTrue(len(result) != 0)
def test_no_file(self): # Tests whether the dictionary.txt file does not work
result = wordladder.file('dictionary.txt').read()
self.assertFalse(len(result) == 0)
def test_build(self): # Tests whether the wrong file is being read
result = wordladder.build('empty.txt').read()
self.assertFalse(len(result) != 0)
def test_same(self): # Tests the inputs for the word ladder if they work
result = zip(1, 'one')
self.assertTrue(result != 0)
def test_same(self): # Tests the inputs for the word ladder if they don't
result = zip(1, 'one')
self.assertTrue(result == 0)
def test_wordRemove(self, path, word): # Tests if the removed word is in the word path
result = (path == word)
self.assertTrue(result)
def test_wordRemove(self, path, word): # Tests if the removed word isn't in the word path
result = (path != word)
self.assertFalse(result)
def test_wordRemove(self, path, word): # Tests if the user starting word is equal to the word user wants removed
result = (path != word[0])
self.assertTrue(result)
def test_userinput(self): #Checks if the user's input is not none
result = input("")
self.assertIsNotNone(result, '')
unittest.main(exit=False) # runs the tests |
92e0b5ade5b8f114237827037f7e4afe0ca9f85c | zhuyuecai/CtCI-6th-Edition-Python | /Chapter1/4_Palindrome Permutation/PalindromePermutation.py | 1,916 | 3.984375 | 4 | # O(N)
import unittest
"""
def pal_perm(phrase):
'''function checks if a string is a permutation of a palindrome or not'''
table = [0 for _ in range(ord('z') - ord('a') + 1)]
countodd = 0
for c in phrase:
x = char_number(c)
if x != -1:
table[x] += 1
if table[x] % 2:
countodd += 1
else:
countodd -= 1
return countodd <= 1
"""
def char_number(c):
a = ord('a')
z = ord('z')
A = ord('A')
Z = ord('Z')
val = ord(c)
if a <= val <= z:
return val - a
elif A <= val <= Z:
return val - A
return -1
#use dict and string.lower() can simplify the code a lot. and these are all build in function or primitive type. if you use python, you should accept this.
def check_odd(string):
ch_count = {}
odd_count = 0
string = string.lower()
for c in string:
if c in ch_count:
ch_count[c]+=1
else:
ch_count[c] = 1
for k in ch_count:
if ch_count[k]%2 != 0 :
odd_count+=1
return odd_count
def pal_perm(string):
string = string.replace(' ','')
length = len(string)
odd_count = check_odd(string)
re = False
if odd_count <= 1:
re = True
return re
class Test(unittest.TestCase):
'''Test Cases'''
data = [
('Tact Coa', True),
('jhsabckuj ahjsbckj', True),
('Able was I ere I saw Elba', True),
('So patient a nurse to nurse a patient so', False),
('Random Words', False),
('Not a Palindrome', False),
('no x in nixon', True),
('azAZ', True)]
def test_pal_perm(self):
for [test_string, expected] in self.data:
actual = pal_perm(test_string)
self.assertEqual(actual, expected)
if __name__ == "__main__":
unittest.main()
|
12c967001835fea6570908ee030e60b02f70bbe2 | QIBET/News | /app/models.py | 628 | 3.734375 | 4 | class Article:
'''
class used to create instances of Articles objects
'''
def __init__(self,id,author,title,description,urlToImage,publishedAt,url):
self.id = id
self.author = author
self.title = title
self.description = description
self.image = urlToImage
self.publishedAt = publishedAt
self.url = url
class Source:
'''
Class to create instances for source objects
'''
def __init__(self,id,name, description,url):
self.id = id
self.name = name
self.description = description
self.url = url |
df088fb37c67578d8327ad3fd90b2eebfaba85dd | dk4267/CS490 | /Lesson1Question3.py | 1,151 | 4.25 | 4 |
#I accidentally made this much more difficult than it had to be
inputString = input('Please enter a string') #get input
outputString = '' #string to add chars for output
index = 0 #keeps track of where we are in the string
isPython = False #keeps track of whether we're in the middle of the word 'python'
for char in inputString: #loop through input string by character
if inputString[index:index + 6] == 'python': #only enter if we encounter the word 'python'
outputString += 'pythons' #output 'pythons' instead of just the character
isPython = True #indicates that we're in the middle of the word 'python'
else:
if isPython: #if in a letter in 'python'
if char == 'n': #set isPython to false if at the end of the word
isPython = False
else: #if not inside the word 'python', just add the character to output, don't add char if in 'python'
outputString += char
index += 1 #incrememt index at the end of each iteration
print(outputString)
#here's the easy way...
outputString2 = inputString.replace('python', 'pythons')
print(outputString2) |
83cb74255b2448b7ae873aeb9cc3de3ba0e376b8 | sujineel/opensource | /fib.py | 156 | 3.8125 | 4 | #!/usr/bin/python2.7
f=[]
f.append(0)
f.append(1)
f.append(1)
n=input("Please number!")
for i in range(3, n+1):
f.append(f[i-1]+f[i-2])
print(f[n])
|
8444b3f7acd22ad7e0bdee4ce910e8c982b2e00b | piotroramus/PJN | /lab2/metrics.py | 2,575 | 3.515625 | 4 | def levenshtein_distance(s1, s2):
n, m = len(s1), len(s2)
if n == 0:
return m
if m == 0:
return n
matrix = [[0 for _ in xrange(n + 1)] for _ in xrange(m + 1)]
for i in xrange(m + 1):
matrix[i][0] = i
for i in xrange(n + 1):
matrix[0][i] = i
for i, c1 in enumerate(s1):
for j, c2 in enumerate(s2):
cost = int(c1 != c2)
matrix[j + 1][i + 1] = min(matrix[j][i + 1] + 1, matrix[j + 1][i] + 1, matrix[j][i] + cost)
return matrix[m][n]
def longest_common_subsequence_length(s1, s2):
""" Length of the longest common subsequence of strings s1 and s2"""
n, m = len(s1), len(s2)
c = [[0 for _ in xrange(n + 1)] for _ in xrange(m + 1)]
for i, c1 in enumerate(s1):
for j, c2 in enumerate(s2):
if c1 == c2:
c[j + 1][i + 1] = c[j][i] + 1
elif c[j + 1][i] >= c[j][i + 1]:
c[j + 1][i + 1] = c[j + 1][i]
else:
c[j + 1][i + 1] = c[j][i + 1]
return c[m][n]
def longest_common_substring_length(s1, s2):
""" Length of the longest common substring of strings s1 and s2"""
n, m = len(s1), len(s2)
c = [[0 for _ in xrange(n + 1)] for _ in xrange(m + 1)]
longest = 0
for i, c1 in enumerate(s1):
for j, c2 in enumerate(s2):
if c1 == c2:
c[j + 1][i + 1] = c[j][i] + 1
if c[j + 1][i + 1] > longest:
longest = c[j + 1][i + 1]
else:
c[j + 1][i + 1] = 0
return longest
def levenshtein_metric(s1, s2):
""" Normalized distance between strings s1 and s2 where
0 == perfect match
1 == completely different strings
based on the Levenshtein distance between s1 and s2
"""
return levenshtein_distance(s1, s2) / float(max(len(s1), len(s2)))
def longest_common_subsequence_metric(s1, s2):
""" Normalized distance between strings s1 and s2 where
0 == perfect match
1 == completely different strings
based on the length of the longest common subsequence of s1 and s2
"""
return 1 - longest_common_subsequence_length(s1, s2) / float(max(len(s1), len(s2)))
def longest_common_substring_metric(s1, s2):
""" Normalized distance between strings s1 and s2 where
0 == perfect match
1 == completely different strings
based on the length of the longest common substring of s1 and s2
"""
return 1 - longest_common_substring_length(s1, s2) / float(max(len(s1), len(s2)))
|
e08ea56443f08fb4a90650b4dec896d23406dc19 | danielforero19/ejemplos-de-bucles-anidados | /ejemplo 1.py | 81 | 3.53125 | 4 | for x in range(12):
for y in range(3):
print("x vale", x,"y vale", y) |
90134f566a29c2dc47658224c55090064fc61a32 | appsjit/testament | /Miscellaneous/AlgTool/wk2fractional_knapsack.py | 883 | 3.921875 | 4 | # Uses python3
import sys
class knapsack():
def __init__(self,pRatio,pTagId):
self.ratio = pRatio
self.tagId = pTagId
def get_optimal_value(capacity, weights, values,n):
value = 0.
for x in range(0,n):
print(x)
print(weights.__getitem__(x))
##print(wt)
# write your code here
return value
if __name__ == "__main__":
###data = list(map(int, sys.stdin.read().split()))
# data = list(map(int, sys.stdin.read().split()))
# n, capacity = data[0:2]
# values = data[2:(2 * n + 2):2]
# weights = data[3:(2 * n + 2):2]
data = list(map(int, '3 50 60 20 100 50 120 30'.split())) ### To Hardcode entry
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values,n)
print("{:.10f}".format(opt_value))
|
342b6b8449d061f9cde986a9d64c10ca48148732 | appsjit/testament | /LeetCode/educative/StQ_Ch3_RevKinQ.py | 734 | 4.03125 | 4 | from myStack import myStack
from myQueue import myQueue
def reverseK(queue,k):
# Write your code here
mstack = myStack()
cnt = 0
while cnt < k:
mstack.push(queue.dequeue())
cnt += 1
while not mstack.isEmpty():
queue.enqueue(mstack.pop())
totSize = len(queue.queueList)
print(totSize)
for x in range(totSize - k):
queue.enqueue(queue.dequeue())
#testing our logic
queue = myQueue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(5)
queue.enqueue(6)
queue.enqueue(7)
queue.enqueue(8)
queue.enqueue(9)
queue.enqueue(10)
print ("the queue before reversing:")
print (queue.queueList)
reverseK(queue, 10)
print ("the queue after reversing:")
print (queue.queueList) |
dae84ac89abab12d06b0b22264a995764a72d110 | appsjit/testament | /LeetCode/educative/LinkedList_Ch06_Loop.py | 399 | 3.703125 | 4 | #Access HeadNode => list.getHead()
#Check if list is empty => list.isEmpty()
#Node class { int data ; Node nextElement;}
def detectLoop(list):
# Write your code here
cnode = list.getHead()
visitedNodes = []
while cnode.nextElement != None:
print(cnode.data)
cnode = cnode.nextElement
if ( cnode in visitedNodes):
return True
visitedNodes.append(cnode)
return False |
37289bf83605e88e888b447c06f9b99827dcf227 | appsjit/testament | /LeetCode/soljit/s063_UniquePath2.py | 1,422 | 3.546875 | 4 | class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
r = len(obstacleGrid)
c = len(obstacleGrid[0])
# If the starting cell has an obstacle, then simply return as there would be
# no paths to the destination.
if obstacleGrid[0][0] == 1:
return 0
# Number of ways of reaching the starting cell = 1.
obstacleGrid[0][0] = 1
for i in range(1, r):## Filling value for first column
if int(obstacleGrid[i][0] == 0 and obstacleGrid[i - 1][0] == 1):
obstacleGrid[i][0] = 1
else:
obstacleGrid[i][0] = 0
##obstacleGrid[i][0] = int(obstacleGrid[i][0] == 0 and obstacleGrid[i - 1][0] == 1)
# Filling the values for the first row
for j in range(1, c):
if int(obstacleGrid[0][j] == 0 and obstacleGrid[0][j - 1] == 1):
obstacleGrid[0][j] = 1
else:
obstacleGrid[0][j] = 0
##obstacleGrid[0][j] = int(obstacleGrid[0][j] == 0 and obstacleGrid[0][j-1] == 1)
for i in range(1, r):
for j in range(1, c):
if (obstacleGrid[i][j]) == 0:
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1]
else:
obstacleGrid[i][j] = 0
return obstacleGrid[r - 1][c - 1] |
51e9f480efe28c6db2e708995e944674b63eaabb | appsjit/testament | /LeetCode/soljit/s023_MergeKSortedLists.py | 2,432 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
if l1 == None:
return l2
if l2 == None:
return l1
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
##prev.next = l1 if l1 is not None else 12 ## throws error
prev.next = l1 if l1 is not None else l2 ## works
return prehead.next
totLists = len(lists)
interval = 1
while interval < totLists:
for x in range(0, totLists - interval, 2 * interval):
lists[x] = mergeTwoLists(lists[x], lists[x + interval])
interval *= 2
##print(lists[x])
return lists[0] if totLists > 0 else lists
## Merge 2 Lists first and then add 3rd List to FIrst List
## Merge By Divide and Conquer
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
def mergeTwo(l1, l2):
if l1 == None:
return l2
if l2 == None:
return l1
preHead = ListNode(-1)
res = preHead
while l1 and l2:
if l1.val <= l2.val:
res.next = l1
l1 = l1.next
else:
res.next = l2
l2 = l2.next
res = res.next
res.next = l1 if l1 is not None else l2
return preHead.next
if len(lists) <= 1:
return lists
interval = 1
while interval < len(lists):
for x in range(0, len(lists) - interval, interval * 2):
lists[x] = mergeTwo(lists[x], lists[x + interval])
interval = interval * 2
return lists[0] if len(lists) > 0 else lists |
5eae40a6a77aa2e27d7492d7e5cfac3ba5a27979 | appsjit/testament | /LeetCode/soljit/s020_validParenthesis.py | 661 | 3.6875 | 4 | class Solution:
def isValid(self, s):
if len(s) % 2 != 0:
return False
stack = []
match = set([('(', ')'), ('[', ']'), ('{', '}')])
for c in s:
if c in ('(', '[', '{'):
stack.append(c)
if c in (')', ']', '}'):
if len(stack) == 0:
return False
else:
lastOp = stack.pop()
if (lastOp, c) not in match:
return False
if (len(stack) > 0):
return False
return True
"""
:type s: str
:rtype: bool
"""
|
67b81266248d8fb5394b5ffbd7a950a2ae38f5b2 | appsjit/testament | /LeetCode/soljit/s208_TrieAddSearchSW.py | 2,080 | 4.125 | 4 | class TrieNode:
def __init__(self, value=None):
self.value = value
self.next = {}
self.end = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
current = self.root
for i in range(0, len(word)):
letter = word[i]
if (not letter in current.next):
current.next[letter] = TrieNode(letter)
current = current.next[letter]
current.end = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
self.isFound = False
def dfs(word, cur):
if len(word) < 1:
if cur.end:
self.isFound = True
return
elif word[0] == '.':
for let in cur.next:
dfs(word[1:], cur.next[let])
else:
if word[0] in cur.next:
dfs(word[1:], cur.next[word[0]])
else:
return
print(word)
dfs(word, self.root)
return self.isFound
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
self.isStartWith = False
def dfsSW(prefix, cur):
if len(prefix) < 1:
self.isStartWith = True
else:
if prefix[0] in cur.next:
dfsSW(prefix[1:], cur.next[prefix[0]])
else:
return
print(prefix)
dfsSW(prefix, self.root)
return self.isStartWith
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix) |
f5fa5c732290e75bc783f0ffb6414abe81beed07 | appsjit/testament | /LeetCode/soljit/s002_AddingNumbers.py | 2,415 | 3.796875 | 4 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getNm(l):
x=""
childNode = l
while childNode.next != None:
x = str(childNode.val)+x
# print(childNode.val)
childNode = childNode.next
# print(childNode.val)
x = str(childNode.val)+x
if (x == "" or x == None ):
x=0
return int(x)
def addTwoNumbers(self, l1, l2):
# resNum = Solution.getNm(l1) + Solution.getNm(l2)
# return list(map(int, str(resNum)[::-1]))
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
hatcha = 0
result = list()
while l1 or l2 or hatcha:
val1 = l1.val if l1 else 0
l1 = l1.next if l1 else 0
l2,val2=[l2.next , l2.val] if l2 else [0,0]
hatcha , baki =divmod(val1 + val2 + hatcha , 10)
result.append(baki)
return result
### Using LinkedList
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
preHead = ListNode(-1)
res = preHead
rem = 0
while l1 != None and l2 != None:
newNum = l1.val + l2.val + rem
rem = 0
if newNum < 10:
newNum = newNum
else:
rem = 1
newNum -= 10
newNode = ListNode(newNum)
res.next = newNode
res = res.next
l1 = l1.next
l2 = l2.next
remList = l1 if l1 is not None else l2
while remList != None:
newNum = remList.val + rem
rem = 0
if newNum < 10:
newNum = newNum
else:
rem = 1
newNum -= 10
res.next = ListNode(newNum)
res = res.next
remList = remList.next
if rem > 0:
res.next = ListNode(rem)
return preHead.next
|
7606e3ab011a884ecadbd3db10920b506991da66 | appsjit/testament | /LeetCode/soljit/s394_decodeString.py | 1,826 | 3.609375 | 4 | class Solution:
def decodeString(self, s: str) -> str:
ans = ""
def peek_stack(stack):
if stack:
return stack[-1] # this will get the last element of stack
else:
return None
stack = []
k = ''
for idx, x in enumerate(s):
if x == '[':
# Store the current string in stack with the current multiplier
stack.append((idx, int(k)))
k = ''
continue
elif x == ']':
## pop last string
last_string, last_k = stack.pop()
if stack == []:
inside = self.decodeString(s[last_string + 1:idx])
ans += last_k * inside
continue
##ans = last_string + ans*last_k
elif x.isnumeric():
k += x
continue
if stack == []:
ans += x
return ans
# def decodeString(self, s: str) -> str:
# ans = ""
# def peek_stack(stack):
# if stack:
# return stack[-1] # this will get the last element of stack
# else:
# return None
# stack = []
# k = 0
# for x in s:
# if x == '[' :
# # Store the current string in stack with the current multiplier
# stack.append((ans, k))
# ans = ""
# k = 0
# elif x == ']' :
# ## pop last string
# last_string, last_k = stack.pop(-1)
# ans = last_string + ans*last_k
# elif x.isnumeric():
# k = k*10 + int(x)
# else :
# ans += x
# return ans
|
f1fc4cee503b73c157276cf2528fcb0493e15c86 | appsjit/testament | /LeetCode/soljit/s094_BST_Inorder.py | 1,109 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from queue import LifoQueue
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = []
# def helper(pnode):
# if pnode == None:
# return
# helper(pnode.left)
# print(pnode.val)
# result.append(pnode.val)
# helper(pnode.right)
# if root == None:
# return []
# helper(root)
# return result
curNode = root
##stack = deque()
stack = LifoQueue()
while (curNode != None or not stack.empty()):
while (curNode != None):
print(curNode.val)
stack.put(curNode)
curNode = curNode.left
curNode = stack.get()
result.append(curNode.val)
curNode = curNode.right
return result
|
c76de6d1f45c00a5f5f5f6b5f0478b74507dc753 | darlingtonbesa/SSR-GBS-pipeline | /extract_alleles.py | 2,797 | 3.65625 | 4 | # It uses a codominant matrix as an input containing alleles defined according to length. Then it sepeartes the sequences from each allele in a seperated file per sample.
# Usage: python extract_alleles.py codominat_matrix.txt(tab-delimited text) Directory_containing_sequence_per_marker_annd_per_sample(fasta or fastq) file_type(fasta/fastq) Output_Directory
from Bio import SeqIO
import sys
# only keeps sequences with a defined length
def extractLengthFasta(fasta, length):
for rec in SeqIO.parse(fasta, 'fasta'):
if length == len(rec):
yield rec
def extractLengthFastq(fastq, length):
for rec in SeqIO.parse(fastq, 'fastq'):
if length == len(rec):
yield rec
# three inputs: 1) matrix containing lengths; 2) directory containing fasta files; 3) directory to save results
allelesFile = open(sys.argv[1])
FastaDir = sys.argv[2]
fileType = sys.argv[3]
outDir = sys.argv[4]
# this part parses the matrix and uses the function from before to extract and then save the correct sequences
for l in allelesFile:
led = l.rstrip('\n').split(',')
Sample = led[0]
print('processing sample ' + Sample)
if Sample == 'samplename': # if line starts with Mix it means it is the header
loci = led[1:] # saves the loci information
else:
alleles = led[1:] # saves the alleles lengths for a certain sample
for i in range(0, len(loci), 2): # goes locus by locus and ...
locus = loci[i]
al1 = alleles[i]
al2 = alleles[i + 1] # extarcts information for each locus / sample combination from the matrix
print('...processing locus ' + locus)
if al1 != '0' and al2 != '0':
print('......genotype: ' + al1 + ',' + al2)
if fileType == 'fasta':
f = FastaDir + Sample + '_' + locus + '.fasta'
elif fileType == 'fastq':
f = FastaDir + Sample + '_' + locus + '.fastq'
else:
print('please provide a valid file format')
for al in list(set([al1, al2])):
outFasta = open(outDir + locus + '_' + Sample + '_Al_' + al + '.fasta', 'w') # creates an output file
if fileType == 'fasta':
SeqIO.write(extractLengthFasta(f, int(al)), outFasta, 'fasta') # sequences for each sample/allele combination
elif fileType == 'fastq':
SeqIO.write(extractLengthFastq(f, int(al)), outFasta, 'fasta') # sequences for each sample/allele combination
else:
print('please provide a valid file format')
outFasta.close()
else:
print('......genotype: missing')
|
ab7c467b47bb356cec6496a4873fb4a52670d9e8 | Hashah1/Leetcode-Practice | /medium/221. Maximal Square.py | 790 | 3.59375 | 4 | class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
"""
Time Complexity: O(row*col), row = len(matrix), col = len(matrix[0])
Space Complexity: O(row * col), row = len(matrix), col = len(matrix[0])
"""
dp = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
max_size = 0
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] == "1": # Validate matrix square
left = dp[row][col - 1]
up = dp[row - 1][col]
adj = dp[row - 1][col - 1]
dp[row][col] = min(left, up, adj) + 1
max_size = max(dp[row][col], max_size)
return max_size ** 2 |
6b36039673eba232521cd9777b2caed9538cf08d | Hashah1/Leetcode-Practice | /medium/230. Kth Smallest Element in a BST.py | 649 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
"""
Brute force: Inorder traversal, return kth element O(2^height of tree)
"""
inorder_trav = []
def helper(node):
if not node:
return
# Inorder
helper(node.left)
inorder_trav.append(node.val)
helper(node.right)
helper(root)
return inorder_trav[k - 1] |
38ebd923872af70b5fdf33c03d10cf53d288dc70 | Hashah1/Leetcode-Practice | /easy/BT_cousins.py | 1,932 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
:rtype: bool
"""
# Get depth of the two nodes.
x_depth = self.get_depth(root, x, 0)
y_depth = self.get_depth(root, y, 0)
# Find parents
parent_x = self.get_parent(root, x)
parent_y = self.get_parent(root, y)
if parent_x.val != parent_y.val:
if x_depth == y_depth:
return True
return False
def get_depth(self, root, target_val, depth):
"""
Finds the depth of a target root from the tree's root node
:param target_val: {Int} The target who's node equivalent's depth needs to be found
:param root: {TreeNode} Root node passed in.
:return depth: {Int} The depth of the node.
"""
if not root:
return 0
if root.val == target_val:
return depth
left = self.get_depth(root.left, target_val, depth + 1)
right = self.get_depth(root.right, target_val, depth + 1)
return max(left, right)
def get_parent(self, root, target_val):
"""
Finds the parent of target node
"""
if not root:
return None
if root.val == target_val:
return root
if root.right:
if root.right.val == target_val:
return root
if root.left:
if root.left.val == target_val:
return root
node = self.get_parent(root.left,target_val)
if node:
return node
else:
node = self.get_parent(root.right,target_val)
if node:
return node |
6de9cbd5e764ff8fd45291bbe82ded9f025287b2 | Hashah1/Leetcode-Practice | /medium/637. Average of Levels in Binary Tree.py | 939 | 3.796875 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
"""
Time Complexity: O(n), n = number of nodes in tree
Space Complexity: O(2^depth), depth is depth of tree
"""
q = deque([root])
averages = []
while q:
level_len = len(q)
sum_per_level = 0
for _ in range(level_len):
root = q.popleft()
sum_per_level += root.val
if root.left:
q.append(root.left)
if root.right:
q.append(root.right)
average = sum_per_level / level_len
averages.append(average)
return averages
|
84455b0473913ce9734e7c4b62f4b604a1c3e82c | Hashah1/Leetcode-Practice | /medium/inorder_traversal.py | 1,257 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
traversal_list = []
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.traversal_list = []
return self.iterative_sol(root)
def recursive_sol(self,root):
# Terminating condition.
if root:
self.recursive_sol(root.left)
self.traversal_list.append(root.val)
self.recursive_sol(root.right)
return self.traversal_list
def iterative_sol(self,root):
stk = []
if not root:
return self.traversal_list
while True:
# Go left until node is null
while root:
stk.append(root) # Keep adding to stack
root = root.left
if not root:
if stk:
# Pop off stack and add to list
node = stk.pop()
self.traversal_list.append(node.val)
root = node.right
else:
return self.traversal_list |
b20fb77c38e50c5a3b1a047e3cd5af74eb364b1a | Hashah1/Leetcode-Practice | /easy/design_hashmap.py | 1,719 | 4.09375 | 4 | class MyHashMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
# Use two arrays, which will always have the same
# length and will have a one-one relationship
self.hashmap = []
def put(self, key, value):
"""
value will always be non-negative.
:type key: int
:type value: int
:rtype: None
"""
# Update the hashashmapap
for i in range(len(self.hashmap)):
if self.hashmap[i][0] == key:
self.hashmap[i] = [key,value]
return
# Add to hashmap if none found
self.hashmap.append([key,value])
def get(self, key):
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
:type key: int
:rtype: int
"""
# Check if key is in list, return false otherwise
for i in range(len(self.hashmap)):
if self.hashmap[i][0] == key:
return self.hashmap[i][1]
return -1
def remove(self, key):
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
:type key: int
:rtype: None
"""
# Check if key is in list, return false otherwise
for i in range(len(self.hashmap)):
if self.hashmap[i][0] == key:
del self.hashmap[i]
return -1
if __name__ == "__main__":
a = MyHashMap()
a.put(1,1)
a.put(2,2)
ans = a.get(1)
ans = a.get(3)
a.put(2,1)
ans = a.get(2)
a.remove(2)
ans = a.get(2) |
a326d24bb276b5310d0a4f74ba822ccb8aa5205c | Hashah1/Leetcode-Practice | /easy/max subarray.py | 661 | 3.6875 | 4 | def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Set initial sums to the first element
previous_max = current_max = nums[0]
# Iterate through everything after first number
# Compare the current num and the
# previous sum of numbers leading to it.
# Maximum sum is the max of the two
for i in range(1, len(nums)):
# Get the max and set it to the previous_max
previous_max = max(nums[i], nums[i] + previous_max)
if previous_max > current_max:
current_max = previous_max
return current_max
|
1e5f673a2ebd9bd87525fb51591a8e6d31360f21 | Hashah1/Leetcode-Practice | /easy/intersection_2_lists.py | 1,748 | 3.625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
# Approach:
# 1. Get lenght of both lists
# 2. Iterate the longer list times (difference of lenA and lenB). So they start from same spots.
p_a = headA
p_b = headB
l_a, l_b = self.get_list_lengths(p_a, p_b)
# Make ptr for list A and list B start from a point so that
# both can reach None at the same time or reach the intersection node at same time.
if l_a > l_b:
# If list A is greater than list B
diff = l_a - l_b
i = 0
while i != diff and p_a:
p_a = p_a.next
i += 1
elif l_b > l_a:
diff = l_b - l_a
i = 0
while i != diff and p_b:
p_b = p_b.next
i += 1
# Simply return true if node is the same or not
while True:
if not p_a:
return None
if not p_b:
return None
if p_a == p_b:
return p_a
p_a = p_a.next
p_b = p_b.next
@staticmethod
def get_list_lengths(p_a, p_b):
"""Gets lengths of both lists"""
l_a = 0
l_b = 0
while True:
if p_a:
p_a = p_a.next
l_a += 1
if p_b:
p_b = p_b.next
l_b += 1
if not p_a and not p_b:
break
return l_a, l_b |
5100ba7cac697fb4bb69e10609557a2e29cf8b06 | Hashah1/Leetcode-Practice | /easy/is_symmetric.py | 998 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
r_a = r_b = root
return self.traverse(r_a, r_b)
def traverse(self,ra, rb):
# If either of them are Null
if not ra or not rb:
# Check if both are null, return True
# as the two nodes have traversed at same rate
if not ra and not rb:
return True
return False
# Traverse symmetrically
left_mirror = self.traverse(ra.left, rb.right)
right_mirror = self.traverse(ra.right, rb.left)
# As long as each mirror node is same and the left and right subtrees are same
# return True
if ra.val == rb.val and left_mirror and right_mirror:
return True |
3d19120e68c4aad4bc1406bff2bc75baca2f023b | Hashah1/Leetcode-Practice | /medium/48. Rotate Image.py | 734 | 3.953125 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
def reverse(lst):
l = 0
r = len(lst) - 1
while l < r:
lst[l], lst[r] = lst[r], lst[l]
l += 1
r -= 1
return lst
# Transpose each row in matrix
for row in range(len(matrix)):
for col in range(row, len(matrix[0])):
matrix[col][row], matrix[row][col] = matrix[row][col], matrix[col][row]
# Reverse each matrix row
for row in range(len(matrix)):
matrix[row] = reverse(matrix[row])
return matrix
|
1772cc776ab52f857090e0d91949512e23ec0de0 | Hashah1/Leetcode-Practice | /medium/LCA_binarytree.py | 1,354 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.path = []
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
# Populate path to find p
self.has_path(root, p)
path_p = self.path
self.path = []
# Populate path to find q
self.has_path(root, q)
path_q = self.path
LCA = None
# Return the last node where p and q's lists were equal.
while path_p and path_q:
p = path_p.pop(0)
q = path_q.pop(0)
if p == q:
LCA = p
else:
break
return LCA
def has_path(self, root, target):
"""
Find path to target node and populates a list with it.
"""
# If we find target, return
if not root:
return False
# Store the path to a list
self.path.append(root)
if root == target or self.has_path(root.left, target) or self.has_path(root.right, target):
return True
self.path.pop()
return False |
91382fa88ad4ed185fe2d6b635b3f321c22d2297 | Hashah1/Leetcode-Practice | /medium/654. Maximum Binary Tree.py | 1,309 | 3.578125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
"""
Thought Process:
TC: O(len(nums) * len(subarray))
SC: O(len(nums))
- root = Pick the max from nums, and thats going to be the root
- root.left = Pass left_bound..root_idx - 1 to the next recursion_call
- root.right = Pass root_idx + 1..right_bound to the next recursion_call
Bottleneck issue: Max value
"""
def helper(left, right):
if left > right:
return None
max_val, max_val_idx = get_max(left, right)
root = TreeNode(max_val)
root.left = helper(left, max_val_idx - 1)
root.right = helper(max_val_idx + 1, right)
return root
def get_max(left, right):
max_val, max_idx = 0, 0
for idx in range(left, right + 1):
val = nums[idx]
if val >= max_val:
max_val = val
max_idx = idx
return max_val, max_idx
return helper(0, len(nums) - 1) |
ff02b770288584cac77790cda21a5ece164fe1c7 | Hashah1/Leetcode-Practice | /easy/Climbin stairs.py | 1,050 | 3.8125 | 4 | class Solution(object):
def climbStairs(self, n):
""" RECURSIVE
:type n: int
:rtype: int
"""
# Cache with stairs:numways relationship
cache = {}
def helper(n):
# Base case 1
if n in cache:
return cache[n]
# Base case 2
if n < 2:
return 1
res = helper(n - 1) + helper(n - 2)
cache[n] = res
return res
return helper(n)
# def climbStairs(self, n):
# """ ITERATIVE
# :type n: int
# :rtype: int
# """
# # Use bottom up approach
# # Store the 0 and 1 step ways in list
# stored_results_list = [1,1]
# for each_way in range(1,n):
# # Store the num of ways to climb n'th step.
# # The num step is the current step + previous step
# stored_results_list.append(stored_results_list[each_way] + stored_results_list[each_way - 1])
# return stored_results_list.pop() |
3d72b16a663cdd2f59f293615dbe063462f877dd | forat19-meet/meet2017y1lab3 | /helloWorld.py | 2,137 | 4.375 | 4 | >>> print("hello world")
hello world
>>> print('hello world')
hello world
>>> print("hello gilad")
hello gilad
>>> # print("Hello World!")
>>> print("Γειά σου Κόσμε")
Γειά σου Κόσμε
>>> print("Olá Mundo")
Olá Mundo
>>> print("Ahoj světe")
Ahoj světe
>>> print("안녕 세상")
안녕 세상
>>> print("你好,世界")
你好,世界
>>> print("नमस्ते दुनिया")
नमस्ते दुनिया
>>> print("ुSalamu, Dunia")
ुSalamu, Dunia
>>> print("Hola Mundo")
Hola Mundo
>>> print("ສະບາຍດີຊາວໂລກ")
ສະບາຍດີຊາວໂລກ
>>> print("Witaj świecie")
Witaj świecie
print("Γειά σου Κόσμε is how you say hello world in (greek).")
>>> print("ola mondo is how you say hello world in (portuguese).")
ola mondo is how you say hello world in (portuguese).
>>> print("Γειά σου Κόσμε is how you say hello world in (greek).")
Γειά σου Κόσμε is how you say hello world in (greek).
>>> print("Ahoj světe is how you say hello world in (czech).")
Ahoj světe is how you say hello world in (czech).
>>> print("안녕 세상 is how you say hello world in (korean).")
안녕 세상 is how you say hello world in (korean).
>>> print("你好,世界 is how you say hello world in (chinese).")
你好,世界 is how you say hello world in (chinese).
>>> print("नमस्ते दुनिया is how you say hello world in (hindi).")
नमस्ते दुनिया is how you say hello world in (hindi).
>>> print("ुSalamu, Dunia is how you say hello world in (swahili).")
ुSalamu, Dunia is how you say hello world in (swahili).
>>> print("ुhola mundo is how you say hello world in (spanish).")
ुhola mundo is how you say hello world in (spanish).
>>> print("ुWitaj świecie is how you say hello world in (polan).")
ुWitaj świecie is how you say hello world in (polan).
>>> print("ुສະບາຍດີຊາວໂລກ is how you say hello world in (lau).")
ुສະບາຍດີຊາວໂລກ is how you say hello world in (lau).
>>>
|
2142a60c7a8db734a6d41468d3ae3c45ce7c14d1 | jordanCain-zz/Java-Optimisation-Atom-Plugin | /debugUtil.py | 1,412 | 3.625 | 4 | import inspect
class Trace():
def __init__(self, debug):
self.debugLevel = debug
if debug >= 1:
print ("Initialising User Trace")
userFile = open('UserTrace.txt', 'w+')
self.userFile = userFile
self.userFile.write("User Trace \n")
if debug >= 2:
print ("Initialising Stack Trace")
stackFile = open('StackTrace.txt', 'w+')
self.stackFile = stackFile
self.stackFile.write("Stack Trace\n")
def __exit__(self):
if self.debugLevel >= 1:
self.userFile.close()
if self.debugLevel >= 2:
self.stackFile.close()
def writeTrace(self, message = ""):
if self.debugLevel >= 1:
self.userTrace(message)
if self.debugLevel >= 2:
self.stackTrace()
def userTrace(self, message):
self.userFile.write(message + "\n")
def stackTrace(self):
self.formatStackTrace(len(inspect.stack())-2)
self.stackFile.write(inspect.stack()[2][3] + " ")
self.formatStackTrace(len(inspect.stack())-2)
self.stackFile.write(" " + inspect.stack()[2][1] + " : " + str(inspect.stack()[2][2]-2) + "\n")
#Allows the method calls to be formatted in a cascading tree
def formatStackTrace(self,count):
while count > 0:
self.stackFile.write(" ")
count -= 1
|
6be025375f60e36c59bb84f3a12f90d28e6df505 | yjlee0209/kite | /Python/module_basic/test_module.py | 537 | 3.96875 | 4 | # 변수
PI = 3.14
# 함수 : 사용자의 데이터 입력 값을 반환하는 기능
def number_input():
result = input('숫자를 입력해주세요 >>> ')
return float(result)
# 함수 : 원의 둘레를 구하고 값을 반환하는 기능
def get_circumference(radius):
return 2*PI*radius
# 함수 : 원의 면적을 구해서 반환하는 기능
def get_circle_area(radius):
return PI*radius*radius
if __name__ == '__name__':
print(__name__)
print(get_circumference(10))
print(get_circle_area(10)) |
5db6b90a933778253e1c023dce68643d026d367b | voitenko-lex/leetcode | /Python3/06-zigzag-conversion/zigzag-conversion.py | 2,703 | 4.28125 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
"""
import unittest
class Solution:
def convert(self, s: str, numRows: int) -> str:
lstResult = [[str("")] * numRows]
strResult = ""
state = "zig"
col = 0
row = 0
for char in s:
while True:
# print(f"char = {char} row = {row} col = {col}")
if row < 0:
row = 0
elif row == 0:
state = "zig"
break
elif row >= numRows:
row = numRows - 2
lstResult.append([str("")] * numRows)
col += 1
state = "zag"
else:
break
lstResult[col][row] = char
if state == "zig":
row += 1
else:
lstResult.append([str("")] * numRows)
col += 1
row -= 1
# print(f"lstResult = {lstResult}")
for row in range(numRows):
for col in range(len(lstResult)):
strResult += lstResult[col][row]
# print(f"strResult = {strResult}")
return strResult
class TestMethods(unittest.TestCase):
sol = Solution()
def test_sample00(self):
self.assertEqual("PAHNAPLSIIGYIR", self.sol.convert(s = "PAYPALISHIRING", numRows = 3))
def test_sample01(self):
self.assertEqual("PINALSIGYAHRPI", self.sol.convert(s = "PAYPALISHIRING", numRows = 4))
def test_sample02(self):
self.assertEqual("ABC", self.sol.convert(s = "ABC", numRows = 1))
def test_sample03(self):
self.assertEqual("ABCD", self.sol.convert(s = "ABCD", numRows = 1))
def test_sample04(self):
self.assertEqual("ACEBDF", self.sol.convert(s = "ABCDEF", numRows = 2))
if __name__ == '__main__':
do_unittests = False
if do_unittests:
unittest.main()
else:
sol = Solution()
# sol.convert(s = "ABC", numRows = 1)
# sol.convert(s = "ABCDEF", numRows = 2)
sol.convert(s = "123456789", numRows = 1)
|
52c86bc850235388c689c5fad29accb4f1c9537d | voitenko-lex/leetcode | /Python3/TreeNode.py | 4,690 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
## Kth Smallest Element in a BST
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Constraints:
The number of elements of the BST is between 1 to 10^4.
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Hide Hint #1
Try to utilize the property of a BST.
Hide Hint #2
Try in-order traversal. (Credits to @chan13)
Hide Hint #3
What if you could modify the BST node's structure?
Hide Hint #4
The optimal runtime complexity is O(height of BST).
"""
import unittest
from typing import List, Set, Tuple, Dict
# import math
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def get_depth(self, depth = 0):
depth += 1
depth_left = 0
depth_right = 0
if self.left:
depth_left = self.left.get_depth()
if self.right:
depth_right = self.right.get_depth()
return depth + max(depth_left, depth_right)
def to_list(self, tree_list=None, n=1):
if not tree_list:
tree_list = [None for _ in range(2 ** self.get_depth())]
tree_list[n-1] = self.val
if self.left:
tree_list = self.left.to_list(tree_list, 2*(n))
if self.right:
tree_list = self.right.to_list(tree_list, 2*(n)+1)
return tree_list
def to_set(self, tree_set=set()):
tree_set.add(self.val)
if self.left:
tree_set = self.left.to_set(tree_set)
if self.right:
tree_set = self.right.to_set(tree_set)
return tree_set
def __str__(self):
result = ""
tree_list = self.to_list()
tree_depth = self.get_depth() # The log() will be faster, but this will require the import of math
cur_depth = 1
for num, val in enumerate(tree_list):
num += 1
if num >= 2**cur_depth:
cur_depth += 1
result += "\n\n"
result += "\t" * (tree_depth - cur_depth + 1)
if val:
result += str(val)
else:
result += "\t"
return result
@staticmethod
def make_TreeNode(iterable):
list_nodes = []
for num, val in enumerate(iterable):
new_node = TreeNode(val)
list_nodes.append(new_node)
num += 1
if num > 1:
root_node = num // 2
if num % 2 == 0:
list_nodes[root_node-1].left = new_node
else:
list_nodes[root_node-1].right = new_node
return list_nodes[0]
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
tree_list = list(root.to_set())
print(tree_list)
return tree_list[k-1]
class TestMethods(unittest.TestCase):
sol = Solution()
def test_sample00(self):
self.assertEqual(1, self.sol.kthSmallest(root = TreeNode.make_TreeNode([3,1,4,None,2]), k = 1))
def test_sample01(self):
self.assertEqual(3, self.sol.kthSmallest(root = TreeNode.make_TreeNode([5,3,6,2,4,None,None,1]), k = 3))
# def test_sample02(self):
# self.assertEqual(False, self.sol.kthSmallest(root = [1,2,3,None,4], x = 2, y = 3))
if __name__ == '__main__':
do_unittests = False
if do_unittests:
unittest.main()
else:
tree = TreeNode.make_TreeNode([5,3,6,2,4,None,None,1])
# tree = TreeNode.make_TreeNode([1,2,3,4,5,6,7,8,9])
# tree.PrintTree()
# print(tree)
print()
# sol = Solution()
# tree = TreeNode( 1,
# TreeNode( 2,
# TreeNode( 4,
# None,
# None),
# None),
# TreeNode( 3,
# None,
# None))
# # tree.PrintTree()
# print(sol.isCousins(root = tree, x = 3, y = 4))
|
28b61ff27c9b29b985fe9c584447b3391367e569 | voitenko-lex/leetcode | /Python3/05-longest-palindromic-substring/longest-palindromic-substring.py | 2,865 | 4.09375 | 4 | """
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
import unittest
class Solution:
def longestPalindrome(self, s: str) -> str:
"""
1616 ms / 13.8 MB
"""
try:
result_txt = s[0]
except:
result_txt = ""
result_len = 1
# print(f"{s}")
for cur_pos, char in enumerate(s):
nchars = s.count(char, cur_pos)
# print(f"{cur_pos} {char} {nchars}")
if nchars > 1:
look_pos = cur_pos+1
for _ in range(nchars-1):
look_pos = s.find(char, look_pos) + 1
# print(f" > {cur_pos} {look_pos} {s[cur_pos:look_pos]}=={s[cur_pos:look_pos][::-1]}={s[cur_pos:look_pos]==s[cur_pos:look_pos][::-1]}")
if (look_pos - cur_pos > result_len) and (s[cur_pos:look_pos]==s[cur_pos:look_pos][::-1]):
result_txt = s[cur_pos:look_pos]
result_len = len(result_txt)
# print(f" >> {result_txt}")
return result_txt
# def longestPalindrome(self, s: str) -> str:
# """
# 7312 ms / 12.9 MB
# """
# result_txt = ""
# for i in range(len(s)+1):
# for j in range(i):
# sample = s[j:i]
# if sample == sample[::-1]:
# if len(result_txt) < len(sample):
# result_txt = sample
# return result_txt
# def longestPalindrome(self, s: str) -> str:
# """
# 4808 ms / 13.6 MB
# """
# result_txt = ""
# for i in range(len(s)+1):
# for j in range(i):
# if (i-j) > len(result_txt):
# sample = s[j:i]
# if sample == sample[::-1]:
# if len(result_txt) < len(sample):
# result_txt = sample
# return result_txt
# def longestPalindrome(self, s):
# pass
class TestMethods(unittest.TestCase):
sol = Solution()
def test_sample00(self):
self.assertEqual("bab", self.sol.longestPalindrome("babad"))
def test_sample01(self):
self.assertEqual("bb", self.sol.longestPalindrome("cbbd"))
def test_sample02(self):
self.assertEqual("a", self.sol.longestPalindrome("a"))
def test_sample03(self):
self.assertEqual("", self.sol.longestPalindrome(""))
if __name__ == '__main__':
do_unittests = False
if do_unittests:
unittest.main()
else:
# print("12345"[-1:2])
sol = Solution()
print(sol.longestPalindrome("abcaac")) |
e47ec00b96e1851b21d61daa57a2f498fc88a41a | voitenko-lex/leetcode | /Python3/30-day-leetcoding-challenge/week-4/Subarray Sum Equals K.py | 2,522 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
## Find the Town Judge
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
- The town judge trusts nobody.
- Everybody (except for the town judge) trusts the town judge.
- There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
Note:
1 <= N <= 1000
trust.length <= 10000
trust[i] are all different
trust[i][0] != trust[i][1]
1 <= trust[i][0], trust[i][1] <= N
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
"""
import unittest
from typing import List, Set, Tuple, Dict
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
scores = {x:0 for x in range(1, 1+N)}
for pair in trust:
# scores[pair[0]] -= 1
try:
scores.pop(pair[0])
except KeyError:
pass
scores[pair[1]] += 1
print(f"\n {scores}")
for el in scores:
if scores[el] == N-1: return el
return -1
class TestMethods(unittest.TestCase):
sol = Solution()
def test_sample00(self):
self.assertEqual(2, self.sol.findJudge(N=2, trust=[[1,2]]))
def test_sample01(self):
self.assertEqual(3, self.sol.findJudge(N=3, trust=[[1,3],[2,3]]))
def test_sample02(self):
self.assertEqual(-1, self.sol.findJudge(N=3, trust=[[1,3],[2,3],[3,1]]))
def test_sample03(self):
self.assertEqual(-1, self.sol.findJudge(N=3, trust=[[1,2],[2,3]]))
def test_sample04(self):
self.assertEqual(3, self.sol.findJudge(N=4, trust=[[1,3],[1,4],[2,3],[2,4],[4,3]]))
def test_sample05(self):
self.assertEqual(1, self.sol.findJudge(N=1, trust=[]))
if __name__ == '__main__':
do_unittests = False
if do_unittests:
unittest.main()
else:
sol = Solution()
print(sol.findJudge(N=1, trust=[])) |
ed39fed3c0d69d077cbbf00350885c7205b00ae6 | voitenko-lex/leetcode | /Python3/02-add-two-numbers/add-two-numbers.py | 2,693 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
def ToReverseListNode(source: str):
nextv = None
for i in source:
node = ListNode(i)
node.next = nextv
nextv = node
return nextv
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
result = str(self.val)
pointer = self.next
while pointer != None:
result = result + " <- " + str(pointer.val)
pointer = pointer.next
return result
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
curval = ListNode(0)
result = curval
i = 0
while (curval.val > 0 or l1 or l2) and i<10:
i += 1
# print(f"Iter {i}, {curval.val} + [{l1.val} + {l2.val}]")
curval.next = ListNode(0)
local_sum = curval.val
if l1:
local_sum += int(l1.val)
if l2:
local_sum += int(l2.val)
curval.val = local_sum % 10
curval.next.val = local_sum // 10
lastval = curval
curval = curval.next
if l1: l1 = l1.next
if l2: l2 = l2.next
else:
lastval.next = None
# print(f"result {result}")
return result
# nextval = 0
# while pointer != None:
# curval = l1.val + l2.val + nextval
# nextval = curval//10
# curval = curval%10
# curnode = ListNode()
# l1 = l1.next
# l2 = l2.next
class TestStringMethods(unittest.TestCase):
sol = Solution()
def addTwoNumbersTest(self, val1, val2):
test_val1 = ToReverseListNode(str(val1))
test_val2 = ToReverseListNode(str(val2))
test_result = ToReverseListNode(str(val1+val2))
print("-----------\n{}\n + \n{} \n = \n{}".format(test_val1, test_val2, test_result))
print("===========")
print(self.sol.addTwoNumbers(test_val1, test_val2))
self.assertEqual(str(self.sol.addTwoNumbers(test_val1, test_val2)), str(test_result))
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
# Explanation: 342 + 465 = 807.
def test_sample00(self):
self.addTwoNumbersTest(203, 308)
def test_sample01(self):
self.addTwoNumbersTest(202, 0)
def test_sample03(self):
self.addTwoNumbersTest(789, 333)
def test_sample04(self):
self.addTwoNumbersTest(2, 10)
if __name__ == '__main__':
unittest.main()
|
dcb2f37d5210d29312bff7ce6a9d38e17e4d209e | adamhammes/advent-of-code | /aoc_2020/day12.py | 3,133 | 3.5 | 4 | import dataclasses
import enum
from lib import Point, get_input
class TurnDirection(enum.Enum):
Clockwise = enum.auto()
CounterClockwise = enum.auto()
class Orientation(enum.IntEnum):
North = 0
East = 1
South = 2
West = 3
def as_coords(self) -> Point:
# fmt: off
return Point(*{
Orientation.North: ( 0, 1),
Orientation.East: ( 1, 0),
Orientation.South: ( 0, -1),
Orientation.West: (-1, 0),
}[self])
# fmt: on
@staticmethod
def from_char(c: str) -> "Orientation":
return {
"N": Orientation.North,
"E": Orientation.East,
"S": Orientation.South,
"W": Orientation.West,
}[c]
@dataclasses.dataclass
class ShipState:
position: Point = Point(0, 0)
orientation: Orientation = Orientation.East
waypoint: Point = Point(10, 1)
def displace_in_direction(self, direction: Orientation, steps: int):
dx, dy = direction.as_coords()
self.position = self.position.displace(dx * steps, dy * steps)
def displace_front(self, steps: int):
self.displace_in_direction(self.orientation, steps)
def turn(self, direction: TurnDirection, steps: int):
if direction == TurnDirection.Clockwise:
self.orientation = Orientation((self.orientation + steps) % 4)
else:
self.orientation = Orientation((self.orientation - steps) % 4)
def move(self, line: str) -> "ShipState":
instruction, steps = line[0], int(line[1:])
if instruction in "NESW":
direction = Orientation.from_char(instruction)
self.displace_in_direction(direction, steps)
elif instruction == "L":
num_turns = steps // 90
self.turn(TurnDirection.CounterClockwise, num_turns)
elif instruction == "R":
num_turns = steps // 90
self.turn(TurnDirection.Clockwise, num_turns)
elif instruction == "F":
self.displace_front(steps)
return self
def move_waypoint(self, line: str) -> "ShipState":
instruction, steps = line[0], int(line[1:])
if instruction in "NESW":
displacement = Orientation.from_char(instruction).as_coords().times(steps)
self.waypoint = self.waypoint.displace(*displacement)
elif instruction in "LR":
degrees = -1 * steps if instruction == "R" else steps
self.waypoint = self.waypoint.rotate(degrees)
elif instruction == "F":
displacement = self.waypoint.times(steps)
self.position = self.position.displace(*displacement)
return self
def part_1(raw: str):
ship = ShipState()
[ship.move(line) for line in raw.splitlines()]
return Point(0, 0).manhattan_distance_to(ship.position)
def part_2(raw: str):
ship = ShipState()
[ship.move_waypoint(line) for line in raw.splitlines()]
return Point(0, 0).manhattan_distance_to(ship.position)
if __name__ == "__main__":
print(part_1(get_input(12)))
print(part_2(get_input(12)))
|
781681dc75e3bfa3068f0ff02b464bbc160f47ea | adamhammes/advent-of-code | /aoc_2022/day02.py | 1,564 | 3.5 | 4 | from collections.abc import Iterable
import enum
import lib
class Option(str, enum.Enum):
Rock = "X"
Paper = "Y"
Scissors = "Z"
beats = {
Option.Rock: Option.Scissors,
Option.Paper: Option.Rock,
Option.Scissors: Option.Paper,
}
loses = {b: a for a, b in beats.items()}
def parse_input(raw: str) -> Iterable[tuple[Option, Option]]:
str_to_opt = {
"A": Option.Rock,
"B": Option.Paper,
"C": Option.Scissors,
"X": Option.Rock,
"Y": Option.Paper,
"Z": Option.Scissors,
}
for line in raw.strip().splitlines():
opp, us = line.split()
yield str_to_opt[opp], str_to_opt[us]
def score_match(opponent_choice, our_choice):
score = {
Option.Rock: 1,
Option.Paper: 2,
Option.Scissors: 3,
}[our_choice]
if beats[our_choice] == opponent_choice:
score += 6
elif loses[our_choice] == opponent_choice:
score += 0
else:
score += 3
return score
def part_1(raw: str) -> int:
scores = [score_match(opp, us) for opp, us in parse_input(raw)]
return sum(scores)
def part_2(raw: str) -> int:
total_score = 0
for opp, should_do in parse_input(raw):
us = opp # draw by default
if should_do == "X": # lose
us = beats[opp]
elif should_do == "Z": # win
us = loses[opp]
total_score += score_match(opp, us)
return total_score
if __name__ == "__main__":
print(part_1(lib.get_input(2)))
print(part_2(lib.get_input(2)))
|
a7ed10e9782bb1d07f03ac85384d23770d9a1be2 | adamhammes/advent-of-code | /aoc_2020/day03.py | 1,173 | 3.703125 | 4 | import typing as t
import lib
TEST_INPUT_1 = """
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
""".strip()
class Point(t.NamedTuple):
x: float
y: float
def get_input() -> t.Tuple[int, t.Dict[Point, bool]]:
with open("inputs/day03.txt") as f:
lines = f.read().strip().splitlines()
points = {}
for y, line in enumerate(lines):
for x, character in enumerate(line):
points[Point(x, y)] = character == "#"
return len(lines[0]), points
def check_slope(dx, dy):
width, points = get_input()
tree_count = 0
current_point = Point(0, 0)
while True:
if current_point not in points:
return tree_count
tree_count += points[current_point]
x, y = (current_point.x + dx) % width, current_point.y + dy
current_point = Point(x, y)
def part_1():
return check_slope(3, 1)
def part_2():
slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
return lib.product(check_slope(dx, dy) for dx, dy in slopes)
if __name__ == "__main__":
print(part_1())
print(part_2())
|
2cac80f5684db963e7c759375ca254aa0808e33e | adamhammes/advent-of-code | /aoc_2018/day01.py | 1,057 | 3.578125 | 4 | import itertools
import unittest
tests1 = [
([1, -2, 3, 1], 3),
([1, 1, 1], 3),
([1, 1, -2], 0),
([-1, -2, -3], -6),
]
tests2 = [([1, -1, 2], 2)]
def get_input():
with open("inputs/day1.txt") as f:
return map(int, f.readlines())
def compute_frequency_drift(numbers):
return sum(numbers, 0)
def repeated_frequency_drift(numbers):
seen_frequencies = set()
current_sum = 0
for frequency in itertools.cycle(numbers):
current_sum += frequency
if current_sum in seen_frequencies:
return current_sum
seen_frequencies.add(current_sum)
class TestDay1(unittest.TestCase):
def test1(self):
for test_input, result in tests1:
self.assertEqual(result, compute_frequency_drift(test_input))
def test2(self):
for test_input, result in tests2:
self.assertEqual(result, repeated_frequency_drift(test_input))
if __name__ == "__main__":
print(compute_frequency_drift(get_input()))
print(repeated_frequency_drift(get_input()))
|
98fabd6301a588815cd22364d109f81faec6a343 | adamhammes/advent-of-code | /aoc_2022/day05.py | 1,778 | 3.796875 | 4 | import re
from typing import NamedTuple
import lib
EXAMPLE_1 = """
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
"""
Board = list[list[str]]
class Instruction(NamedTuple):
quantity: int
from_position: int
to_position: int
def parse_input(raw: str):
raw_board, raw_instructions = raw.strip("\n").split("\n\n")
transposed_board = [list(line) for line in raw_board.splitlines()]
stacks: Board = []
for line in list(zip(*transposed_board[::-1])):
if line[0].isdigit():
stacks.append([c for c in line if c.isalpha()])
instructions = []
for line in raw_instructions.splitlines():
quantity, from_pos, to_pos = re.findall(r"\d+", line)
instruction = Instruction(int(quantity), int(from_pos) - 1, int(to_pos) - 1)
instructions.append(instruction)
return stacks, instructions
def part_1(raw: str) -> str:
board, instructions = parse_input(raw)
for instruction in instructions:
for _ in range(instruction.quantity):
popped = board[instruction.from_position].pop()
board[instruction.to_position].append(popped)
return "".join(crate[-1] for crate in board)
def part_2(raw: str) -> str:
board, instructions = parse_input(raw)
for instruction in instructions:
to_move = board[instruction.from_position][-instruction.quantity :]
board[instruction.from_position] = board[instruction.from_position][
: -instruction.quantity
]
board[instruction.to_position] += to_move
return "".join(crate[-1] for crate in board)
if __name__ == "__main__":
print(part_1(lib.get_input(5)))
print(part_2(lib.get_input(5)))
|
66ec6c800587d4dda3ee1ec81442ac0ac9206525 | adamhammes/advent-of-code | /aoc_2021/p3d.py | 1,334 | 3.671875 | 4 | import typing
class P(typing.NamedTuple):
x: int
y: int
z: int
def rotations(self, n: int) -> "P":
x, y, z = self
rots = [
# positive z up
(-x, -y, +z),
(-y, +x, +z),
(+x, +y, +z),
(+y, -x, +z),
# negative z up
(+x, -y, -z),
(-y, -x, -z),
(-x, +y, -z),
(+y, +x, -z),
# positive x up
(+y, +z, +x),
(+z, -y, +x),
(-y, -z, +x),
(-z, +y, +x),
# negative x up
(-z, -y, -x),
(-y, +z, -x),
(+z, +y, -x),
(+y, -z, -x),
# positive y up
(-z, -x, +y),
(-x, +z, +y),
(+z, +x, +y),
(+x, -z, +y),
# negative y up
(+z, -x, -y),
(-x, -z, -y),
(-z, +x, -y),
(+x, +z, -y),
]
return P(*rots[n])
def translate(self, vector: "P") -> "P":
return P(self.x + vector.x, self.y + vector.y, self.z + vector.z)
def sub(self, vector: "P") -> "P":
return P(self.x - vector.x, self.y - vector.y, self.z - vector.z)
def manhattan_distance(self, o: "P") -> int:
diff = o.sub(self)
return sum(map(abs, diff))
|
64e5c5bf7520e5efdd2ab7cc1bfc2c94b231dfff | adamhammes/advent-of-code | /aoc_2021/day02.py | 1,219 | 3.890625 | 4 | from lib import get_input
from lib import Point
from typing import NamedTuple
class Movement(NamedTuple):
direction: str
magnitude: int
def as_point(self) -> Point:
return {"forward": Point(1, 0), "down": Point(0, 1), "up": Point(0, -1)}[
self.direction
].times(self.magnitude)
def parse_input(raw_input: str) -> [Movement]:
return [
Movement(line.split()[0], int(line.split()[1]))
for line in raw_input.splitlines()
]
def part_1(movements: [Movement]) -> int:
position = Point(0, 0)
for movement in movements:
position = position.displace(*movement.as_point())
return position.x * position.y
def part_2(movements: [Movement]) -> int:
x, depth, aim = 0, 0, 0
for movement in movements:
if movement.direction == "down":
aim += movement.magnitude
elif movement.direction == "up":
aim -= movement.magnitude
elif movement.direction == "forward":
x += movement.magnitude
depth += movement.magnitude * aim
return x * depth
if __name__ == "__main__":
inputs = parse_input(get_input(2))
print(part_1(inputs))
print(part_2(inputs))
|
94c76f1469491425967b64e08d9795a3f46a71d5 | adamhammes/advent-of-code | /aoc_2021/day04.py | 1,877 | 3.53125 | 4 | from typing import NamedTuple, Optional, Tuple
import lib
Calls = list[int]
class BingoBoard(NamedTuple):
squares: list[list[Optional[int]]]
@staticmethod
def from_str(raw: str) -> "BingoBoard":
squares = [[int(c) for c in line.split()] for line in raw.strip().splitlines()]
return BingoBoard(squares)
def update(self, new_num: int) -> "BingoBoard":
squares = [[None if n == new_num else n for n in row] for row in self.squares]
return BingoBoard(squares)
def is_winner(self) -> bool:
for row in self.squares:
if all(s is None for s in row):
return True
for col_i in range(len(self.squares[0])):
if all(r[col_i] is None for r in self.squares):
return True
return False
def score(self) -> int:
return sum(s for row in self.squares for s in row if s)
def parse_input(raw: str) -> Tuple[Calls, list[BingoBoard]]:
raw = raw.strip()
first_line, other_lines = raw.split("\n\n", maxsplit=1)
calls = list(map(int, first_line.split(",")))
boards = list(map(BingoBoard.from_str, other_lines.split("\n\n")))
return calls, boards
def part_1(raw) -> int:
calls, boards = parse_input(raw)
for call in calls:
boards = [board.update(call) for board in boards]
winners = [board for board in boards if board.is_winner()]
if winners:
return winners[0].score() * call
def part_2(raw) -> int:
calls, boards = parse_input(raw)
for call in calls:
boards = [board.update(call) for board in boards]
if len(boards) == 1 and boards[0].is_winner():
return boards[0].score() * call
boards = [b for b in boards if not b.is_winner()]
if __name__ == "__main__":
print(part_1(lib.get_input(4)))
print(part_2(lib.get_input(4)))
|
6303d1c3706e99b0bbd18d019cd124323d4d90e4 | adamabad/WilkesUniversity | /cs125/projects/weights.py | 1,289 | 4.25 | 4 | # File: weights.py
# Date: October 26, 2017
# Author: Adam Abad
# Purpose: To evaluate pumpkin weights and average their total
def info():
print()
print("Program to calculate the average of a")
print("group of pumpkin weights.")
print("You will be asked to enter the number of")
print("pumpkins, followed by each pumpkin weight.")
print("Written by Adam Abad.")
print()
def weight(pumpkin):
text = "Enter the weight for pumpkin " + str(pumpkin) + ": "
weight = float(input(text))
print() #forturnin
if weight < 50:
print("{0:0.3f} is light".format(weight))
elif weight < 70:
print("{0:0.3f} is normal".format(weight))
else:
print("{0:0.3f} is heavy".format(weight))
return weight
def calcAverage(totalWeight,numPumpkins):
average = totalWeight/numPumpkins
print("The average weight of the",numPumpkins,end='')
print(" pumpkins is {0:0.3f}".format(average))
def main():
info()
numPumpkins = int(input("Enter the number of pumpkins: "))
print() #forturnin
print()
totalWeight = 0
for pumpkin in range(numPumpkins):
totalWeight = totalWeight + weight(pumpkin+1)
calcAverage(totalWeight,numPumpkins)
print()
main()
|
9d2cf5ad9820012e8b04b74c424fa27b034184e3 | adamabad/WilkesUniversity | /cs125/projects/histo.py | 2,544 | 4.09375 | 4 | #File: histo.py
#Date: December 7, 2017
#Author: Adam Abad
#Purpose: To construct a histogram for data in a file
from math import *
def intro():
print()
print("Program to print a histogram of scores.")
print("It also produces the high, low, and average score")
print("along with the standard deviation.")
print("Written by Adam Abad.")
print()
def getFile():
infileName = input("Enter the name of the input file: ")
print() #forturnin
print()
infile = open(infileName, "r")
return infile
def makeList(file):
mainList = []
for line in file:
mainList = mainList + line.split()
return mainList
def calcScores(scores):
numScores = []
high = 0 #Number will always be higher than 0
low = 100 #Number will always be lower than 100
total = 0
for scoreValue in range(1,len(scores),2):
numScores = numScores + [int(scores[scoreValue])]
for value in numScores:
total = total + value
if value < low:
low = value
if value > high:
high = value
average = total / len(numScores) #collin's idea
#deviation calc
sigma = 0
for Dvalue in numScores:
sigma = sigma + ((average - Dvalue) ** 2)
denom = len(numScores) - 1
standard = sqrt(sigma / denom)
return low, high, average, standard, numScores
def output(scores):
print("Name Score")
print("==== =====")
print()
for index in range(0,len(scores),2):
print("{0:<12}{1:11.2f}".format(scores[index],float(scores[index + 1])))
def histogram(numScores,low,high):
print("Histogram:")
print("==========")
print()
numScores.sort()
position = 0
for histo in range(low,high+1):
print("{0:4}".format(str(histo)+":"), end='')
while numScores[position] == histo:
print("*",end='')
if len(numScores)-1 == position: #No list out of range @ last num
break
position = position + 1
print()
def main():
intro()
file = getFile()
scores = makeList(file)
file.close()
low, high, average, standard, numScores = calcScores(scores)
print("Worst score:{0:13.2f}".format(low))
print("Best score:{0:14.2f}".format(high))
print("Average score:{0:11.2f}".format(average))
print("Standard deviation:{0:6.2f}".format(standard))
print()
output(scores)
print()
histogram(numScores,low,high)
print()
main()
|
201d52619b0eea154785427223844d3d9e48c5e7 | regynald/Project-Euler-Solutions | /Python/euler/bruh.py | 831 | 3.640625 | 4 | # def run():
# def circular_prime(n, primes):
# if not primes[n]:
# return False
# elif n < 10 and primes[n]:
# return True
# number = map(int, str(n))
# rotator = deque(number)
# for i in range(len(number)):
# num = int(''.join(map(str, rotator)))
# if num % 2 == 0:
# return False
# elif not primes[num]:
# return False
# rotator.rotate()
# return True
# result = 0
# primes = sieve(int(1e6))
# for i in range(3, int(1e6), 2):
# if circular_prime(i, primes):
# result += 1
# primeList = prime_list(int(1e6))
# for i in primeList:
# if circular_prime(i, primes):
# result += 1
# return result
# print run() |
c7d12d4ff7ce104c97eb20b3b9b4b222647fd09e | regynald/Project-Euler-Solutions | /Python/euler/library.py | 1,820 | 3.84375 | 4 | import math
# Returns true if n is a palindrome
def is_palindrome(n):
if isinstance(n, str):
return n == n[::-1]
else:
return is_palindrome(str(n))
# return true if n is prime
def is_prime(n):
if n <= 1:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
# returns a list of primes from 2 to n
def prime_list(n):
if n <= 2:
return []
sieve = range(3, n, 2)
top = len(sieve)
for si in sieve:
if si:
bottom = (si*si - 3) // 2
if bottom >= top:
break
sieve[bottom::si] = [0] * -((bottom - top) // si)
return [2] + [el for el in sieve if el]
# returns a boolean list from 0 to n + 1 where if a value is true its index is prime
def sieve(limit):
primes = [False] * 2 + [True] * (limit - 1)
for n in range(int(math.sqrt(limit))):
if primes[n]:
for i in range(n * n, limit+1, n):
primes[i] = False
return primes
# returns the number of divisors of n using prime factorization and the primelist, primes.
def number_of_divisors(n, primes):
nod, exponent, remain = 1, 1, n
for i in range(len(primes)):
if primes[i] ** 2 > n:
return nod * 2
exponent = 1
while remain % primes[i] == 0:
exponent += 1
remain /= primes[i]
nod *= exponent
if remain == 1:
return nod
return nod
# returns true if a number, nr contains the digits 1 to n at least once
def is_pandigital(nr, n):
nr = str(nr)
beg=nr[0:n]
end=nr[-n:]
for i in map(str, range(1, n + 1)):
if i not in beg or i not in end:
return False
return True |
2f362e378804ba491b518e056ab5df68cf175e70 | regynald/Project-Euler-Solutions | /Python/014.py | 1,174 | 3.765625 | 4 | """
Project Euler Problem 14
========================
The following iterative sequence is defined for the set of positive
integers:
n->n/2 (n is even)
n->3n+1 (n is odd)
Using the rule above and starting with 13, we generate the following
sequence:
13->40->20->10->5->16->8->4->2->1
It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms. Although it has not been proved yet (Collatz Problem),
it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
"""
def run():
target = 1000000
cache = [-1] * (target + 1)
max_length = -1
max_n = -1
cache[1] = 0
cache[2] = 1
for i in range(1, target + 1):
n = i
length = 0
sequence_nums = []
while n != 1 and n >= i:
length += 1
sequence_nums.append(n)
if n % 2 == 0:
n /= 2
else:
n = n * 3 + 1
for j in sequence_nums:
if j <= target:
cache[j] = length + cache[n]
if cache[i] > max_length:
max_length = cache[i]
max_n = i
return max_n
print run()
#come back to this question
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.