blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
404c1ddc387dfdff72da9ddec74ad4fb038cfb2b | nguyenkims/projecteuler-python | /src/p28.py | 843 | 3.71875 | 4 | def hasDisctintDigit(n):
'''test if all digits of n are distinct'''
s = str(n)
for i in range(0,len(s)-1):
for j in range(i+1,len(s)):
if s[i] == s[j]:
return False
return True
def isOK(n,k) :
''' test if n, n*2,...,n*k can form a pandigital'''
if not hasDisctintDigit(n): return -1
s=""
for i in range(1,k+1): s+= str(n*i)
# print s
if not hasDisctintDigit(s): return -1
for i in range(1,10):
if s.find(str(i)) < 0: return -1
return int(s)
def pandigital(n) :
'''return the pandigital corresponding to n if exists k such that isOK(n,k)'''
m = 9 / len(str(n))
for k in range(2,m +1):
if isOK(n,k) > 0: return isOK(n,k)
limit=10000
print isOK(192,3)
print pandigital(192)
def main():
m=-1
for i in range(1,limit):
t = pandigital(i)
if t >0: print i,t
if t > m: m = t
print 'max:',m
main() |
36e88e83240461f02ab56f14a09acfede124ba70 | SUHAYB-MACHINELEARNING-FULL-STACK/Data-Science-Project | /Data-Science-project.py | 1,020 | 3.921875 | 4 | # Task 1
x = 7
y = x/3
z = x==7
s= "Hello python programmer!"
print(f"type of x: {type(x)}\ntype of y: {type(y)}\ntype of z: {type(z)}\ntype of s: {type(s)}\n")
# Task 2
quantity = 2
price = 10.5
text = f"I want to pay {price} riyals for {quantity} pieces of this item."
print(f"{text}\n")
# Task 3
def bigger_than_10(x):
print(f"{x>10}\n")
bigger_than_10(19)
# Task 4
# Task 4 - Level 1
fruites = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(f"{fruites[-2:]}\n")
# Task 4 - Level 2
[print(f"{i}\n") for i in fruites]
# Task 5
# Task 5 - Level 1
colors = {
"blue": "0000FF",
"green": "00FF00",
"yellow": "FFFF00",
"red": "FF0000",
"white": "unknown"
}
colors['black'] = '000000'
print(f"{colors}\n")
# Task 5 - Level 2
colors['white'] = 'FFFFFF'
print(f"{colors}\n")
# Task 5 - Level 3
def exchange_values(lista):
print([colors[lista[i]] for i in range(len(lista))])
exchange_values(['blue', 'white', 'black', 'yellow', 'green', 'red'])
|
a7c5d2f0bba9de62c2730accc96cc356e475e4b0 | nazkeyramazan/hw | /infomatics/Ввод-вывод/b.py | 163 | 3.734375 | 4 |
x = int(input())
b = x+1
c = x-1
print ("The next number for the number", x ,"is", str(b)+"." )
print ("The previous number for the number", x ,"is", str(c)+"." ) |
24abcde35f1b881f991ab617d5ef288c6160c815 | huangichen97/Titanic-ML-PCA-DecisionTree | /titanic_pandas_pca.py | 4,046 | 3.734375 | 4 | """
File: titanic_pandas_pca.py
Name: Ethan H
---------------------------
This file shows how to use pandas and sklearn
packages to build a machine learning project
from scratch by their high order abstraction.
The steps of this project are:
1) Data pre-processing by pandas
2) PCA to extract components
3) Learning by sklearn
4) Test on D_test
"""
import pandas as pd
from sklearn import linear_model, preprocessing, decomposition
# Constants - filenames for data set
TRAIN_FILE = 'titanic_data/train.csv' # Training set filename
TEST_FILE = 'titanic_data/test.csv' # Test set filename
# Global variable
nan_cache = {} # Cache for test set missing data
def main():
# Data cleaning
data = data_preprocess(TRAIN_FILE, mode='Train')
# Extract true labels
y = data.Survived
# Extract features ('Pclass', 'Age', 'Sex', 'SibSp', 'Parch', 'Fare', 'Embarked')
# Extract feature_names first!
feature_names = ['Pclass', 'Age', 'Sex', 'SibSp', 'Parch', 'Fare', 'Embarked']
x_train = data[feature_names]
# Standardization
standardizer = preprocessing.StandardScaler()
x_train = standardizer.fit_transform(x_train)
# 0 mean
# PCA
pca = decomposition.PCA(n_components=5)
x_train_reduce = pca.fit_transform(x_train)
poly_feature_extractor = preprocessing.PolynomialFeatures(degree=2)
x_train_poly = poly_feature_extractor.fit_transform(x_train_reduce)
# Degree 2 Polynomial
h = linear_model.LogisticRegression(max_iter=10000)
classifier = h.fit(x_train_poly, y)
acc = classifier.score(x_train_poly, y)
print('Degree 2 Training Acc:', acc)
# Test
test_data = data_preprocess(TEST_FILE, mode='Test')
test_data = test_data[feature_names]
# standardize
test_data = standardizer.transform(test_data)
# pca
test_data = pca.transform(test_data)
test_poly = poly_feature_extractor.transform(test_data)
predictions = classifier.predict(test_poly)
test(predictions, "Ethan_pandas_PCA__components_submission_degree2.csv")
def data_preprocess(filename, mode='Train'):
"""
: param filename: str, the csv file to be read into by pd
: param mode: str, the indicator of training mode or testing mode
-----------------------------------------------
This function reads in data by pd, changing string data to float,
and finally tackling missing data showing as NaN on pandas
"""
# Read in data as a column based DataFrame
data = pd.read_csv(filename)
if mode == 'Train':
# Cleaning the missing data in Fare column by replacing NaN with its median
fare_median = data['Fare'].dropna().median()
data['Fare'] = data['Fare'].fillna(fare_median)
# Cleaning the missing data in Age column by replacing NaN with its median
age_median = data['Age'].dropna().median()
data['Age'] = data['Age'].fillna(age_median)
# Cache some data for test set
nan_cache['Age'] = age_median
nan_cache['Fare'] = fare_median
else:
# Fill in the NaN cells by the values in nan_cache to make it consistent
data['Fare'] = data['Fare'].fillna(nan_cache['Fare'])
data['Age'] = data['Age'].fillna(nan_cache['Age'])
# Changing 'male' to 1, 'female' to 0
data.loc[data.Sex == 'male', 'Sex'] = 1
data.loc[data.Sex == 'female', 'Sex'] = 0
# Changing 'S' to 0, 'C' to 1, 'Q' to 2
data['Embarked'] = data['Embarked'].fillna('S')
data.loc[data.Embarked == 'S', 'Embarked'] = 0
data.loc[data.Embarked == 'C', 'Embarked'] = 1
data.loc[data.Embarked == 'Q', 'Embarked'] = 2
return data
def test(predictions, filename):
"""
: param predictions: numpy.array, a list-like data structure that stores 0's and 1's
: param filename: str, the filename you would like to write the results to
"""
print('\n==========================')
print('Writing predictions to ...')
print(filename)
with open(filename, 'w') as out:
out.write('PassengerId,Survived\n')
start_id = 892
for ans in predictions:
out.write(str(start_id)+','+str(ans)+'\n')
start_id += 1
print('\n==========================')
if __name__ == '__main__':
main()
|
b1a024e453e23793dfbf567b69a22106d63a1a5d | whigg/polar_stereo | /source/nsidc_polar_ij.py | 2,281 | 3.5 | 4 | from polar_convert import polar_xy_to_lonlat
import numpy as np
def nsidc_polar_ij(i, j, grid, hemisphere):
"""Transform from NSIDC Polar Stereographic I, J coordinates
to longitude and latitude coordinates
Args:
i (int): an integer or integer array giving the x grid coordinate(s)
j (int): an integer or integer array giving the y grid coordinate(s)
grid (float): 6.25, 12.5 or 25; the grid cell dimensions in km
hemisphere (1 or -1): Northern or Southern hemisphere
Returns:
If i and j are scalars then the result is a
two-element list containing [longitude, latitude].
If i and j are numpy arrays then the result will be a two-element
list where the first element is a numpy array containing
the longitudes and the second element is a numpy array containing
the latitudes.
Examples:
print(nsidc_polar_ij(608, 896, 12.5, 1))
[350.01450147320855, 34.40871032516291]
"""
true_scale_lat = 70
re = 6378.273
e = 0.081816153
if grid != 6.25 and grid != 12.5 and grid != 25:
raise ValueError("Legal grid values are 6.25, 12.5, or 25")
if hemisphere != 1 and hemisphere != -1:
raise ValueError("Legal hemisphere values are 1 or -1")
if hemisphere == 1:
delta = 45
imax = 1216
jmax = 1792
xmin = -3850 + grid/2
ymin = -5350 + grid/2
else:
delta = 0
imax = 1264
jmax = 1328
xmin = -3950 + grid/2
ymin = -3950 + grid/2
if grid == 12.5:
imax = imax//2
jmax = jmax//2
elif grid == 25:
imax = imax//4
jmax = jmax//4
if np.any(np.less(i, 1)) or np.any(np.greater(i, imax)):
raise ValueError("'i' value is out of range: [1, " + str(imax) + "]")
if np.any(np.less(j, 1)) or np.any(np.greater(j, jmax)):
raise ValueError("'j' value is out of range: [1, " + str(jmax) + "]")
# Convert I, J pairs to x and y distances from origin.
x = ((i - 1)*grid) + xmin
y = ((jmax - j)*grid) + ymin
lonlat = polar_xy_to_lonlat(x, y, true_scale_lat, re, e, hemisphere)
lon = lonlat[0] - delta
lon = lon + np.less(lon, 0)*360
return [lon, lonlat[1]]
|
0f5c7df632312c4270c0bd3dfd9029aa21d90805 | grspraveen/python | /psd11.py | 164 | 3.703125 | 4 | #lets play with while loop
colors=["orange","red", "blue","green", "pink"]
newcolors=[]
i=0
while (colors[i]!="green"):
print(colors[i])
i=i+1
|
4ffd21485ea9493b1f471d13115a0dbe94505137 | adam-harmasz/gomoku_v_0_2 | /src/core/utils.py | 5,788 | 3.5 | 4 | """Utils file to place 'help' functions"""
import re
from datetime import datetime
from collections import defaultdict
import requests
def extract_data(record_content):
"""Function to extract data from game record content"""
# regex expressions to match content in game record
game_record_regex = r"(1.)(\s).+([a-z0-9]( ))"
black_player_nickname_regex = r"(Black)(\s).+([a-zA-Z])"
white_player_nickname_regex = r"(White)(\s).+([a-zA-Z])"
result_regex = r"(Result)(\s).+((0-1)|(1-0)|(1/2-1/2))"
date_regex = r"(Date)(\s).+([0-9])"
time_regex = r"(Time)(\s).+([0-9])"
game_record_string = re.search(
game_record_regex, record_content, re.MULTILINE | re.DOTALL
).group()
black_player_nickname_str = re.search(
black_player_nickname_regex, record_content
).group()
white_player_nickname_str = re.search(
white_player_nickname_regex, record_content
).group()
date_str = re.search(date_regex, record_content).group()
time_str = re.search(time_regex, record_content).group()
result_str = re.search(result_regex, record_content).group()
payload = defaultdict(list)
game_record_list = make_game_record_list(game_record_string)
swap_and_color_data = get_data_about_color_swap(game_record_list)
# Adding keys and values to the dictionary
payload["game_date"] = get_date_data_from_str(time_str, date_str)
payload["game_record"] = get_game_record_from_list(game_record_list)
payload["swap"] = swap_and_color_data[0]
payload["swap_2"] = swap_and_color_data[1]
payload["color_change"] = swap_and_color_data[2]
for _ in get_data_from_str_generator(
black_player_nickname_str, white_player_nickname_str, result_str
):
if _[0] == "result" and _[1] == "1-0":
payload[_[0]] = "black"
elif _[0] == "result" and _[1] == "0-1":
payload[_[0]] = "white"
elif _[0] == "result" and _[1] == "1/2-1/2":
payload[_[0]] = "draw"
else:
payload[_[0]] = _[1]
make_game_record_list(game_record_string)
return payload
def extract_data_from_game_record_file(filename=None, url=None):
"""
helper function to extract data from the game record file
function should return dictionary with values:
white_player, black_player, date_time, result and game_record
"""
if filename is not None and url is not None:
raise ValueError("You can use only one way to create record at the time")
elif filename is not None:
with open(filename, "r") as f:
f_content = f.read()
return extract_data(f_content)
elif url is not None:
res = requests.get(url)
if not res.text:
raise ValueError("no content")
return extract_data(res.text)
def get_date_data_from_str(time_str, date_str):
"""
Function which will extract datetime data from the string and will
be used in the 'extract_data_from_game_record_file' function to avoid
repeating the code
function should return the datetime value
"""
time_list = time_str.split(' "')
date_list = date_str.split(' "')
date_time_list = date_list[1] + " " + time_list[1]
converted_time = datetime.strptime(date_time_list, "%Y.%m.%d %H:%M:%S")
return converted_time
def get_data_from_str_generator(*data_list_params):
"""
Function which will extract data(both players names and result)
from the string and will
be used in the 'extract_data_from_game_record_file' function to avoid
repeating the code
function should return generator
"""
return (data_str.lower().split(' "') for data_str in data_list_params)
def make_game_record_list(game_record_str):
"""Function making game record list from the string"""
# removing \n and \r whitespaces from game record
game_record_list = " ".join(
" ".join(game_record_str.split("\n")).split("\r")
).split(" ")
# removing empty strings from the list
game_record_list = [_ for _ in game_record_list if _ != ""]
# removing . which was attached to numbers
for index, value in enumerate(game_record_list):
if "." in value:
value = value.rstrip(".")
game_record_list[index] = int(value)
return game_record_list
def get_game_record_from_list(game_record_list):
"""
Function extracting game record from a list to make it
a list o tuples with a two values, number of move and coordinate
"""
# Removing all statements from the list which aren't moves coordinates
game_record_list_with_only_moves = []
counter = 1
for index, value in enumerate(game_record_list):
if index == 0 or index % 3 == 0:
pass
elif value in ("white", "black", "--"):
pass
else:
game_record_list_with_only_moves.append(value)
counter += 1
return game_record_list_with_only_moves
def get_data_about_color_swap(game_record_list):
"""
Function determining whether during the game swap or swap2 was used
and if players changed their original color of the stones
"""
swap = False
swap_2 = False
color_change = False
if "white" in game_record_list or "black" in game_record_list:
swap = True
if game_record_list[5] == "black":
color_change = True
elif game_record_list[10] == "white" or game_record_list[10] == "black":
swap_2 = True
if game_record_list[10] == "white":
color_change = True
return [swap, swap_2, color_change]
def check_domain(url):
"""Function checking domain from the given url"""
domain_regex = r"((https)|(http))(://)([^/]+)"
return re.search(domain_regex, url).group()
|
cf1b3dc10f245ab726ce603673de2d6751609ce2 | flavienfr/bootcamp_ml | /day00/ex10/vec_linear_mse.py | 778 | 3.9375 | 4 | def vec_linear_mse(x, y, theta):
"""Computes the mean squared error of three non-empty numpy.ndarray,
without any for-loop. The three arrays must have compatible dimensions.
Args:
y: has to be an numpy.ndarray, a vector of dimension m * 1.
x: has to be an numpy.ndarray, a matrix of dimesion m * n.
theta: has to be an numpy.ndarray, a vector of dimension n * 1.
Returns:
The mean squared error as a float.
None if y, x, or theta are empty numpy.ndarray.
None if y, x or theta does not share compatibles dimensions.
Raises:
This function should not raise any Exception.
"""
if len(x) == 0 or len(y) == 0 or len(theta) == 0:
return None
total = 0.0
return ((np.dot(x, theta) - y).transpose() * (np.dot(x, theta) - y)).mean()
|
082a0f2b409274efb3939cf0a4c863a4df3fdf19 | chunche95/ProgramacionModernaPython | /Proyectos/ProgramacionVintage/Factura/lineaFacturaListaDeListas.py | 964 | 3.765625 | 4 | # Constantes
_UNIDADES = 1
_PRECIO = 0
cadenaUnidades = input("Cantidad: ")
unidades = float(cadenaUnidades)
cadenaPrecio = input("Precio Unitario (€): ")
precio = float(cadenaPrecio)
totalItems = 0
precioTotal = 0
listaPrecios = []
listaUnidades = []
listaLineasFact= []
while unidades > 0 and precio > 0:
totalUnitario = unidades * precio
item = []
item.append(unidades)
item.append(precio)
listaPrecios.append(item)
totalItems += unidades
precioTotal += totalUnitario
cadenaUnidades = input("Cantidad: ")
unidades = float(cadenaUnidades)
cadenaPrecio = input("Precio unitario (€) : ")
precio = float(cadenaPrecio)
for item in listaPrecios:
print(item[_PRECIO], " € - ", item[_UNIDADES], " unidades - ", item[_UNIDADES] * item[_PRECIO] , " € \n")
print("------------------------------")
print("Total: ", precioTotal , " €")
print("Unidades: ",totalItems , " Items")
|
ab22724d7b08e00b26919e443829368bd2d0117a | Kevinloritsch/Buffet-Dr.-Neato | /Python Warmup/Warmup #4/run4.py | 508 | 3.703125 | 4 | import time
counter = 1
ocounter =0
print("This will output only prime numbers--except at the start(1 is undefined)!")
print()
for x in range(counter, 100000000000000000000000000000000):
for x in range(1,counter):
if(counter%x!=0):
ocounter = ocounter +1
if ocounter == counter-2 and counter>11784179441:
print(counter)
elif (counter == int(1)):
print(counter, "is not defined!", end='\n')
time.sleep(2)
counter = counter+1
ocounter = 0
|
59429642fd0a89300b816b7929aa1c13f11a06f6 | poojakhatri/python_basic_programming | /random_002.py | 315 | 3.71875 | 4 | # Generate random numbers from interval [3,7]
# Call random(): in interval [0,1)
# scale number by multiply random number with 4 : in [0,4)
# Shift number (add 3) : # in [3,7)
import random
def my_random():
# Random, scale, shift, return ...
return 4*random.random()+3
for i in range(10):
print my_random() |
3ba54ca59689a6187e30ca6e268b12fe3c0c60e3 | LoganJackson35/01_RPS | /02_user_choice_v3.py | 1,089 | 4.15625 | 4 | # Version 3 - checks that response is in a given list
#functions go here
def choice_checker(question, valid_list, error_txt):
valid = False
while not valid:
# ask user for choice (and put choice in lowercase)
response = input(question).lower()
# iterates through lsit and if response is an item
# in the list (or the first letter of an item), the
# full item name is returned
for item in valid_list:
if response == item[0] or response == item:
return item
# output error if item not in list
print(error_txt)
print()
# Main routine goes here
# lists for checking purposes
rps_list = ["rock", "paper", "scissors", "xxx"]
# loop for testing purposes
choose = ""
while choose != "xxx":
# ask user for choice and check its valid
choose = choice_checker("Choose from rock / paper / scissors (r/p/s) ",
rps_list, "Please choose from rock / paper / scissors (or xxx to quit) ")
# print out choice for comparison purposes
print("You chose {}".format(choose))
|
b6a14b56d70942f700a5a3e91a7f0efd5e387bc3 | jen8/Python-Chapters | /MISC/lists.py | 2,598 | 3.984375 | 4 | def add_matrices(m1, m2):
"""
>>> a = [[1, 2], [3, 4]]
>>> b = [[2, 2], [2, 2]]
>>> add_matrices(a, b)
[[3, 4], [5, 6]]
>>> c = [[8, 2], [3, 4], [5, 7]]
>>> d = [[3, 2], [9, 2], [10, 12]]
>>> add_matrices(c, d)
[[11, 4], [12, 6], [15, 19]]
>>> c
[[8, 2], [3, 4], [5, 7]]
>>> d
[[3, 2], [9, 2], [10, 12]]
"""
output = []
for index in range(len(m1)):
row_1 = m1[index]
row_2 = m2[index]
new_row = []
for index2 in range(len(row_1)):
sum = row_1[index2] + row_2[index2]
new_row.append(sum)
output.append(new_row)
return output
def row_times_column(m1, row, m2, column):
"""
>>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 0)
19
>>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 1)
22
>>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 0)
43
>>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 1)
50
"""
sum = 0
for index in range(len(m1)):
product = m1[row][index] * m2[index][column]
sum += product
return sum
def matrix_mult(m1, m2):
"""
>>> matrix_mult([[1, 2], [3, 4]], [[5, 6], [7, 8]])
[[19, 22], [43, 50]]
>>> matrix_mult([[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 1], [2, 3]])
[[31, 19], [85, 55]]
>>> matrix_mult([[7, 8], [9, 1], [2, 3]], [[1, 2, 3], [4, 5, 6]])
[[39, 54, 69], [13, 23, 33], [14, 19, 24]]
"""
output = []
for rowIndex, row in enumerate(m1): #go through rows in m1
new_row = []
for columnIndex in range(len(m2[0])): #go through indices for each column of m2
sum = 0
for index3 in range(len(row)):
product = m1[rowIndex][index3] * m2[index3][columnIndex]
sum += product
new_row.append(sum)
output.append(new_row)
return output
#output = []
#first for loop corresponds to the rows of my output matrix and loops through the rows of m1 (enumerate)
#create an empty new row
# second for loop, loops through columns of m2
# create sum variable, initialize it with zero
# third for loop, multiplies the index of the row in m1 times the index of the column in m2
# add sum to product and assign this to the sum variable
# append sum to new row
# append new row to output
# return output
if __name__ == '__main__':
import doctest
doctest.testmod() |
2d31e76cefd5b74fe15771d587187baf53358010 | ribizly/python | /lab1_task3.py | 654 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import unicodedata
from unicodedata import normalize, category
input_name=raw_input('Give your full name: ')
# separated_name=input_name.lower().split().reverse().join().decode('utf8')
separated_name=input_name.lower().strip().decode("utf8")
s2=unicodedata.normalize('NFD',separated_name)
#deacuted=''
original_email_name=[]
for c in s2:
char_type=unicodedata.category(c)
if char_type=='Ll' or char_type=="Nd":
original_email_name.append(c)
original_email_name.reverse()
print(original_email_name)
new_mail_name=".".join(original_email_name)
print("%s@foobar.com" % new_mail_name)
|
c9484e88a1305d23455b0d716f947daef88f17db | DamianS6/competitions-challenges-problems | /codingame/medium/there_is_no_spoon_1.py | 743 | 3.75 | 4 | width = int(input()) # the number of cells on the X axis
height = int(input()) # the number of cells on the Y axis
array = [list(input()) for y in range(height)]
for y in range(height):
for x in range(width):
if array[y][x] != "0":
continue
result = f"{x} {y} "
# look for neighbour to the right
for c in range(x + 1, width):
if array[y][c] == "0":
result += f"{c} {y} "
break
else:
result += "-1 -1 "
# look for neighbour down
for c in range(y + 1, height):
if array[c][x] == "0":
print(f"{result} {x} {c}")
break
else:
print(f"{result} -1 -1")
|
648eb662b7bfe410b34a511c798c08c80bdf8fe9 | Pooya448/ComputerVision | /HW9/Solution/Q3C.py | 362 | 3.921875 | 4 | def adaptive_th(image):
'''
Applys adaptive threshold on the input image.
Parameters:
image (numpy.ndarray): The input image.
Returns:
numpy.ndarray: The result panorama image.
'''
result = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 19, 8)
return result
|
d78a19c36f29615b7a091dfacea1a15d849ff5ff | MLgeek96/Interview-Preparation-Kit | /Python_Interview_Questions/leetcode/problem_sets/Q66_plus_one.py | 1,889 | 4.21875 | 4 | from re import A
from typing import List
def plusOne(digits: List[int]) -> List[int]:
"""
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
Constraints:
• 1 <= digits.length <= 100
• 0 <= digits[i] <= 9
• digits does not contain any leading 0's.
"""
assert 1 <= len(digits) <= 100, "Length of input array must be between 1 and 100"
for digit in digits:
assert 0 <= digit <= 9, "Digit must be between 0 and 9"
pointer = 0
while pointer <= len(digits):
if digits[pointer] != 0:
break
assert digits[pointer] != 0, "Digits does not contain any leading 0's"
pointer += 1
# num_str = "".join(map(str, digits))
# num = int(num_str) + 1
# return list(map(int, str(num)))
for i in reversed(range(len(digits))):
if digits[i] != 9:
digits[i] += 1
return digits
else:
digits[i] = 0
digits.insert(0, 1)
return digits |
3f17ec580d4af3d7efb8b68f6dc0b2a5b5c6113e | bglads/algo | /geodist1.py | 289 | 3.703125 | 4 | '''
The probability that a machine produces a defective product is 1/3 . What is the probability that the 1st defect is found during the 5th inspection?
IP
1 3
5
'''
a=list(map(int,input().strip().split()))
b=int(input().strip())
a=float(a[0])/a[1]
print("{:.3f}".format(pow(1-a,4)*a))
|
6466a86200c292dbc1bbcd9cb8a981c520b67c43 | Stheycee/Exerc-cioo | /Projeto_Q2.py | 891 | 3.671875 | 4 | refeições = ['café da manhã', 'Suco de pêssego natural', 77, 'Maçã verde', 79]
almo = ['Almoço','Suco de abacaxi natural',100,'Salada de Alface,Tomate e Pepino',43]
jantar = ['jantar','Omelete',170,'Café com açúcar',62]
print('')
print('café da manhã até 100 calorias, No almoço 400 calorias, 200 calorias no jantar.')
print(f'\n{"=-=" * 10}\n{"Refeições: alimento: calorias:"}')
print(f'{refeições[0]} {refeições[1]} {refeições[2]}')
print(f'{refeições[0]} {refeições[3]} {refeições[4]}')
print(f'{almo[0]} {almo[1]} {almo[2]}')
print(f'{almo[0]} {almo[3]} {almo[4]}')
print(f'{jantar[0]} {jantar[1]} {jantar[2]}')
print(f'{jantar[0]} {jantar[3]} {jantar[4]}')
|
5d4d6d62dfa55dc458ed3dc78bd6f4f8539199e8 | aurelixv/sorts | /merge_sort.py | 620 | 3.6875 | 4 | def merge(A, B):
C = []
Ai = 0
Bi = 0
while Ai < len(A) and Bi < len(B):
if A[Ai] <= B[Bi]:
C.append(A[Ai])
Ai += 1
else:
C.append(B[Bi])
Bi += 1
while Ai < len(A):
C.append(A[Ai])
Ai += 1
while Bi < len(B):
C.append(B[Bi])
Bi += 1
# Returns both input vectors merged and sorted
return C
def merge_sort(A):
B = A[:int(len(A)/2)]
C = A[int(len(A)/2):]
if len(A) > 2:
B = merge_sort(B)
C = merge_sort(C)
# Returns sorted vector
return merge(B, C)
|
35ec30f5d5fd6865420b5b2b061eed174afa2769 | allifizzuddin89/ML_Python_Exercises | /pandas_df_type.py | 1,242 | 3.796875 | 4 | #Written by Allif Izzuddin bin Abdullah
#github : allifizzuddin89
import pandas as pd
#USE CSV AS DATAFRAME
df = pd.read_csv('nyc_weather.csv')
print(df)
#USE EXCEL AS DATAFRAME
df = pd.read_excel("nyc_weather.xlsx", "nyc_weather") #pd.read_excel("file", "sheetname")
print(df)
#USE PYTHON DICT
weather_data = {
'day':['1/1/2017','1/2/2017','1/3/2017','1/4/2017','1/5/2017', '1/6/2017'],
'temperature' : [32, 35, 28, 24, 32, 31],
'windspread' : [6, 7, 2, 7, 4, 2],
'event' : ['Rain', 'Sunny', 'Snow', 'Snow', 'Rain', 'Sunny']
}
df = pd.DataFrame(weather_data)
print(df)
#USE TUPLES
weather_data = [
('1/1/2017', 32, 6, 'Rain'),
('1/2/2017', 35.7, 'Sunny'),
('1/3/2017', 28, 'Snow')
]
#we have to add data name column to the dataframe
df = pd.DataFrame(weather_data, columns= ["daya", "temperature", "wuindspeed", "event"])
print(df)
#USE LIST
weather_data = [
{'day': '1/1/2017', 'temperature': 32, 'windspeed': 6, 'event': 'Rain'},
{'day': '1/2/2017', 'temperature': 40, 'windspeed': 4, 'event': 'Sunny'},
{'day': '1/3/2017', 'temperature': 18, 'windspeed': 9, 'event': 'Snow'},
{'day': '1/4/2017', 'temperature': 19, 'windspeed': 4, 'event': 'Snow'},
]
df = pd.DataFrame(weather_data)
print(df) |
f1ae7c88cf500817afd7d54a67c72117b629bba0 | qiwihui/leetcode-python | /169.majority-element.py | 1,186 | 3.609375 | 4 | #
# @lc app=leetcode id=169 lang=python3
#
# [169] Majority Element
#
# https://leetcode.com/problems/majority-element/description/
#
# algorithms
# Easy (53.86%)
# Likes: 2026
# Dislikes: 178
# Total Accepted: 446.5K
# Total Submissions: 820.3K
# Testcase Example: '[3,2,3]'
#
# Given an array of size n, find the majority element. The majority element is
# the element that appears more than ⌊ n/2 ⌋ times.
#
# You may assume that the array is non-empty and the majority element always
# exist in the array.
#
# Example 1:
#
#
# Input: [3,2,3]
# Output: 3
#
# Example 2:
#
#
# Input: [2,2,1,1,1,2,2]
# Output: 2
#
#
#
# @lc code=start
class Solution:
def majorityElement(self, nums: List[int]) -> int:
# 分治
n = len(nums)
if n == 1:
return nums[0]
left = self.majorityElement(nums[:n//2])
right = self.majorityElement(nums[n//2:])
if left == right:
return left
else:
left_count = sum(1 for i in nums if left == i)
right_count = sum(1 for i in nums if right == i)
return left if left_count > right_count else right
# @lc code=end
|
8675cb0c4803d6f238cf348870fc3e0b97a19ccd | ffismine/leetcode_github | /杂/20211126集团考试题目1.py | 1,636 | 3.5 | 4 | # -*- coding:utf-8 -*-
"""
Created on '2021/11/26-15:42'
Author: Xie Zhang
"""
'''
一个严格递增数列是指每个数都严格比前一个数大的一列数。
一个严格递减数列是指每个数都严格比前一个数小的一列数。
一个严格单调数列是指严格递增数列或是严格递减数列。例如1, 5, 6, 10和9, 8, 7, 1 两个数列都是严格单调数列,
而1, 5, 2, 6和1, 2, 2, 3就不是严格单调数列。
给定你一个数列seq,请找到满足严格单调定义的最长连续子数列,并返回其长度
参数: seq
列表
返回值: l, n(l: 满足严格单调定义的最长连续子数列,n: 满足严格单调定义的最长连续子数列的长度)
# str1 str
# 返回值: True/False
# 理解:递归查找 记录临时答案和flag
'''
class Solution(object):
def __init__(self):
self.allLen = 0
self.res = 0
def conSeq(self, seq):
self.allLen = len(seq)
return self.findMaxAddSeq(seq)
def findMaxAddSeq(self, seq):
flag = 0
tempRes = 0
for i in range(len(seq)):
if flag < seq[i]:
flag = seq[i]
tempRes += 1
continue
else:
break
if tempRes > self.res:
self.res = tempRes
if tempRes < len(seq):
seq = seq[tempRes:]
return self.findMaxAddSeq(seq)
else:
return self.res
if __name__ == '__main__':
seq = [1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 7, 8, 3, 4, 5, 6]
result = Solution()
answer = result.conSeq(seq)
print(answer)
|
cf21b89b8818c0e9a66ee350aabb67158686ed42 | ralic/Note | /Algorithms/tree/init_tree.py | 683 | 3.734375 | 4 | class Tree(object):
def __init__(self, index, leftchild, rightchild):
self.index = index
self.leftchild = leftchild
self.rightchild = rightchild
def create_tree(self, node_list):
pass
def select_root(self, node_list):
root_index = 0
for index in range(1, len(node_list)):
if node_list[index][1] == root_index or node_list[index][0] == root_index:
root_index = index
return node_list[root_index]
node_tuple = [(1, None), (None, None), (0, None), (2, 7),
(None, None), (None, None), (5, None), (4, 6)]
for node in node_tuple:
if node[0] or node[1]:
continue |
fc736c6bdff3d8e2f7dd8e1c96ba2df1c3cf9eb4 | zhangdavids/offer_py | /018.py | 1,731 | 3.6875 | 4 | # -*- coding:utf-8 -*-
# 顺时针打印矩阵
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
m = len(matrix)
ans = []
if m == 0:
return ans
n = len(matrix[0])
# ans = [[0 for i in range(n)] for j in range(n)]
# print ans
upper_i = 0
lower_i = m - 1
left_j = 0
right_j = n - 1
num = 1
i = 0
j = 0
right_pointer = 1
down_pointer = 0
while (num <= m * n):
ans.append(matrix[i][j])
if right_pointer == 1:
if j < right_j:
j = j + 1
else:
right_pointer = 0
down_pointer = 1
upper_i = upper_i + 1
i = i + 1
elif down_pointer == 1:
if i < lower_i:
i = i + 1
else:
right_pointer = -1
down_pointer = 0
right_j = right_j - 1
j = j - 1
elif right_pointer == -1:
if j > left_j:
j = j - 1
else:
right_pointer = 0
down_pointer = -1
lower_i = lower_i - 1
i = i - 1
elif down_pointer == -1:
if i > upper_i:
i = i - 1
else:
right_pointer = 1
down_pointer = 0
left_j = left_j + 1
j = j + 1
num = num + 1
return ans
|
53e763c290a827bb42e46507d06aa0df19377ace | zzz686970/leetcode-2018 | /1360_daysBetweenDates.py | 447 | 3.90625 | 4 | from datetime import datetime
def daysBetweenDates(date1, date2):
date1, date2 = datetime.strptime(date1, '%Y-%m-%d'), datetime.strptime(date2, '%Y-%m-%d')
return (date2 - date1).days if date2 > date1 else (date1 - date2).days
from datetime import date
def daysBetweenDates(date1: str, date2: str) -> int:
s1, s2 = date1.split("-"), date2.split("-")
d1, d2 = date(*map(int, s1)), date(*map(int, s2))
return abs((d1-d2).days) |
496a1874cfca65017352984f4a1188a9a3b505f6 | LucasPAndrade/_Learning | /_Python/Fundamentos-CursoEmVídeo/Desafio 015.py | 381 | 3.796875 | 4 | print('===== DESAFIO 015 =====\n')
km = int(input('Quantos km rodou com o carro? '))
dias = int(input('Quantos dias o carro ficou alugado? '))
valorKm = km*0.15
valorDias = dias*60
print(f'=== ALUGUEL DE CARROS ===n\Carro alugado por {dias} dias, {km}km rodados.\nValor km = R$ {valorKm:.2f}\nValor tempo = R$ {valorDias:.2f}\nValor totoal a pagar = R$ {valorDias+valorKm:.2f}') |
f4b57fc7540a380e57e40998f58b3ea8c17b9385 | flosopher/floscripts | /miniutils/Substract2LizDdgOutputs.py | 2,830 | 3.546875 | 4 | #!/usr/bin/python/
import sys
import os
def add_spaces(string, newlen, dir = 0):
if len(string) > newlen:
return string
fill = newlen - len(string)
if dir == 0:
for i in range(fill):
string = string + ' '
else:
for i in range(fill):
string = ' ' + string
return string
def usage():
print 'Script to read in two files generated by Liz Kellog\'s fix_bb_monomer_ddg executable, get the ddg Values fore ach mutation and also substract the ones in the second file from the ones in the first file ',
print 'Usage: Substract2LizDdgOutputs.py -f1 <file1> -f2 <file2>'
def read_file_to_commentless_linelist( filehandle ):
return_lines = []
line = filehandle.readline()
while( line ):
commentpos = line.find('#')
if commentpos != -1:
if line[commentpos-1:commentpos] != "\\":
#print "splitting out comment %s" % line[commentpos:]
line = line[0:commentpos]
if len(line) > 0 :
return_lines.append(line)
line = filehandle.readline()
return return_lines
CommandArgs = sys.argv[1:]
if len(CommandArgs) < 2:
usage()
sys.exit()
mutnamecolumn = 1
ddg_column = 2
mutfile1_ddgs = []
mutfile2_dict = {}
filename1 = ''
filename2 = ''
outlines = []
for arg in CommandArgs:
if arg == '-f1':
filename1 = CommandArgs[CommandArgs.index(arg)+1]
if arg == '-f2':
filename2 = CommandArgs[CommandArgs.index(arg)+1]
elif arg == '-help':
usage()
sys.exit()
outlines.append("Mutation ddG_"+filename1+" ddG_"+filename2+" diff_ddG")
file1 = open(filename1,'r')
file1lines = read_file_to_commentless_linelist( file1 )
file1.close()
file2 = open(filename2,'r')
file2lines = read_file_to_commentless_linelist( file2 )
file2.close()
for line in file2lines:
line_items = line.split()
if len( line_items ) < 2:
continue
mutfile2_dict[ line_items[mutnamecolumn] ] = line_items[ ddg_column ]
#print str( len( mutfile2_dict ) ) + " mutations were found in " + filename2
for line in file1lines:
line_items = line.split()
if len( line_items ) < 2:
continue
this_mutation = line_items[ mutnamecolumn ]
if mutfile2_dict.has_key( this_mutation ):
#print line_items[ddg_column]
#print mutfile2_dict[ this_mutation ]
this_diff = float(line_items[ddg_column]) - float(mutfile2_dict[ this_mutation ])
outlines.append( this_mutation + " " + line_items[ddg_column] + " " + mutfile2_dict[ this_mutation ] + " " + str( this_diff ) )
else:
print "Mutation " + this_mutation + " in file 1 not found in file2."
for outline in outlines:
print outline
|
83cd5862f0cd449523e27b3f1a57a9ff697c544d | DanMayhem/project_euler | /106.py | 1,266 | 3.578125 | 4 | #!python
"""
Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
S(B) ≠ S(C); that is, sums of subsets cannot be equal.
If B contains more elements than C then S(B) > S(C).
For this problem we shall assume that a given set contains n strictly increasing elements and it already satisfies the second rule.
Surprisingly, out of the 25 possible subset pairs that can be obtained from a set for which n = 4, only 1 of these pairs need to be tested for equality (first rule). Similarly, when n = 7, only 70 out of the 966 subset pairs need to be tested.
For n = 12, how many of the 261625 subset pairs that can be obtained need to be tested for equality?
"""
from itertools import combinations
n=12
a = set([i for i in range(n)])
k=0
def must_check_set(a, b):
if len(a)!=len(b):
return True
a = sorted(a)
b = sorted(b)
if a[0] > b[0]:
a, b = b, a
if max(a)<min(b):
return False
for i in range(len(a)):
if a[i] > b[i]:
return True
return False
for i in range(2,len(a)//2+1):
for b in combinations(a, i):
b = set(b)
x = a-b
for c in combinations(x, i):
if must_check_set(b, c):
k+=1
print([k/2,b,c]) |
d4b11fd179d50082c1202401a63f982dfa8d2954 | wmyles/Self_Taught_Programmer | /simulate_queue_two_stacks.py | 1,500 | 4.28125 | 4 | """simulate queue with two stacks
idea is to push items into one stack to show entrance into queue
then pop it into the outstack so items that entered instack first
gets popped out first
"""
class MyQueue:
def __init__(self):
"""
initialize your data structure here.
"""
self.inStack, self.outStack = [], []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.inStack.append(x)
def pop(self):
"""
:rtype: nothing
"""
self.move()#helper function to move items into outstack before popping
return self.outStack.pop()
def peek(self):
"""
:rtype: int
"""
self.move()
return self.outStack[-1]
def empty(self):
"""
:rtype: bool
"""
return self.inStack==[] and self.outStack==[]
def move(self):
"""
:rtype nothing
"""
if self.outStack==[]: #ifoutstack is empty
while self.inStack:
self.outStack.append(self.inStack.pop())
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
queue=MyQueue()
queue.push(1)
queue.push(2)
"""test cases
should be true true and true and true respectively for below code"""
print(queue.peek()==1)
print(queue.pop()==1)
print(queue.empty()==False)
|
802817793ef4f6401a63b0d4b56ff41a4bf28f15 | 2swamped4u/wiser | /dataengineer.csv | 2,949 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 20 12:09:08 2021
@author: javier
"""
# import zipfile
from zipfile import ZipFile
# path to the zipfile
file = './Documents/drive-download-20210220T171123Z-001.zip'
# read zipfile and extract contents
with ZipFile (file, 'r') as zip:
zip.printdir()
zip.extractall()
#Once I have converted dataframes to .csv files, I comment ##
#out the code where I imported the files out of their zipfiles.
# import pandas
# import json
import pandas as pd
import numpy as np
import json
cnames=['c0','c1']
#reading directly into a DataFrame usind pd.read_json()
path = './acervo_1556_1899.json'
#write DataFrame
df = pd.read_json(path)
#write a csv file
df.to_csv('Book1.csv')
#read a csv file
csv_file=pd.read_csv('Book1.csv',
header=None,
index_col=0,
sep='\t',
names=cnames)
#write an excel file
csv_file.to_excel('Book1.xlsx')
#read an excel file
excel_file=pd.read_excel('Book1.xlsx',
sheet_name='Sheet1',
header=None,
index_col=0,
names=cnames)
#writing data in designated excel file, in Sheet3
writer=pd.ExcelWriter(path='Book9.xlsx')
excel_file.to_excel(writer,sheet_name='Sheet3')
writer.save()
#reading directly into a DataFrame usind pd.read_json()
path2 = './acervo_1900_1979.json'
#write DataFrame
df2 = pd.read_json(path2)
#write a csv file
df2.to_csv('Book2.csv')
#read a csv file
csv_file2=pd.read_csv('Book2.csv',
header=None,
index_col=0,
sep='\t',
names=cnames)
#write an excel file
csv_file2.to_excel('Book2.xlsx')
#read an excel file
excel_file2=pd.read_excel('Book2.xlsx',
sheet_name='Sheet1',
header=None,
index_col=0,
names=cnames)
#writing data in designated excel file, in Sheet2
writer=pd.ExcelWriter(path='Book9.xlsx')
excel_file2.to_excel(writer,sheet_name='Sheet2')
writer.save()
# reading directly into a DataFrame usind pd.read_json()
path3 = './acervo_1980_1989.json'
# write DataFrame
df3 = pd.read_json(path3)
# write a csv file
df3.to_csv('Book3.csv')
#read a csv file
csv_file3=pd.read_csv('Book3.csv',
header=None,
index_col=0,
sep='\t',
names=cnames)
#write an excel file
csv_file3.to_excel('Book3.xlsx')
#read an excel file
excel_file3=pd.read_excel('Book3.xlsx',
sheet_name='Sheet1',
header=None,
index_col=0,
names=cnames)
#writing data in designated excel file, in Sheet3
writer=pd.ExcelWriter(path='Book9.xlsx')
excel_file3.to_excel(writer,sheet_name='Sheet3')
writer.save()
|
63f43d8b7d82d282fe7d1e02e52ba28dc04a2236 | deepbhav/Python_Essentials | /Assignment4/Ass_4_2.py | 181 | 3.90625 | 4 | fPtr=lambda no1,no2 : no1*no2
no1=input("Enter first no : ")
no2=input("Enter second no: ")
print("Multiplication of {0} & {1} is : {2} .".format(no1,no2,fPtr(int(no1),int(no2)))) |
f1e35a617e211e1dfefcbd0179b156886bc934ea | Filipe-Amorim1/Scripts-Python | /Aula14/Desafio_63_Fionacci_seq.py | 584 | 4 | 4 | #Escreva um programa que leia um número N inteiro qualquer e
# mostre na tela os N primeiros elementos de uma Sequência de Fibonacci.
# Exemplo: 0 – 1 – 1 – 2 – 3 – 5 – 8
#Sequência de Fibonacci é uma sucessão de números que, misteriosamente, aparece em muitos fenômenos da natureza.
# Descrita no final do século 12 pelo italiano Leonardo Fibonacci, ela é infinita e começa com 0 e 1.
# Os números seguintes são sempre a soma dos dois números anteriores.
# Portanto, depois de 0 e 1, vêm 1, 2, 3, 5, 8, 13, 21, 34
n = int(input('Digite um número: '))
n2 = |
f84a043b312b7e20fa58bffdeee944d8c4f61d3a | Shinpei2/python_source | /sukkiri_python/chapter2/sum_avg.py | 1,114 | 3.703125 | 4 | subject = []
score = []
# 1科目目の受付
subject.append(input("1科目目の科目名を入力して下さい :"))
score.append(input("1科目目の点数を入力して下さい :"))
sub_num = 1
# 追加強化の受付
while True:
print("追加する教科はありますか?")
# prompt inputting until user inputs 1 or 0
while True:
next = int(input("ある場合:1 ない場合:2"))
if next == 1 or next == 2:
break
else:
print("1または2を入力して下さい。")
# nextが1の場合は科目と点数をリストに追加、それ以外の場合はループを抜ける
if next == 1:
sub_num += 1
subject.append(input(f"{sub_num}科目目の科目名を入力して下さい :"))
score.append(input(f"{sub_num}科目目の点数を入力して下さい :"))
else:
break
# 点数の表示
sum = 0
avg = 0
for i in range(len(subject)):
print(f"教科: {subject[i]} 点数:{score[i]}")
sum += int(score[i])
avg = sum / len(subject)
print(f"合計: {sum} 平均:{avg: 1f}")
|
8d81c1a3dda34cf7a1685285f7f5dd9fb9e096b2 | Sofista23/Aula1_Python | /Aulas/Exercícios-Mundo3/Aula021/Ex0103.py | 426 | 3.96875 | 4 | def ficha(nome="",pontos=""):
if nome=="" and pontos=="":
print(f"O jogador <desconhecido> fez 0 ponto(s).")
elif nome=="":
print(f"O jogador <desconhecido> fez {pontos} ponto(s).")
elif pontos=="":
print(f"O jogador {nome} fez 0 ponto(s).")
else:
print(f"O jogador {nome} fez {pontos} ponto(s).")
n=input("Digite seu nome:")
p=input("Quntidade de pontos feitos:")
ficha(n,p) |
a160017fc2a801fcf448df3a6a5b1fdb36fe98be | KenjaminButton/runestone_thinkcspy | /18_classes_and_objects_deeper/18.1.fractions.py | 1,809 | 4.1875 | 4 | # 18.1 Fractions
'''
We have all had to work with fractions when we were younger. Or,
perhaps you do a lot of cooking and have to manage measurements for
ingredients. In any case, fractions are something that we are
familiar with. In this chapter we will develop a class to represent
a fraction including some of the most common methods that we would
like fractions to be able to do.
A fraction is most commonly thought of as two integers, one over the
other, with a line separating them. The number on the top is called
the numerator and the number on the bottom is called the denominator.
Sometimes people use a slash for the line and sometimes they use a
straight line. The fact is that it really does not matter so long as
you know which is the numerator and which is the denominator.
To design our class, we simply need to use the analysis above to
realize that the state of a fraction object can be completely
described by representing two integers. We can begin by implementing
the Fraction class and the __init__ method which will allow the user
to provide a numerator and a denominator for the fraction being
created.
'''
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
def getNum(self):
return self.num
def getDen(self):
return self.den
myfraction = Fraction(3, 4)
print(myfraction)
print(myfraction.getNum())
print(myfraction.getDen())
'''
Note that the __str__ method provides a “typical” looking fraction
using a slash between the numerator and denominator. The figure below
shows the state of myfraction. We have also added a few simple
accessor methods, getNum and getDen, that can return the state values
for the fraction.
'''
|
619289a80a2608907a83189cb91091c0be05bd91 | arjunagarwal899/visual-cryptography | /main.py | 336 | 3.625 | 4 | from encrypt import encrypt
from decrypt import decrypt
def main():
print('Beginning encryption:')
filename = input('Please enter filename (arjun.jpg): ')
encrypt(r'input_images/' + filename)
while input('\nBegin decryption? [y/n]: ') != 'y':
pass
decrypt(r'decrypted_images/' + filename)
if __name__ == '__main__':
main() |
84325782f70e97ea7909fa30b9512f6967b8705b | AnibalUlibarri/development_code | /Programa3.py | 466 | 3.796875 | 4 | #--coding: utf-8--
'''
Desarrollador: Jorge Aníbal Quezada Ulibarri
Función:
Definir una función
que calcule la longitud de una cadena dada
Fecha: Jueves 8 de Marzo del 2018
'''
def calcula(txt):
x=0
print("Haz introducido: ", txt)
for i in txt:
print(str(i)," Posición ", str(x))
x+=1
print("Total de letras: ", str(x))
if __name__ == "__main__":
eltxt = input("Introduce una palabra: ")
calcula(eltxt) #'''add total: 10''' |
78478e59814831a5896e92e21d11fe205e0bf36b | sw005320/chainer | /cupy/manipulation/transpose.py | 3,571 | 3.828125 | 4 | import six
def rollaxis(a, axis, start=0):
"""Moves the specified axis backwards to the given place.
Args:
a (cupy.ndarray): Array to move the axis.
axis (int): The axis to move.
start (int): The place to which the axis is moved.
Returns:
cupy.ndarray: A view of ``a`` that the axis is moved to ``start``.
.. seealso:: :func:`numpy.rollaxis`
"""
ndim = a.ndim
if axis < 0:
axis += ndim
if start < 0:
start += ndim
if not (0 <= axis < ndim and 0 <= start <= ndim):
raise ValueError('Axis out of range')
if axis < start:
start -= 1
if axis == start:
return a
if ndim == 2:
return transpose(a, None)
axes = list(six.moves.range(ndim))
del axes[axis]
axes.insert(start, axis)
return transpose(a, axes)
def swapaxes(a, axis1, axis2):
"""Swaps the two axes.
Args:
a (cupy.ndarray): Array to swap the axes.
axis1 (int): The first axis to swap.
axis2 (int): The second axis to swap.
Returns:
cupy.ndarray: A view of ``a`` that the two axes are swapped.
.. seealso:: :func:`numpy.swapaxes`
"""
ndim = a.ndim
if axis1 >= ndim or axis2 >= ndim:
raise ValueError('Axis out of range')
axes = list(six.moves.range(ndim))
axes[axis1], axes[axis2] = axes[axis2], axes[axis1]
return transpose(a, axes)
def transpose(a, axes=None):
"""Permutes the dimensions of an array.
Args:
a (cupy.ndarray): Array to permute the dimensions.
axes (tuple of ints): Permutation of the dimensions. This function
reverses the shape by default.
Returns:
cupy.ndarray: A view of ``a`` that the dimensions are permuted.
.. seealso:: :func:`numpy.transpose`
"""
ndim = a.ndim
a_shape = a._shape
a_strides = a._strides
ret = a.view()
if not axes:
if ndim > 1:
ret._shape = a_shape[::-1]
ret._strides = a_strides[::-1]
ret._c_contiguous, ret._f_contiguous = \
a._f_contiguous, a._c_contiguous
return ret
if ndim != len(axes):
raise ValueError('Invalid axes value: %s' % str(axes))
if ndim <= 2:
if ndim == 0:
return ret
elif ndim == 1:
if axes[0] == 0:
return ret
else:
axis0, axis1 = axes
if axis0 == 0 and axis1 == 1:
return ret
elif axis0 == 1 and axis1 == 0:
ret._shape = a_shape[::-1]
ret._strides = a_strides[::-1]
ret._c_contiguous, ret._f_contiguous = \
a._f_contiguous, a._c_contiguous
return ret
raise ValueError('Invalid axes value: %s' % str(axes))
for axis in axes:
if axis < -ndim or axis >= ndim:
raise IndexError('Axes overrun')
axes = [axis % ndim for axis in axes]
a_axes = list(six.moves.range(ndim))
if a_axes == axes:
return ret
if a_axes == axes[::-1]:
ret._shape = a_shape[::-1]
ret._strides = a_strides[::-1]
ret._c_contiguous, ret._f_contiguous = \
a._f_contiguous, a._c_contiguous
return ret
if a_axes != sorted(axes):
raise ValueError('Invalid axes value: %s' % str(axes))
ret._shape = tuple([a_shape[axis] for axis in axes])
ret._strides = tuple([a_strides[axis] for axis in axes])
ret._c_contiguous = -1
ret._f_contiguous = -1
return ret
|
9af8c07639941bcb4e3b76475b6f4c8e0b5d2758 | shbnmzr/Power-Compiler | /Power/Lexer.py | 4,717 | 3.5 | 4 | from . import Constants
from .Token import Token
from .Error import LexicalError
from .Code import Code
class Lexer:
'''
Lexer Stand alone Class
Attributes
----------
Tokenized : bool
A boolean attribute that prevents a code from repeatative Tokenization.
CurrentToken : int
Current Token id used with "Tokens".
Tokens : list
List contains a sort of "Token" class instances.
Code : Code
an instance of Code class from user input
Methods
-------
Tokenizer():
Extracts language tokens from user's input code and updates "Tokens" attribute.
GetNextToken():
Returns instance of Token class for the very next token (None for n+1).
LastTokenRetrived():
Returns instance of Token class for last token returned by GetNextToken method.
ResetTokenPointer():
Sets CurrentToken attribute to 0.
SetTokenPointer(n):
Sets CurrentToken to n.
'''
def __init__(self,Code):
self.Tokenized = False
self.CurrentToken = 0
self.LineNumber = 1
self.Tokens = []
self.Code = Code
def Tokenizer(self):
if self.Tokenized is True:return False
'''
Extracts language tokens from user's input code.
Then updates "Tokens" attribute.
Parameters:
Code
Returns:
None
'''
for Line in self.Code.PowerCode.splitlines():
if Line.startswith("//"): continue
for ProbableToken in Line.split(" "):
if ProbableToken in "\t\n ": continue
ProbableToken = ProbableToken.strip()
if ProbableToken == '//': break
if ProbableToken in Constants.Keywords:
self.Tokens.append(Token("KEYWORD", ProbableToken))
elif ProbableToken in Constants.Operators:
self.Tokens.append(Token("OPERATOR", ProbableToken))
elif ProbableToken in "[]{}()=,^":
self.Tokens.append(Token("DELIMITER", ProbableToken))
elif ProbableToken.isdigit():
self.Tokens.append(Token("INTEGER", ProbableToken))
elif ProbableToken.count('.') == 1 and ProbableToken.replace(".","").isdigit():
self.Tokens.append(Token("FLOAT", ProbableToken))
elif ProbableToken[0] == '"' and ProbableToken[-1] == '"':
if len(ProbableToken) == 3:
self.Tokens.append(Token("CHAR", ProbableToken))
else:
self.Tokens.append(Token("STRING", ProbableToken))
else:
if ProbableToken.startswith('&'):
self.Tokens.append(Token("SPECIALCHAR", '&'))
ProbableToken = ProbableToken[1:]
if ProbableToken.replace('_','').isalnum() and not ProbableToken[0].isdigit() :
self.Tokens.append(Token("IDENTIFIER", ProbableToken))
else:
#print(LexicalError(self.LineNumber, ProbableToken))
pass
self.LineNumber += 1
self.Tokenized = True
def GetNextToken(self):
'''
Returns instance of Token class for the very next token (None for n+1).
Parameters:
None
Returns:
self.Tokens[self.CurrentToken - 1]
'''
if self.Tokenized is False: self.Tokenizer()
self.CurrentToken += 1
if self.CurrentToken <= len(self.Tokens):
return self.Tokens[self.CurrentToken - 1]
else:
return None
def ReturnNextToken(self):
if self.CurrentToken <= len(self.Tokens):
return self.Tokens[self.CurrentToken - 1]
else:
return None
def LastTokenRetrived(self):
return self.Tokens[self.CurrentToken]
def ResetTokenPointer(self):
self.CurrentToken = 0
def SetTokenPointer(self,n):
if n <= len(self.Tokens): self.CurrentToken = n
@classmethod
def LexLine(self, Text):
LineTokens = []
Text = Code.TrimLine(Text)
for ProbableToken in Text.split(" "):
if ProbableToken in "\t\n ": continue
ProbableToken = ProbableToken.strip()
if ProbableToken == '//': break
if ProbableToken in Constants.Keywords:
LineTokens.append(Token("KEYWORD", ProbableToken))
elif ProbableToken in Constants.Operators:
LineTokens.append(Token("OPERATOR", ProbableToken))
elif ProbableToken in "[]{}()=,^":
LineTokens.append(Token("DELIMITER", ProbableToken))
elif ProbableToken.isdigit():
LineTokens.append(Token("INTEGER", ProbableToken))
elif ProbableToken.count('.') == 1 and ProbableToken.replace(".","").isdigit():
LineTokens.append(Token("FLOAT", ProbableToken))
elif ProbableToken[0] == '"' and ProbableToken[-1] == '"':
if len(ProbableToken) == 3:
LineTokens.append(Token("CHAR", ProbableToken))
else:
LineTokens.append(Token("STRING", ProbableToken))
else:
if ProbableToken.startswith('&'):
LineTokens.append(Token("SPECIALCHAR", '&'))
ProbableToken = ProbableToken[1:]
if ProbableToken.replace('_','').isalnum() and not ProbableToken[0].isdigit() :
LineTokens.append(Token("IDENTIFIER", ProbableToken))
else:
#print(LexicalError(0, ProbableToken))
pass
return LineTokens |
30f7098d16ef7dda11b9aef5b03a7e0ccaf34916 | Redster11/NGCP_UGV_2019-2020 | /ReferenceCode/Kyle/SUGV_driving_test/controllers/keyboard_controller_with_deceleration/keyboard_controller_with_deceleration.py | 2,329 | 3.75 | 4 | """keyboard controller with deceleration for SUGV"""
from controller import Robot, Motor, Keyboard
MAX_SPEED = -10
# TIME_STEP = 64
INCREMENT = 0.1
rightSpeed = 0
leftSpeed = 0
# create Robot
robot = Robot()
# create keyboard
kb = robot.getKeyboard()
kb.enable(250)
# instantiate devices on Robot
wheels = [Motor("Motor_LB"), Motor("Motor_LF"), Motor("Motor_RB"), Motor("Motor_RF")]
# get timestep
TIME_STEP = int(robot.getBasicTimeStep())
# set target position to infinity (speed control)
for i in range(0,4):
wheels[i].setPosition(float('inf'))
wheels[i].setVelocity(0.0)
while (robot.step(TIME_STEP) != -1):
# poll keyboard key
key = kb.getKey()
# print(key)
# DRIVING LOGIC
# forward
if(key == ord('W')):
leftSpeed += INCREMENT
rightSpeed += INCREMENT
if(leftSpeed >= MAX_SPEED):
leftSpeed = MAX_SPEED
if(rightSpeed >= MAX_SPEED):
rightSpeed = MAX_SPEED
# print("w:%f:%f" %(leftSpeed, rightSpeed))
# reverse
if(key == ord('S')):
leftSpeed -= INCREMENT
rightSpeed -= INCREMENT
if(leftSpeed <= -1*MAX_SPEED):
leftSpeed = -1*MAX_SPEED
if(rightSpeed <= -1*MAX_SPEED):
rightSpeed = -1*MAX_SPEED
# print("s:%f:%f" %(leftSpeed, rightSpeed))
# turn left
if(key == ord('A')):
leftSpeed -= INCREMENT
rightSpeed += INCREMENT
if(leftSpeed <= -1*MAX_SPEED):
leftSpeed = -1*MAX_SPEED
if(rightSpeed >= MAX_SPEED):
rightSpeed = MAX_SPEED
# print("a:%f:%f" %(leftSpeed, rightSpeed))
# turn right
if(key == ord('D')):
leftSpeed += INCREMENT
rightSpeed -= INCREMENT
if(leftSpeed >= MAX_SPEED):
leftSpeed = MAX_SPEED
if(rightSpeed <= -1*MAX_SPEED):
rightSpeed = -1*MAX_SPEED
# print("d:%f:%f" %(leftSpeed, rightSpeed))
# no input
if(key == -1):
if(leftSpeed != 0):
if(leftSpeed < 0):
leftSpeed += 3*INCREMENT
if(rightSpeed > 0):
leftSpeed -= 3*INCREMENT
else:
leftSpeed = 0
if(rightSpeed != 0):
if(rightSpeed < 0):
rightSpeed += 3*INCREMENT
if(rightSpeed > 0):
rightSpeed -= 3*INCREMENT
else:
rightSpeed = 0
# print(" :%f:%f" %(leftSpeed, rightSpeed))
# set speed
for i in range(0,2):
wheels[i].setVelocity(leftSpeed)
wheels[i+2].setVelocity(rightSpeed)
pass |
5569f066a749791e1cb5d1cfabcfdf79defae72e | Devikd/prog2 | /20.3.18.4.py | 167 | 4.09375 | 4 | def factoriyal(n):
if n == 0:
return 1
else:
return n * factorial (n-1)
n = int("input a number to compute the factorial"))
print factoriyal(n))
|
e13cabd21775ff8231a57a6f8f3e3f389338e0f0 | signalwolf/Leetcode_by_type | /近期谷歌高频题/676. Implement Magic Dictionary.py | 2,945 | 3.71875 | 4 | # coding=utf-8
# 没考虑的情况是如果两个word本身就存在互相间的关系,那么你就不能exclude掉它
# 例如:
# ["MagicDictionary", "buildDict", "search", "search", "search", "search"]
# [[], [["hello","hallo","leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
# 第一个hello是true,因为hello match到了 hallo上。
# 但是有更简单的,见最后
class MagicDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.exclude = set()
self.wordset = {}
def buildDict(self, dict):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
for word in dict:
self.exclude.add(word)
for i in xrange(len(word)):
new_word = word[:i] + '_' + word[i + 1:]
if new_word not in self.wordset:
self.wordset[new_word] = word
elif self.wordset[new_word] == 0:
self.exclude.discard(word)
else:
self.exclude.discard(self.wordset[new_word])
self.exclude.discard(word)
self.wordset[new_word] = 0
def search(self, word):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""
if word in self.exclude: return False
for i in xrange(len(word)):
new_word = word[:i] + '_' + word[i + 1:]
if new_word in self.wordset:
return True
return False
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dict)
# param_2 = obj.search(word)
class MagicDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.pool = {}
self.dic = set([])
def buildDict(self, dict):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
self.pool = {}
for word in dict:
self.dic.add(word)
for i in range(len(word)):
tmp = word[:i]+"*"+word[i+1:]
if tmp in self.pool:
self.pool[tmp] += 1
else:
self.pool[tmp] = 1
def search(self, word):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
:type word: str
:rtype: bool
"""
for i in range(len(word)):
tmp = word[:i]+"*"+word[i+1:]
if tmp in self.pool and (self.pool[tmp] > 1 or (self.pool[tmp] == 1 and word not in self.dic)):
return True
return False
|
6ffa66e716d7e0c4e4939ce2c696133e1a7d8a0e | blueclowd/leetCode | /python/0861-Score_after_flipping_matrix.py | 1,171 | 3.75 | 4 | '''
Description:
We have a two dimensional matrix A where each value is 0 or 1.
A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.
After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score.
'''
class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
n_rows, n_cols = len(A), len(A[0])
for row_idx, row in enumerate(A):
if row[0] == 0:
A[row_idx] = [1 - cell for cell in row]
for col_idx in range(1, n_cols):
n_ones = sum([A[row_idx][col_idx] for row_idx in range(n_rows)])
n_zeros = n_rows - n_ones
if n_zeros > n_ones:
for row_idx in range(n_rows):
A[row_idx][col_idx] = 1 - A[row_idx][col_idx]
total_sum = 0
for row in A:
row_sum = 0
for idx in range(n_cols):
row_sum = row_sum * 2 + row[idx]
total_sum += row_sum
return total_sum
|
0fce5b815abbc4dd43e9172a6cd33fd1e35321d7 | hhwe/gopher | /algorithm/sort.py | 638 | 4.125 | 4 | def BubbleSort(Iterator):
""" 冒泡排序 """
a = list(Iterator)
for i in range(len(a)):
for j in range(len(a)-1-i):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
return a
def InsertSort(Iterator):
""" 插入排序 """
a = list(Iterator)
for i in range(1, len(a)):
for j in range(i, 0, -1):
if a[j] < a[j-1]:
a[j], a[j-1] = a[j-1], a[j]
return a
def main():
data = [74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586]
print(BubbleSort(data))
print(InsertSort(data))
if __name__ == '__main__':
main() |
df2f1f8f2bbb1d8efe1010a178521331c9a25980 | Python-aryan/Hacktoberfest2020 | /RockPaperScissors.py | 753 | 3.875 | 4 | from random import *
l=['R','P','S']
def game(n):
x = randint(1,3)
if (x==1):
k='Rock'
if (x==2):
k='Paper'
if (x==3):
k='Scissors'
if(n==l[0] and (x==3)):
print("You Win")
print("Computer: "+ k)
return ()
if(n==l[1] and x==1):
print("You Win")
print("Computer: "+ k)
return ()
if(n==l[2] and x==2):
print("You Win")
print("Computer: "+ k)
return ()
if(n==l[0] and x==1) or (n==l[1] and x==2) or (n==l[2] and x==3):
print('Draw')
print("Computer: "+ k)
return ()
else:
print('You Lose')
print("Computer: "+ k)
return ()
print("WELCOME LETS PLAY:")
print("R:Rock")
print("P:Paper")
print("S:Scissors")
name = input("What's your choice?\n ")
if(name in l):
game(name)
else:
print("Invalid Choice")
|
e6df62e6e2ce2acb07606e53e97b17b444233deb | sotsoguk/elementsOfPI | /primes_sieve.py | 960 | 4.25 | 4 | # Elements of Programming Interviews
# Chapter 05 - Arrays
# 5.9 Enumerate all primes up to n
#
# O(n/2 + n/3 + n/5 + n/7 +...) = O(nlog logn)
def generate_primes(n):
if n < 2:
return []
primes = []
is_prime = [False,False]+[True]*(n-1)
for p in range(2,n+1):
if is_prime[p]:
primes.append(p)
for i in range(p,n+1,p):
is_prime[i] = False
return primes
def generate_primes2(n):
if n<2:
return []
primes = [2]
# check only odd numbers 3,5,7, .. n (or n-1)
# index with i ==> p = 2*i+3 => size = (n-3)//2 +1
size = (n-3)//2 +1
is_prime = [True] *size
for i in range(size):
if is_prime[i]:
p = 2*i + 3
primes.append(p)
for j in range(2*i**2+6*i+3,size,p):
is_prime[j] = False
return primes
if __name__ == "__main__":
print(generate_primes(100))
print(generate_primes2(100))
|
59836f42b45f18eaf5196bd944d8943c29bb4313 | Myduzo/holberton-system_engineering-devops | /0x16-api_advanced/0-subs.py | 526 | 3.65625 | 4 | #!/usr/bin/python3
"""
function that queries the Reddit API and returns the number of subscribers.
"""
import requests
def number_of_subscribers(subreddit):
"""method that returns the number of subs"""
url = "https://www.reddit.com/r/{}/about.json".format(subreddit)
headers = {"User-agent": "Myduzo"}
subs = requests.get(url, headers=headers).json()
if subreddit is None:
return 0
try:
total = subs["data"]["subscribers"]
return total
except KeyError:
return 0
|
7d262c6fb15b6a51853e5702e6f5e1a4f0f8a58d | olutoni/pythonclass | /number_exercises/numbers_01.py | 371 | 3.921875 | 4 | number = 100
i = 4.7
int_value = 1
string_value = '1.5'
# prints the type of the variables defined above
print(type(number))
print(type(i))
print(type(int(i)))
float_value = float(int_value)
print('\nint value as a float:', float_value)
print(type(float_value))
float_value = float(string_value)
print('string value as a float:', float_value)
print(type(float_value))
|
a957eb0f5ed98e8901391fdf488561936f51bb13 | LeeEunHak/Python_Study | /CHAPTER06_리스트/mySort.py | 693 | 3.9375 | 4 | # 선택 정렬을 구현하는 함수
def selectionSort(alist):
for i in range(len(alist)):
least=i # i를 최솟값으로 간주
leastValue=alist[i]
for k in range(i+1, len(alist)): # (i+1)번부터 비교하기
if alist[k] < leastValue: # k번째 요소가 현재의 최솟값보다 작으면
least=k # k번째 요소를 최솟값으로 한다.
leastValue=alist[k]
alist[i],alist[least]=alist[least],alist[i] # i번째 요소와 최솟값을 교환
if __name__=="__main__":
list1=[7, 9, 5, 1, 8]
selectionSort(list1)
print(list1)
|
c1a9649a8d8fb4accce2cce6b22050445a9881b5 | matthewvarga/web-crawler | /spider.py | 1,652 | 3.5625 | 4 | import urlparse
import urllib
from bs4 import BeautifulSoup
def crawl(website, fileName):
url = website
urlQueue = [url] #starts with the website home page url
urlHistory = [url] #keeps track of every single url visited
urlFile = open("{0}.json".format(fileName),"w")
urlFile.write(url)
urlFile.write("\n")
while len(urlQueue) > 0: #while we have links to still visit
try: #prevents program from crashing if website url is invalid
htmlText = urllib.urlopen(urlQueue[0]).read() #gets the html text of url at top of queue
except:#what happens if there is an error trying to open webpage
print urlQueue[0] #prints url we could not open
soup = BeautifulSoup(htmlText, "html.parser")
urlQueue.pop(0) #removes the url at top of queue after we have scraped it
print len(urlQueue)
for tag in soup.findAll("a", href=True): #finds the <"a"> tag, and if it has a valid href/link continues
tag["href"] = urlparse.urljoin(url,tag["href"]) #if the link is missing http://.... this adds it
if url in tag["href"] and tag["href"] not in urlHistory: #checks if the link is actually part of the site, not fb or twitter or spam, then checks if we have visited link yet or not, if not continues
urlQueue.append(tag["href"]) #adds the new/unvisited url that we found to the queue
urlHistory.append(tag["href"]) #stores the new url in history
urlFile.write(str(tag["href"]))
urlFile.write("\n")
crawl("http://www.example.com", "output_file_name")
|
85313437dd96f2768d1ee587f39a830e74cdb4ab | zenje/chinese-english-lookup | /chinese_english_lookup/__init__.py | 653 | 3.671875 | 4 | """Contains utilities for Chinese-English dictionary, HSK3.0, and HSK2.0.
Usage examples:
dictionary = Dictionary()
found_word_entry = dictionary.lookup('词典')
hsk3 = HSK3()
intermediate_words = hsk3.get_intermediate()
for word in intermediate_words:
print(word)
hsk2 = HSK2()
level_3_words = hsk2.get_words_for_level(3)
for word in level_3_words:
print(word)
"""
from .dictionary import Dictionary
from .hsk2 import HSK2
from .hsk3 import HSK3, Category as HSK3Category
__all__ = ["Dictionary", "HSK2", "HSK3", "HSK3Category"]
|
cd7bf1778bfa14baaa00fdfd588e7b41afbbec62 | nhs0912/algoAvengers | /leetCode/heeseok/912. Sort an Array.py | 947 | 3.5 | 4 | class Solution:
# exchange a to b
def exchange(self, nums: List[int], aIndex, bIndex):
tmp = nums[aIndex]
nums[aIndex] = nums[bIndex]
nums[bIndex] = tmp
# Make a Selection Sort
def selectSort(self, nums: List[int]) -> List[int]:
numsSize = len(nums)
#두번째부터 제일 작은 수를 검색한다.
for i in range(1,numsSize):
# 첫번재 수
firstNum = nums[i-1]
firstNumIndex = i-1
smallNum = nums[i]
smallNumIndex = i
for j in range(i,numsSize):
if smallNum > nums[j]:
smallNum = nums[j]
smallNumIndex = j
if smallNum < firstNum:
self.exchange(nums,firstNumIndex,smallNumIndex)
return nums
# Order Sort
def sortArray(self, nums: List[int]) -> List[int]:
return self.selectSort(nums)
|
11882634355536524fd71e9f51f1e8ce4ced58df | mnbotk/python_study | /if_comp1.py | 111 | 3.890625 | 4 |
# coding: utf-8
nums1 = [1, 3, 7, 10, 9, 15, 20, 30]
nums2 = [n for n in nums1 if (n % 3) == 0]
print(nums2)
|
337bd607fda0442c329002b8a6b131e53a442fb9 | jdnorton22/LAPython | /input.py | 301 | 4.21875 | 4 | name = input("What is your name?: ")
color = input("What is your favorite color?: ")
age = int(input("How old are you today?: "))
print("{} is {} years old and loves the color {}.".format(name.upper(), age, color.upper()))
print(name, "is", age, "years old and loves the color", color + ".", sep=" ") |
8a04a7f3e5d46bd9863c0d85ebfd135da9d183aa | UraraEiss/python_test | /determine.py | 154 | 3.8125 | 4 | #!/usr/bin/python
n = input("输入数字:")
n = int(n)
if n == 10:
print("相等")
elif n > 10:
print("大于")
else:
print("小于")
|
42f4ea951ca89eeed55c8ed6fd5af2558598cfff | pecanjk/leetcode_solution | /22_generateParenthesis.py | 634 | 4.21875 | 4 | '''
括号生成
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
'''
def generateParenthesis(n):
result=[]
backtracking(n,0,0,'',result)
return result
def backtracking(n,left,right,s,result):
if left<right:
return
if left==n and right==n:
print('s ',s)
result.append(s)
return
if left<n:
backtracking(n,left+1,right,s+'(',result)
if right<n:
backtracking(n,left,right+1,s+')',result)
if __name__=="__main__":
out=generateParenthesis(3)
print(out)
|
115df8ac7b0c1b87b977e68049c15c88926ed348 | fessupboy/python_bootcamp_6 | /NestedStatements_Scope/NestedStatements_Scope.py | 523 | 4.09375 | 4 | # x =25
#
# def printer():
# x = 50
# return x
# print(x)
#
# print(printer())
#GLOBAL
# name = "THIS IS A GLOBAL STRING"
# def greet():
# #ENCLOSING
# name = 'SAMMY'
#
# def hello():
# #LOCAL
# name = "I'M A LOCAL"
# print("HELLO " +name)
# hello()
# greet()
x = 50
def func(x):
#global x
print(f"X is {x}")
#LOCAL REASSIGNMENT ON A GLOBAL VARIABLE
x = "NEW VALUE"
print(f"I JUST LOCALLY CHANGED X TO {x}")
return x
print(x)
x = func(x)
print(x) |
f23b81403fcb782cf378804a7116e1984db09632 | yen-nhi/algorithms | /Online Judge/10986 - Sending email.py | 936 | 3.609375 | 4 | #On Weighted Graph: Dijkstra’s, Easier
import heapq
def read_input():
n, m, s, t = (int(i) for i in input().split())
adjacent = [[] for i in range(n)]
for i in range(m):
u, v, w = (int(j) for j in input().split())
adjacent[u].append((w, v))
adjacent[v].append((w, u))
return adjacent, s, t, n
def dijkstra(adjacent, s, t, n):
prior_q = [(0, s)]
heapq.heapify(prior_q)
dist = [None] * n
while prior_q:
(d, u) = heapq.heappop(prior_q)
if dist[u] == None:
dist[u] = d
if u == t:
return dist[u]
for (w, v) in adjacent[u]:
if dist[v] == None:
heapq.heappush(prior_q, (d+w, v))
return 'unreachable'
if __name__ == "__main__":
test = int(input())
for num in range(test):
adjacent, s, t, n = read_input()
print('Case #' + str(num+1) + ':', dijkstra(adjacent, s, t, n))
|
1016a131fbf5b375b511317cbddd70b80716294b | Suryamadhan/9thGradeProgramming | /CPLab_21/RPSRunner.py | 1,045 | 4.34375 | 4 | """
Lab 21.2 Rock Paper Scissors
--------
In this lab, you will create a Rock, Paper, Scissors game.
The user will input one of the three choices, and the computer
will pick one at random. The winner will be determined by the
rules of Rock, Paper, Scissors that you play in the real world.
"""
from RockPaperScissors import *
def main():
response = "Y"
"""
while response is "Y" or "y"
user input "Rock-Paper-Scissors - pick your weapon[R,P,S]:: "
rps = new RockPaperScissors object - user input is parameter
print rps
print the output of determineWinner() on rps
response = user input: "Do you want to play again?"
"""
while response == "Y" or response == "y":
rps = RockPaperScissors(input("Rock-Paper-Scissors - pick your weapon[R,P,S]:: "))
print(rps)
print(rps.determineWinner())
response = (input("Do you want to play again? "))
if response == "Yes" or response == "yes" or response == "YES":
main()
main()
|
08f1a335a05c551b157ac55822fb4b12a846680c | ellynhan/challenge100-codingtest-study | /hall_of_fame/lysuk96/DFS_BFS/LTC_200.py | 1,461 | 3.890625 | 4 | '''
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is '0' or '1'.
'''
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def dfs(i,j):
if i<0 or i>=len(grid)\
or j<0 or j>= len(grid[0])\
or grid[i][j] != '1':
return
grid[i][j]=0
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j-1)
dfs(i,j+1)
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs(i,j)
count+=1
return count
solution = Solution()
print(solution.numIslands(grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]))
|
84825ae91c4b27360e3f52f1ee8f19caf7ed9e8f | loliveira-ds3x/robos-santander | /Python/Packages/ETLs/Xls_to_csv.py | 3,895 | 3.5625 | 4 | import pandas as pd
def Xls_to_csv_method(input_file=None, input_file_tab1=None,index_columns=None,column_names=[],output_file=None,skiped_rows=[]):
try:
#logging.info('Iniciando tratamentos do arquivo. Convertendo em csv.')
#lê o excel, renomeia colunas e salva o csv
df = pd.read_excel('/home/ds3x/robos-santander/Outputs/'+input_file, input_file_tab1, usecols = index_columns, skiprows=skiped_rows)
df.columns = column_names
df.to_csv('/home/ds3x/robos-santander/Outputs/'+output_file, index = False, header=True, sep='|')
except Exception as e:
print(e)
#logging.error('Erro ao fazer tratamento do arquivo')
else:
print('Sucesso excel_to_csv')
#logging.info('Csv gerado com sucesso')
def Pivot_excel_to_csv_method(input_file=None,input_file_tab1=None,output_file=None,headers=None,skiped_rows=[],column_names=[],nrows=None):
try:
print(input_file)
df = pd.read_excel('/home/ds3x/robos-santander/Outputs/'+input_file, input_file_tab1,header=headers, skiprows=skiped_rows,nrows=nrows)
pivot = df.melt(id_vars=["Unnamed: 2"], var_name="Date", value_name="Value").drop([0, 1]).drop(columns=["Unnamed: 2"])
pivot.columns = column_names
pivot.to_csv('/home/ds3x/robos-santander/Outputs/'+output_file, index = False, header=True, sep='|')
except Exception as e:
print(e)
#logging.error('Erro ao fazer tratamento do arquivo')
else:
print('Sucesso pivo_excel_to_csv')
#logging.info('Csv gerado com sucesso')
def Fipezap_pivot_method(input_file=None, input_file1_tab=None, output_file=None,header=[0,1,2,3]):
try:
df = pd.read_excel('/home/ds3x/robos-santander/Outputs/'+input_file, sheet_name=input_file1_tab,header=[0,1,2,3])
print(df)
except Exception as e:
print(e)
print('erro ao ler excel')
#try:
# df.columns = ['_'.join(col)for col in df.columns]
#except Exception as e:
# print(e)
# print('erro no merge de colunas')
#try:
# df = df.rename(columns = {'Índice FipeZap_Unnamed: 1_level_1_Unnamed: 1_level_2_Data':'Data'})
#except Exception as e:
# print(e)
# print('erro ao renomear colunas')
#try:
# df = df.drop('Unnamed: 0_level_0_Unnamed: 0_level_1_Unnamed: 0_level_2_Unnamed: 0_level_3', 1)
#except Exception as e:
# print(e)
# print('erro ao dropar colunas')
#try:
# df1 = pd.melt(df, id_vars =['Data'])
#except Exception as e:
# print(e)
# print('erro ao erro ao pivotar')
#try:
# df1[['tipo', 'categoria','calculo','colunas']] = df1['variable'].str.split('_', n=3, expand=True)
#except Exception as e:
# print(e)
# print('erro ao renomear colunas pivot')
#try:
# df1 = df1.drop('variable', 1)
# df1.dropna(inplace=True)
#except Exception as e:
# print(e)
# print('erro ao tratar nulos')
try:
df.to_csv('/home/ds3x/robos-santander/Outputs/'+output_file, index = False, header=True, sep='|')
except Exception as e:
print(e)
print('erro ao converter df em csv')
else:
print('Sucesso Fipezap_pivot')
def Pivot_excel_to_csv_method_generic(input_file=None,input_file_tab1=None,output_file=None,headers=[],column_names=[]):
try:
df = pd.read_excel('/home/ds3x/robos-santander/Outputs/'+input_file, input_file_tab1,header=headers)
df = df.drop('Unnamed: 0', 1)
df1 = df[["Mês", "Admissões", "Desligamentos"]]
df1.columns = column_names
df1 = pd.melt(df1, id_vars =['period'], var_name="nome", value_name="value")
df1.dropna(inplace=True)
df1.to_csv('/home/ds3x/robos-santander/Outputs/'+output_file, index = False, header=True, sep='|')
except Exception as e:
print(e)
#logging.error('Erro ao fazer tratamento do arquivo')
else:
print('Sucesso pivo_excel_to_csv')
#logging.info('Csv gerado com sucesso') |
1f9f1a5589fe7009bf46e7a9a86fc9c6dae15080 | mradrianhh/aha478 | /2_2/task_1.py | 505 | 3.8125 | 4 | import numpy as np
# Creates a ndarray of shape (100, ) with np.arange, then reshapes it into a ndarray of shape (10, 10).
x = np.arange(-49, 51).reshape((10, 10))
print(x<0)
# Creates a new array of boolean values determined by the evaluation the boolean expression.
y = (x**2 - 500) > 0
# Sets every value in x that satifies the boolean expression given by y to 0.
x[y] = 0
# Loops through y and checks if its True, if it is, set the value to np.nan, else, x^2-0.2.
z = np.where(y, np.nan, x**2-0.2) |
60d4f8bdfa2fd68fefbda48763320a6a590edd84 | xulihang/misc | /python/计算机技术课算法作业/2/printList.py | 136 | 3.8125 | 4 | list1=[["life","is"],["nothing","but"],["a"],["game"]]
for innerList in list1:
for element in innerList:
print(element)
|
5bc64901d0082cd4c45451313ce1b1e73bf8e397 | niikasa/solutions | /fibonacci.py | 1,311 | 4.15625 | 4 | import time
# Calculate Fibonacci by recursive method
def fib(n):
if n == 1 or n == 2:
result = 1
else:
result = fib(n-1) + fib(n-2)
return result
# Calculate Fibonacci using memoization
def fib_2(n, memo):
if memo[n] is not None:
return memo[n]
if n == 1 or n == 2:
result = 1
else:
result = fib_2(n-1,memo) + fib_2(n-2, memo)
memo[n] = result
return result
def fib_memo(n):
memo = [None] * (n+1)
return fib_2(n,memo)
# Calculate Fibonacci using bottom_up approach.
def fib_bottom_up(n):
if n == 1 or n == 2:
return 1
bottom_up = [None] * (n+1)
bottom_up[1] = 1
bottom_up[2] = 1
for i in range(3, n+1):
bottom_up[i] = bottom_up[i-1] + bottom_up[i-2]
return bottom_up[n]
def main():
n = 35
start = time.time()
print("F({}) = {}".format(n,fib(n)))
end = time.time()
print(end - start, "seconds, recursive method\n")
start = time.time()
print("F({}) = {}".format(n,fib_memo(n)))
end = time.time()
print(end - start, "seconds, memoization method\n")
start = time.time()
print("F({}) = {}".format(n,fib_bottom_up(n)))
end = time.time()
print(end - start, "seconds, bottom-up method")
if __name__ == "__main__":
main()
|
0ace45ffb0b707d29d81a48253dbd69e211efe71 | dbalesteri/Python_Projects | /webpage_generator/webpage_generator_gui.py | 2,084 | 3.84375 | 4 | # Dan Balesteri - Python 3.9.0 - Windows 10
#
# Web Page Generator Assignment - The Tech Academy
#
# Your task is to create a GUI with Tkinter that will enable
# the users to set the body text for a newly-created web page.
# There should also be a control in the GUI that initiates the
# process of making the new web page.
#
# Set a new body text of your choice.
#
# The GUI should open the html file in a new tab within your
# browser that displays the newly added text from the user.
import os, webbrowser, os.path
from tkinter import *
from tkinter import messagebox
import tkinter as tk
# import other module
import webpage_generator_main
import webpage_generator_func
def load_gui(self):
self.lbl_title = tk.Label(self.master, text="Create a webpage!", font=('TkDefaultFont',20))
self.lbl_title.grid(row=0,column=1,padx=(10,10),pady=(20,10),sticky=W)
self.lbl_fileName = tk.Label(self.master, text="Enter desired file name (omit extention):")
self.lbl_fileName.grid(row=1,column=0,padx=(20,10),pady=(0,0),sticky=W)
self.txt_fileName = tk.Entry(self.master, text="", width=40)
self.txt_fileName.grid(row=1, column=1, columnspan=2, padx=(20,10),pady=(10,10),sticky=W)
self.lbl_instruction = tk.Label(self.master, text="Enter desired body text below:")
self.lbl_instruction.grid(row=3,column=0,padx=(20,10),pady=(0,0),sticky=W)
self.txt_body = tk.Text(self.master) #used Text() widget for multi line entry instead of Entry
self.txt_body.grid(row=4, column=0, columnspan=3, padx=(20,10),pady=(10,10),sticky=W)
self.btn_create = tk.Button(self.master,width=16,height=2,text="Create Webpage!",command=lambda: webpage_generator_func.createFile(self))
self.btn_create.grid(row=5,column=0,padx=(60,10),pady=(10,10),sticky=W)
self.btn_close = tk.Button(self.master,width=16,height=2,text="Close Program",command=lambda: webpage_generator_func.ask_quit(self))
self.btn_close.grid(row=5,column=2,padx=(10,60),pady=(10,10),sticky=E)
if __name__ == "__main__":
pass
|
ebafab1342094a99488d7e4ac3024f248b5275b2 | AustenHsiao/CS199 | /Su_2019_Term_1/Exam/Final_Example_2.py | 404 | 3.59375 | 4 | #Second final problem for CS199 practice
user_list = []
user_in = int(input("Enter positive integers (-1 to terminate): "))
while user_in != -1:
user_list.append(user_in)
user_in = int(input("Enter positive integers (-1 to terminate): "))
mean = sum(user_list)/len(user_list)
count = 0
for each in user_list:
if each % 2 == 0 and each <= mean + 10 and mean - 10 <= each:
count += 1
print(count)
|
880a5055a6c1982c1dc95d56d4b6a0cc4a6fd0a3 | iamslash/learntocode | /leetcode2/MergeStringsAlternately/a.py | 1,010 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# Copyright (C) 2021 by iamslash
# 16ms 100.00% 14.3MB 33.33%
# brute force
# O(N) O(1)
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
ans = ""
for a, b in zip(word1, word2):
ans += a + b
min_len = min(len(word1), len(word2))
additional = ""
if len(word1) > len(word2):
additional = word1[min_len:]
else:
additional = word2[min_len:]
return ans + additional
# 24ms 100.00% 14.4MB 33.33%
# brute force
# O(N) O(1)
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue=''))
if __name__ == "__main__":
sln = Solution()
# apbqcr
print(sln.mergeAlternately('abc', 'pqr'))
# apbqrs
print(sln.mergeAlternately('ab', 'pqrs'))
# apbqcd
print(sln.mergeAlternately('abcd', 'pq'))
# apqr
print(sln.mergeAlternately('a', 'pqr'))
|
61029c8407f7688f5fddc4fadefb7827abc0ca0e | flywhn/spider | /project/myio2.py | 642 | 3.953125 | 4 |
def write(filename,mode,buffer):
with open(filename,mode) as file:
buffer = buffer + '\n'
file.writelines(buffer)
def read(filename):
try:
with open(filename) as file:
content = file.read()
print(content)
except FileNotFoundError:
print("the file ",filename," does not exist")
if __name__ == '__main__':
filename ="c:\\hello12.txt"
mode ="a"
buffer = ''' hello,java
i'am python ,
where are you\n'
o,i'am c language'''
read(filename)
write(filename,mode,buffer)
read(filename)
|
614dcefde41a4b7d064f8248fceb4a7d3204e60e | fernandosergio/Documentacoes | /Python/Praticando/Utilização da linguagem/while encaixado desafio.py | 675 | 4.3125 | 4 | #usuario vai digita uma sequencia de numeros
#imprimi o fatorial do numero digitado
#while sem função
#entrada = 1
#while entrada => 0:
# entrada = int(input("Digite um número natural ou 0 para parar: "))
# i = 1
# anterior = 1
# while i <= entrada:
# mult = anterior * i
# anterior = mult
# i = i + 1
# print(mult)
# while com função
def fatorial (n):
i = 1
anterior = 1
while i <= n :
mult = anterior * i
anterior = mult
i = i + 1
print(mult)
def main():
entrada = 1
while entrada >= 0:
entrada = int(input("Digite um valor natural: "))
fatorial(entrada)
main()
|
f364194f1a967a54e2b3c823657707c389b6a4e0 | employeesns/python3Code | /leetCode/108.将有序数组转换为二叉搜索树.py | 1,050 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=108 lang=python3
#
# [108] 将有序数组转换为二叉搜索树
#
# @lc code=start
from typing import List
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
"""[summary]
递归法,每次root的val取中间位置的元素
下面两种方式都是可以的
1. mid向左取整
2. mid向右取整
"""
def _buildBST(left, right):
if left > right:
return None
mid = left + (right - left) // 2
# mid = left + (right - left + 1) // 2
node = TreeNode(nums[mid])
node.left = _buildBST(left, mid - 1)
node.right = _buildBST(mid + 1, right)
return node
return _buildBST(0, len(nums) - 1)
s = Solution()
nums = [-10, -3, 0, 5, 9]
s.sortedArrayToBST(nums)
# @lc code=end
|
b6fc9ce1ad2ece24745916301a715cc0022e75d6 | abhishekjoshi1991/Python_Learning | /Regular_Expressions/Introduction.py | 20,106 | 4.6875 | 5 | #Regular Expressions: RegEx:
#***************************
'''
Regular Expression, is a sequence of characters that forms a search pattern.
RegEx can be used to check if a string contains the specified pattern we want to search
import in built re module for RegEx.
Function in RegEx
#################
match : try to apply the pattern at start of string only and returns match object,
it returns none if no match found
syntax: re.match(pattern, string, flags=0)
search :scan through string to search for pattern, returns match object
based on first occurance of pattern only, even if multiple patterns
are found, return none if no pattern found
syntax: re.search(pattern, string, flags=0)
findall:Returns a list containing all matches
syntax: re.findall(pattern, string, flags=0)
split: The split() function returns a list where the string has been split
at each match
If the pattern is not found, re.split() returns a list containing the original string
sub : the sub() function replaces the matches with the text of your choice:
If the pattern is not found, re.sub() returns the original string
subn: it returns a tuple of 2 items containing the new string and the number of substitutions made.
finditer: throws iterator object of all matched patterns in which all matched objects would be there
#methods associated with match object
group() : method returns the part of the string where there is a match.
by default group() takes 0 as an argument inside braces,
if specific group number is specified then it will print that
group only
start() : function returns the index of the start of the matched substring
end() : returns the end index of the matched substring.
string : attribute returns the passed string.
re : attribute of a matched object returns a regular expression object(i.e. pattern)
let's go through example below
'''
import re
print('o/p of match function')
print('*'*25)
matcher = re.match('python','python is easy python language')
print(matcher) #it found match at start from index 0 to 6(excluding)
#changing case of python letter in string
matcher = re.match('python','Python is easy python language')
print(matcher) #returns None, as no pattern found at start of string
#ignoring cases using ignorecase flags
matcher = re.match('python','python is easy python language',re.I) #or re.IGNORECASE
print(matcher) #now found the match with case ignored
'''as seen o/p of above programs, it is clear that
match searches for pattern at start only and it throws match object,
with index span and match found
we can print the start and end index, and found match as below'''
print('functions associated with match object')
print(matcher.start())
print(matcher.end())
print(matcher.group())
#let take another e.g to see functions associated with match object
r = re.search('(\d{3}) (\d{2})','39801 356, 2102 1111')
#to find three digit number followed by space followed by two digit number
#two combinations are there using findall [('801', '35'), ('102', '11')]
#here we created two group (\d{3}) and second is (\d{2})
print(r)
print(r.group())#available only with search not with findall
print(r.group(1)) #will print text from first group only
print(r.group(2)) #will print text from second group only
print(r.start())
print(r.end())
print(r.string)
print(r.re)
#***************************************************************************************
print('\n')
print('o/p of search function')
print('*'*25)
matcher = re.search('python','Python is easy python language of python lovers')
print(matcher)
'''
as seen from above, re.search() function searches for first occurence of pattern,
here due to Uppercase P character it has skipped first python word and printed
first occurence in index span (15,21)
'''
#***************************************************************************************
print('\n')
print('o/p of findall function')
print('*'*25)
matcher = re.findall('python','Python is easy python language of python lovers')
print(matcher)
'''
as seen from above, re.findall() function searches for all occurences of pattern,
and returns list of all matched patterns, if no pattern found then returns empty list
'''
#***************************************************************************************
print('\n')
print('o/p of split function')
print('*'*25)
matcher = re.split('\s','the rain in spain')
print(matcher) #split at whitespace
matcher = re.split('r','the rain in spain')
print(matcher) #split at r
#we can control the number of occurrences by specifying the maxsplit parameter:
matcher = re.split('\s','the rain in spain',maxsplit=1)
print(matcher) #split at max 1 whitespace
#***************************************************************************************
print('\n')
print('o/p of sub function')
print('*'*25)
matcher = re.sub('\s','#','the rain in spain')
print(matcher) #replaces whitespaces by #
#we can control the number of replacements by specifying the count parameter:
matcher = re.sub('\s','#','the python is an easy language',count=2)
print(matcher)
#***************************************************************************************
print('\n')
print('o/p of subn function')
print('*'*25)
matcher = re.subn('\s','','the rain in spain')
print(matcher) #remove all whitespaces, 3 replacement made
#***************************************************************************************
print('\n')
print('o/p of finditer function')
print('*'*25)
p = re.finditer('py[0-9]{2}n','py89n is py66n of words')
print(p) #will throw iterator object
for all in p:
print(all.start(),all.end(), all.group())
#***************************************************************************************
#***************************************************************************************
'''
In RegEx metacharacters are used in patterns
Different metacharacters are:
'''
#***************************************************************************************
print('\n')
print('*******************************')
print('Metacharacters in RegEx')
print('*******************************')
#1. []
'''
it represents set of characters,
example - [a-m]
Characters can be listed individually, e.g. [amk] will match 'a' or 'm', or 'k'
Ranges of characters can be indicated by giving two characters and separating them by a '-', for example [a-z]
[0-5][0-9] will match all the two-digits numbers from 00 to 59
If - is escaped (e.g. [a\-z]) or if it’s placed as the first or last character (e.g. [-a] or [a-]), it will match a literal '-' also
[^0-9] means will match any character including space other than 0 to 9
Expression String Matched?
[abc] a 1 match
ac 2 matches
Hey Jude No match
abc de ca 5 matches
'''
#Find all lower case characters alphabetically between "a" and "m"
print('1. o\p from metacharacter []')
r = re.findall('[a-m]','The rain in Spain')
print(r)
#find all lower case character only 'a','e','n'
r = re.findall('[aen]','The rain in Spain')
print(r)
r = re.findall('[aen]','pytho ot goad')
print(r)
#find two digit number from string say 78
r = re.findall('[0-9][0-9]','The rain in 78 Spain')
print(r)
r = re.findall('[a\-m]','The rain in - Spain')
print(r)
r = re.findall('[^0-9]','this is 9 part')
print(r)
#removing punctuation from string
test = 'this is a string! But it has punctuation. How to remove?'
clean = re.findall(r'[^!.? ]+',test) #all ! ? . and space is removed
print(' '.join(clean)) # to join all string together with space
#grabing only hypenated words from string say abhi-joshi
test1 = 'only find the hypen-word from sentence do not know how-long'
p1 = re.findall(r'[\w]+-[\w]+',test1)
print(p1)
#***************************************************************************************
#2. dot(.) or period
'''
In the default mode, this matches any character except a newline.
If the DOTALL flag has been specified as re.DOTALL, this matches any character including a newline.
Expression String Matched?
.. a No match
ac 1 match
acd 1 match
'''
print('\n')
print('2. o\p from metacharacter .dot')
r = re.findall('ra.n','The rain in Spain ra$n ra\nn')
print(r) #searches for any character as replacement for .dot
r = re.findall('ra..n','The raipn in Spain ra$n ra\nn')
print(r)
#with DOTALL flagprint('\n')
r = re.findall('ra.n','The rain in Spain ra$n ra\nn',re.DOTALL)
print(r)
#***************************************************************************************
#3. ^(caret)
'''
matches the start of string, means is pattern is present at start of string or not
Expression String Matched?
^a a 1 match
abc 1 match
bac No match
'''
print('\n')
print('3. o\p from metacharacter ^')
r = re.findall('^hello','Hello i am saying hello')
print(r) #no match
r = re.findall('^hello','hello i am saying hello')
print(r)
#***************************************************************************************
#4. $
'''
Check if the string ends with pattern passed,
Expression String Matched?
a$ a 1 match
formula 1 match
cab No match
'''
print('\n')
print('4. o\p from metacharacter $')
r = re.findall('world$','this is last statement of world')
print(r)
#***************************************************************************************
#5. *
'''
causes zero or more occurences of preceding letter of pattern, means
ab* will match zero or more occurences of preceding character (b) and
hence result may be a, ab or a followed by no of occurences of b
Expression String Matched?
ma*n mn 1 match
man 1 match
maaan 1 match
main No match (a is not followed by n)
woman 1 match
'''
print('\n')
print('5. o\p from metacharacter *')
r = re.findall('ab*', 'i am abhishek abbbsh')
print(r)
'''here 'am' has zero occurence of b, 'abhishek' has 1
occurence of b and 'abbbsh' has 3 occurences of b'''
#***************************************************************************************
#6. +
'''
Causes the resulting RE to match 1 or more repetitions of the preceding RE.
ab+ will match ‘a’ followed by any non-zero number of ‘b’s
Expression String Matched?
ma+n mn No match (no a character)
man 1 match
maaan 1 match
main No match (a is not followed by n)
woman 1 match
'''
print('\n')
print('6. o\p from metacharacter +')
r = re.findall('aix+', 'The rain in Spain falls mainly in the plain!')
print(r)
'''here there no such letter in string, where 'ai' is
followed by 'x', hence o/p is blank list
'''
#***************************************************************************************
#7. {}
'''
exactly matches specified number of occurences mentioned in {}.
fewer matches cause the entire RE not to match.
For example, a{6} will match exactly six 'a' characters, but not five.
Note**: ab{2} will match two occurence of b and not ab, always
consider immediate preceding character
{m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE,
attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters.
Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound.
As an example, a{4,}b will match 'aaaab' or a thousand 'a' characters followed by a 'b', but not 'aaab'
{m,n}? causes the resulting RE to match from m to n repetitions of the preceding RE,
attempting to match as few repetitions as possible
For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}?
will only match 3 characters.
'''
print('\n')
print('7. o\p from metacharacter {}')
r = re.findall('al{2}','The already in Spain falls mainly in the plain')
print(r) #matches exactly two occurence of 'l' after 'a'
r = re.findall('abhi{1,3}','my name is abhiiiishek and abhi')
print(r) #will match max 3 characters in abhiiiishek
r = re.findall('abhi{1,3}?','my name is abhiiiishek and abhi')
print(r) #will match least character
r = re.findall('[0-9]{2,4}','my name is 12 and 345673')
print(r) #see o/p carefully
#***************************************************************************************
#8. ?
'''
The question mark symbol ? matches zero or one occurrence of the pattern left to it.
Expression String Matched?
ma?n mn 1 match
man 1 match
maaan No match (more than one a character)
main No match (a is not followed by n)
woman 1 match
'''
print('\n')
print('8. o\p from metacharacter ?')
r = re.findall('ma?n','find in mn and man in maaaan')
print(r)
#***************************************************************************************
#9. |
''' Vertical bar | is used for alternation (or operator)
the target string is scanned, REs separated by '|' are tried from left to right.
Expression String Matched?
a|b cde No match
ade 1 match (match at ade)
acdbea 3 matches
'''
print('\n')
print('9. o\p from metacharacter |')
x = re.findall("falls|stays", 'The rain in Spain falls mainly in the stays plain')
print(x)
#***************************************************************************************
#10. () group
'''
Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that matches
either a or b or c followed by xz
Expression String Matched?
(a|b|c)xz ab xz No match
abxz 1 match (match at abxz)
axz cabxz 2 matches
'''
print('\n')
print('10. o\p from metacharacter ()')
x = re.findall('(a|b?y)p','this is bypass factor in refrigeration')
print(x)
#***************************************************************************************
#11. \ (backslash)
'''
Either escapes special characters (permitting us to match characters like '*', '?', and so forth), or
signals a special sequence described below section
for e.g. \$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine
in a special way that is as metacharacter.
lets escape special character disccused above and see the output
'''
print('\n')
print('11. o\p from metacharacter "\"')
r = re.findall('ma*n', 'it is man document')
print(r)
r = re.findall('m\a*n', 'it is mn man document')
print(r) #it has escaped special meaning of \a*, printed mn only
#***************************************************************************************
#***************************************************************************************
#********************
# Special sequences :
#********************
'''
Special sequences make commonly used patterns easier to write. Here's a list of special sequences:
'''
print('\n')
print('*****************************')
print('Special Characters in RegEx')
print('*****************************')
#1. \A - Matches if the specified characters are at the start of a string
print('\n')
print('1. o\p from special character \A')
r = re.findall('\Athe','the sun is throwing heat')
print(r)
r = re.findall('\Ahe','the sun is throwing heat')
print(r)
#2. \b - Matches if the specified characters are at the beginning or end of a word.
'''
Expression String Matched?
\bfoo football Match
a football Match
afootball No match
foo\b the foo Match
the afoo test Match
the afootest No match
'''
print('\n')
print('2. o\p from special character \b')
r = re.search('\bain','the rain in spain')
print(r) #Check if "ain" is present at the beginning of a WORD:
r = re.findall(r'ain\b','the rain in spain') #without raw text ans differs
print(r) #Check if "ain" is present at the end of a WORD:
#3. \B - Opposite of \b. Matches if the specified characters are present but not at the beginning or end of a word.
'''
Expression String Matched?
\Bfoo football No match
a football No match
afootball Match
foo\B the foo No match
the afoo test No match
the afootest Match
'''
print('\n')
print('3. o\p from special character \B')
r = re.search(r'\Bent','the entomology is pentos study')
print(r)
r = re.search(r'ent\B','development is intercontinental') #without raw text ans differs
print(r)
#4. \d - Matches any decimal digit. Equivalent to [0-9]
'''
Expression String Matched?
\d 12abc3 3 matches (at 12 3)
Python No match
'''
print('\n')
print('4. o\p from special character \d')
r = re.search('\d','he is 28 years old')
print(r) #only one match at 2, as we are using search function
r = re.findall('\d','he is 28 years old')
print(r)
#to match group of digit together, we can use \d+
r = re.findall('\d+','his birthdate is 30 april 1991')
print(r)
#if d+ not used o/p will be like 3,0,1,9,9,1
#5. \D - Matches any non-decimal digit. Equivalent to [^0-9]
print('\n')
print('5. o\p from special character \D')
r = re.findall('\D','he is 28 years old')
print(r)
#6. \s - Matches where a string contains any whitespace character.
print('\n')
print('6. o\p from special character \s')
r = re.findall('\s','this is Python language')
print(r)
r = re.search('\sP','this is Python language')
print(r)
#7. \S - Matches where a string contains any non-whitespace character.
print('\n')
print('7. o\p from special character \S')
r = re.findall('\S','this is Python language')
print(r)
r = re.search('\Sth','this is Python language')
print(r) #any non white space character followed by th
#8. \w : Matches any alphanumeric character (digits and alphabets).
# this is Equivalent to [a-zA-Z0-9_], underscore _ is also considered an
# alphanumeric character. it does not include whitespace character
print('\n')
print('8. o\p from special character \w')
r = re.findall('\w','this is _ Python language')
print(r)
#to match the group of character we use \w+
r =re.findall('\w+','his birthdate is 30 april 1991')
print(r)
#9. \W: Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0-9_]
print('\n')
print('9. o\p from special character \W')
r = re.findall('\W','this is _ @ Python language')
print(r)
#10. \Z: Matches if the specified characters are at the end of a string.
print('\n')
print('10. o\p from special character \Z')
r = re.search('Python\Z','this Python language of Python')
print(r)
'''
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Set Description
[arn] Returns a match where one of the specified characters (a, r, or n) are present
[a-n] Returns a match for any lower case character, alphabetically between a and n
[^arn] Returns a match for any character EXCEPT a, r, and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[0-9] Returns a match for any digit between 0 and 9
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for
any + character in the string
'''
#compile function with RegEx
'''
instead of syntax like, r= re.search(pattern, string) we can use following using compile method
a=re.compile(pattern)
a.search(string)
'''
print('\n')
print('compile function')
x = re.compile('\d')
matcher = x.search('i a 568 string')
print(matcher)
|
4b7fe60a895e200801826b2c2c60720c65ff0850 | Jiawen0115/Leetcode | /873_Length_of_Longest_Fibonacci_Subsequence.py | 1,565 | 3.8125 | 4 | #Question:
#A sequence x1, x2, ..., xn is Fibonacci-like if:
# n >= 3
# xi + xi+1 == xi+2 for all i + 2 <= n
#Given a strictly increasing array arr of positive integers forming a sequence,
#return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.
#A subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr,
#without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].
#Solution 1: python3
class Solution:
def lenLongestFibSubseq(self, arr: List[int]) -> int:
a = set(arr)
n = len(arr)
result = 0
for i in range(0,n-2):
for j in range(i+1,n-1):
count = 2
x, y = arr[i], arr[j]
while x + y in a:
x,y = y, x+y
count += 1
result = max(count,result)
return result if result > 2 else 0
#Solution 2:
"""
class Solution:
def lenLongestFibSubseq(self, arr: List[int]) -> int:
result = 0
a = set(arr)
n = len(arr)
lengths = [[2]*(n) for _ in range(n)]
for i in range(0,n-2):
for j in range(i+1,n-1):
next = arr[j] + arr[i]
if next in a:
k = arr.index(next)
lengths[j][k] = lengths[i][j] +1
result = max(result,lengths[j][k])
return result if result > 2 else 0
"""
|
35cd008aa00e259cf165ee62970c865a99ee1f42 | ansamant/SER531-Team-7 | /merge.py | 627 | 3.578125 | 4 | import pandas as pd
'''
Code takes the Artwork ID in artworksFinal.csv
and adds it to the coordinate dataset found in demo.xlsx
Then writes a new .csv file with all three data values.
Replace <filePath> with your file path
'''
df_1 = pd.read_csv('<filePath>/artworksFinal.csv')
df_list = df_1['Artwork ID'].tolist()
df_list = df_list[:10000]
serie = pd.Series(df_list)
print(serie.size)
df_2 = pd.read_excel('<filePath>/demo.xlsx')
df_2 = df_2.drop_duplicates(subset=['latitude', 'longitude'])
print(df_2.size)
df_2['Artwork ID'] = serie.values
df_2.to_csv('<filePath>/<fileName.csv>')
print(df_2.head())
print(df_2.size)
|
8d08572fc7c07b139eabc081b2c67d25fbe00ee7 | PallaviGandalwad/Python_Assignment_4 | /Assignment4_3.py | 1,101 | 3.9375 | 4 | #Write a program which contains filter(), map() and reduce() in it.
#Python application which contains one list of numbers.
#List contains the numbers which are accepted from user.
#Filter should filter out all such numbers which greater than or equal to 70 and less than or equal to 90.
#Map function will increase each number by 10.
#Reduce will return product of all that numbers.
#Input List = [4, 34, 36, 76, 68, 24, 89, 23, 86, 90, 45, 70]
#List after filter = [76, 89, 86, 90, 70]
#List after map = [86, 99, 96, 100, 80]
#Output of reduce = 6538752000
inputList= list();
N=input("Enter Number of elements in the array: ");
print("Enter elements in the array");
for i in range(0,N):
element=input("Element : ");
inputList.append(int(element));
#applying filer()
fliterList = list(filter(lambda no :(no>=70 and no<=90),inputList ))
print(fliterList);
#applying map()
mappedList = list(map(lambda no : no+10,fliterList));
print(mappedList);
#applying reduce()
reducedOutput = reduce(lambda no1, no2: no1*no2,mappedList);
print(reducedOutput); |
65e51f2352bd2fe184b6d977504488a81f46b4db | onherblackwings/SimpleClassExercises | /factorial_iterative.py | 180 | 4.1875 | 4 | def factorial(num):
ctr=num
fac=1
while ctr>0:
fac=fac*ctr
ctr-=1
return fac
fac=input("Input a number for factorial: ")
print factorial(fac)
|
2c024436820301716c50ababa746cb29eff50ec6 | yashkumar0707/PnS_IT302 | /181IT231_IT302_P8.py | 1,461 | 3.625 | 4 | import math
def combinations(n,r): #CALCULATING nCr
ans=1
if(n<r):
return 0
if(r==0 or r==n):
return 1
if(n-r<r):
r=n-r
for i in range(1,r+1):
ans*=(n-r+i)/i
return ans
f=open("181IT231_IT302_P8_Output_TC6.txt","w")
a=int(input("Enter value of A : "))
b=int(input("Enter value of B : "))
c=int(input("Enter value of C : "))
d=int(input("Enter value of D : "))
if(a<0 or b<0 or c<0 or d<0):
print("INVALID INPUTS HENCE PROGRAM TERMINATED")
f.write("INVALID INPUTS HENCE PROGRAM TERMINATED")
f.close()
exit(0)
f.write("INTERMEDIATE VALUES")
one=combinations(b,d)
two=combinations(a-b,c-d)
three=combinations(a,c)
prob=(one*two)/three
print("probabilty of",d,"component/s to be defective is/are : ",prob)
f.write("\nprobabilty of "+str(d)+" component/s to be defective is/are : "+str(prob))
mean=b*c/a
print("mean->",mean)
f.write("\nMEAN->"+str(mean))
variance=((a-c)/(a-1))*c*(b/a)*(1-(b/a))
print("variance->",variance)
f.write("\nVARIANCE->"+str(variance))
standard_deviation=math.sqrt(variance)
print("standard deviation->",standard_deviation)
f.write("\nSTANDARD DEVIATION->"+str(standard_deviation))
left=mean - 2*standard_deviation
#left=0 if mean - 2*standard_deviation<0 else mean - 2*standard_deviation
right=mean+2*standard_deviation
print("Chebyshev's interval for μ ± 2σ is : (",left,",",right,")")
f.write("\nChebyshev's interval : ( "+str(left)+" , "+str(right)+" ) ")
f.close()
|
a6a799de0ca4994b2e21c83b44ddf372a2a1363e | macluiggy/Python-Crash-Course-2nd-edition-Chapter-1-11-solutions | /CHAPTER 10/10-3. Guest.py | 134 | 3.671875 | 4 | name = input("Tell me your name: ")
filename = 'guest.txt'
with open(filename, 'w') as file_object:
file_object.write(name)
input() |
f75decf4e53bb996993d803ae042e2e2fe0ce805 | N-biswas000/python-projects | /new_ex2.py | 182 | 3.90625 | 4 | name=input("Enter Your Name")
age=int(input("Enter Your age"))
if age>=10 and (name[0]=='a' or name[0]=='A'):
print("You Can Watch COCO")
else:
print("You Cannot Watch COCO") |
19ad95d8896f25b26112d940264b977ceb93a1f8 | jaomorro/StanfordCourseraAlgorithms | /Part4/Bellman-Ford.py | 1,602 | 4.1875 | 4 | """
Bellman-Ford implementation of shortest path algortihm
Given a graph it finds the shortest path to each vertice from a source vertice
"""
def read_data(filename):
"""
:param filename: filename of data
:return: adjancy list
"""
with open(filename) as f:
data = f.read().strip("\n").split("\n")
data_dict = {}
for i in range(1,len(data)):
vals = data[i].strip("\n").split(" ")
data_dict.setdefault(int(vals[0]),{})
data_dict[int(vals[0])][int(vals[1])] = int(vals[2])
return data_dict
def bellman_ford(g,source):
"""
Bellman-Ford algorithm to find shortest path from source to each vertice
:param g : graph with distances between nodes
:param source : source of the graph
:return: dictionary with shortest path distance from source to each vertice
"""
dist = {node: float('inf') for node in g}
dist[source] = 0
for i in range(len(g)-1):
for node in g:
for neighbor in g[node]:
if dist[neighbor] > dist[node] + g[node][neighbor]:
dist[neighbor] = dist[node] + g[node][neighbor]
for node in g:
for neighbor in g[node]:
if dist[neighbor] > dist[node] + g[node][neighbor]:
return "Negative weight cycle"
return dist
if __name__ == "__main__":
filename = "Data/FW1.txt"
graph = read_data(filename)
distance = bellman_ford(graph,1)
print(distance)
# graph = {
# 'a': {'c': 3},
# 'b': {'a': 2},
# 'c': {'b': 7, 'd': 1},
# 'd': {'a': 6},
# }
|
94cf37ee00779bca131bd2b9c25b51746a03a6fe | wxyBUPT/leetCode.py | /twopoint/Solution_125.py | 932 | 3.765625 | 4 | #coding=utf-8
__author__ = 'xiyuanbupt'
# e-mail : xywbupt@gmail.com
import string
'''
125. Valid Palindrome Add to List QuestionEditorial Solution My Submissions
Total Accepted: 135300
Total Submissions: 535713
Difficulty: Easy
Contributors: Admin
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
'''
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
upper = set(string.uppercase)
s.upper()
i = 0
j=len(s)-1
while i<j:
while i<j and s[i] not in upper:
i += 1
while i<j and s[j] not in upper:
j -= 1
if s[i] != s[j]:
return False
i+=1
j-=1
return True
|
dc865656ae3054865bd5bf668c4b459dd24896f5 | NatanLisboa/python | /exercicios-cursoemvideo/Mundo1/ex006.py | 1,959 | 3.78125 | 4 | # Desafio 006 - Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada.
coresFundo = {
'padrao': '\033[m',
'branco': '\033[40m',
'vermelho': '\033[41m',
'verde': '\033[42m',
'amarelo': '\033[43m',
'azul': '\033[44m',
'lilas': '\033[45m',
'verdeagua': '\033[46m',
'cinza': '\033[47m'
}
print('Desafio 006 - Dobro, triplo e raiz quadrada de um número')
n = int(input('Digite um número: '))
print('O dobro de {}{}{} é {}{}{}'.format(coresFundo['verdeagua'],
n,
coresFundo['padrao'],
coresFundo['cinza'],
n * 2,
coresFundo['padrao']))
print('{}O{} {}triplo{} {}de{} {}{}{} {}é{} {}{}{}'.format(coresFundo['padrao'],
coresFundo['branco'],
coresFundo['vermelho'],
coresFundo['verde'],
coresFundo['amarelo'],
coresFundo['azul'],
coresFundo['lilas'],
n,
coresFundo['verdeagua'],
coresFundo['cinza'],
'\033[7m',
'\033[4;34m',
n * 3,
coresFundo['padrao']))
print('A raiz quadrada de {} é {}'.format(n, pow(n, (1/2))))
|
7010f2eb862611a9294ef9d36cb0d28dfa8b4a18 | harmanbirdi/HackerRank | /30DaysOfCode/day12_inheritence.py | 1,335 | 3.71875 | 4 | #!/usr/bin/env python
#
# Problem: https://www.hackerrank.com/challenges/30-inheritance
# __author__ : Harman Birdi
#
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print "Name:", self.lastName + ",", self.firstName
print "ID:", self.idNumber
# Add your code to class Student
class Student(Person):
def __init__(self, firstName, lastName, idNumber, scores):
self.grade = ''
self.scores = scores
Person.__init__(self, firstName, lastName, idNumber)
def calculate(self):
grades = {'O': [90, 100], 'E': [80, 89], 'A': [0, 79], 'P': [55, 69], 'D': [40, 54], 'T': [0, 39]}
avg = int(reduce(lambda x, y: x + y, self.scores) / (len(self.scores) * 1.0))
for grade in grades.keys():
if grades[grade][0] <= avg <= grades[grade][1]:
self.grade = grade
return self.grade
# Code below provided by HackerRank template
line = raw_input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(raw_input()) # not needed for Python
scores = map(int, raw_input().split())
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print "Grade:", s.calculate()
|
7bb4a305b1f46875c5a824cc47907b4b919167bb | MateuszG/combinatorial-algorithms | /8_rgf_podzial.py | 1,966 | 3.671875 | 4 | """
Algorytm 17
1) k = 1
2) Szukamy największego F[j] (1...n) porównując go z wartością 'k', jeśli
znajdziemy większą wartość to przypisujemy 'k' tą wartość F[j].
3) Tworzymy pustą listę 'B' z podlistami (1...k).
4) Iterując 'j' (1...n) wartości F[j] potraktuj jako indeksy listy B,
dodając do podzbioru B[F[j]] wartość [j].
"""
def rgf_podzial(n, F):
k = 1
for j in range(1, n):
if F[j] > k:
k = F[j]
B = [[] for _ in range(k + 2)]
for j in range(1, n + 1):
B[F[j]] = B[F[j]] + [j]
B = [x for x in B if x != []] # Remove empty lists in list B
return B
values = [
[1, 1, 1, 1],
[1, 1, 1, 2],
[1, 1, 2, 1],
[1, 1, 2, 2],
[1, 1, 2, 3],
[1, 2, 1, 1],
[1, 2, 1, 2],
[1, 2, 1, 3],
[1, 2, 2, 1],
[1, 2, 2, 2],
[1, 2, 2, 3],
[1, 2, 3, 1],
[1, 2, 3, 2],
[1, 2, 3, 3],
[1, 2, 3, 4],
]
for val in values:
print (val, end=' ')
val.reverse()
val.append([])
val.reverse()
print (rgf_podzial(4, val))
# [1, 1, 1, 1] [[1, 2, 3, 4]]
# [1, 1, 1, 2] [[1, 2, 3], [4]]
# [1, 1, 2, 1] [[1, 2, 4], [3]]
# [1, 1, 2, 2] [[1, 2], [3, 4]]
# [1, 1, 2, 3] [[1, 2], [3], [4]]
# [1, 2, 1, 1] [[1, 3, 4], [2]]
# [1, 2, 1, 2] [[1, 3], [2, 4]]
# [1, 2, 1, 3] [[1, 3], [2], [4]]
# [1, 2, 2, 1] [[1, 4], [2, 3]]
# [1, 2, 2, 2] [[1], [2, 3, 4]]
# [1, 2, 2, 3] [[1], [2, 3], [4]]
# [1, 2, 3, 1] [[1, 4], [2], [3]]
# [1, 2, 3, 2] [[1], [2, 4], [3]]
# [1, 2, 3, 3] [[1], [2], [3, 4]]
# [1, 2, 3, 4] [[1], [2], [3], [4]]
"""
Procedura wyznaczająca z zadanej funkcji RGF(f[1] , . . . , f[n])
odpowiadający jej podział zbioru {1, 2, . . . , n} na stosowna liczbe bloków.
1) Pierwszy 'for' wyznacza, na podstawie zadanej funkcji RGF, liczbe bloków w
podziale odpowiadającym tej funkcji. Sprowadza się to do wyznaczenia
największej składowej.
2) W ostatniej pętli 'for' wstawiane są do kolejnych bloków podziału stosowne
elementy.
"""
|
34f539e3c36524a86d5e1f1df330c34be3161cbb | CJHdreamore/Udacity_learning | /Data_Science_Anaconda/Visualization.py | 1,084 | 4.09375 | 4 | import ggplot
from ggplot import *
from pandas import *
df = pandas.read_csv(r'C:\Users\CJH\PycharmProjects\Data_Science_Anaconda\turnstile_data_master_with_weather.csv')
def plot_weather_data(df):
'''
Here are some suggestions for things to investigate and illustrate:
* Ridership by time of day or day of week
* How ridership varies based on Subway station (UNIT)
* Which stations have more exits or entries at different times of day
(You can use UNIT as a proxy for subway station.)
:param df:
:return:
'''
# Ridership by time of day
p1 = ggplot(df,aes(x = 'Hour',y = 'ENTRIESn_hourly')) + geom_bar()+\
ggtitle(' Ridership by time of day')
# Ridership varies based on Unit
p2 = ggplot(df,aes(x = 'Hour',y = 'ENTRIESn_hourly',color = 'UNIT')) + geom_point()+\
scale_color_gradient(low = 'black',high = 'red') +\
ggtitle(' Ridership by time of day in different stations')
p3 = ggplot(df,aes(x = 'Hour',y = 'ENTRIESn_hourly')) + geom_point() + stat_smooth
return p3
print plot_weather_data(df) |
bc3e2d7b37866c8626ca83c47fd2a229c8d686c2 | noeleel/AgileDevGr3 | /GUI_exit_windows.py | 751 | 3.53125 | 4 | from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import *
from Misc import *
class PopUpConfirmQuit(Toplevel):
"""A TopLevel popup that asks for confirmation that the user wants to quit.
.
Upon confirmation, the App is destroyed.
If not, the popup closes and no further action is taken
"""
def __init__(self, master=None):
super().__init__(master)
Label(self , text = "Are you sure you want to quit").pack()
Button(self, text = 'Yes', command=master.destroy).pack(side=RIGHT, fill=BOTH, padx=5, pady=5)
Button(self, text = 'No', command=self.destroy).pack(side=RIGHT, fill=BOTH, padx=5, pady=5) |
60524de4808e15315c9a047176b23313cc601710 | stankevichevg/daily-interview | /11_fc_binary_tree.py | 1,250 | 3.96875 | 4 | # Given an integer k and a binary search tree, find the floor (less than or equal to) of k,
# and the ceiling (larger than or equal to) of k. If either does not exist, then print them as None.
#
# Here is the definition of a node for the tree.
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def find_ceiling_floor(root_node, k, floor=None, ceil=None):
if root_node is None:
return floor, ceil
elif root_node.value < k:
return find_ceiling_floor(root_node.right, k, root_node.value, ceil)
elif root_node.value > k:
return find_ceiling_floor(root_node.left, k, floor, root_node.value)
elif root_node.value == k:
if root_node.left is not None and root_node.right is not None:
return root_node.left.value, root_node.right.value
elif root_node.left is not None:
return root_node.left.value, ceil
elif root_node.right is not None:
return floor, root_node.right.value
root = Node(8)
root.left = Node(4)
root.right = Node(12)
root.left.left = Node(2)
root.left.right = Node(6)
root.right.left = Node(10)
root.right.right = Node(14)
print(find_ceiling_floor(root, 5))
# (4, 6) |
000f52677ad78711c1e8e9a81c8109506db2a74c | bignamehyp/interview | /python/leetcode/Fraction2RecurringDecimal.py | 920 | 3.625 | 4 | class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
sign = 1
if numerator * denominator < 0:
sign = -1
numerator = abs(numerator)
denominator = abs(denominator)
ans = str(numerator / denominator)
if sign == -1:
ans = '-' + ans
numerator = numerator % denominator
if numerator > 0:
ans += '.'
dict = {}
frac = ''
i = 0
while numerator > 0:
if numerator in dict:
idx = dict[numerator]
frac = frac[:idx] + '(' + frac[idx:] + ')'
break
else:
dict[numerator] = i
numerator *= 10
val = numerator / denominator
numerator = numerator % denominator
frac = frac + str(val)
i += 1
return ans + frac |
dd4f5806c4ddf8144919a632a4060ebfa027ccc3 | pocotila/project000 | /test000.py | 870 | 3.90625 | 4 | print("first message") # nu necesita paranteze in 2.7
a = input('Apasa tasta r')
print(a)
print("Elevul'x' nu si-a realizat tema")
print('Elevul "x" nu si-a realizat tema')
print("Ana are mere \n ion")
print("""
\tAna are mere
Petre e la joaca""")
variabila1 = 1
variabila2 = 2
variabila3 = f"Ana are {variabila1} mar si {variabila2} pere."
print(variabila3)
variabila4 = "Ana are {1} mar si {0} pere".format(variabila1, variabila2)
print(variabila4)
variabila5 = "Ana are {1} mar si {1} pere".format(variabila1, variabila2)
print(variabila5)
print(type(variabila4))
variabila6 = "Ana are " + str(variabila2) + "mere."
print(variabila6)
variabila6 = "Ana are " + str(variabila2) + "mere."
print(variabila6)
print(variabila1 + variabila2)
print(str(variabila1) + str(variabila2))
variable_number_1 = 3 - 2j
print(variable_number_1.real)
print(variable_number_1.imag)
|
4386c627774e18c709e0df2fe1ec79cd63869da2 | martinpeck/random-pi | /mpeck/isotopes.py | 1,271 | 3.765625 | 4 | import random
class Isotope:
def __init__(self, change_of_decay):
self.decayed = False
self.chance = change_of_decay
def test_decay(self):
if not self.decayed and random.randint(1, self.chance) == 1:
self.decayed = True
return True
else:
return False
def decay_simulation_1():
loops = 0
total_isotopes = 100
decayed_isotopes = 0
isotopes = [Isotope(6) for x in range(1, total_isotopes+1)]
while decayed_isotopes < total_isotopes:
loops += 1
for i in isotopes:
if i.test_decay():
decayed_isotopes +=1
print("loop:",loops, "decayed:", decayed_isotopes)
print("everything has decayed")
def decay_simulation_2():
loops = 0
total_isotopes = 100
chance_of_decay = 6
remaining_isotopes = total_isotopes
while remaining_isotopes > 0:
loops += 1
for i in range(0, remaining_isotopes):
if random.randint(1, chance_of_decay) == 1:
remaining_isotopes -= 1
print("loop:",loops, "remaining:", remaining_isotopes)
print("everything has decayed")
decay_simulation_2()
|
0b7f1779a9b22772c86c1bdd5aad4ea1631ebd6f | andres4423/Andres-Arango--UPB | /50Ejercicios/Ejercicio36.py | 250 | 3.671875 | 4 | digito = input("Por favor ingrese un número: ")
digi1 = digito.split(".")
digi1 = int("".join(digi1))
if digi1 < 100000:
print(digito, "tiene", len(str(digi1)),"digitos.")
else:
print("El número ingresado es mayor que 100.000.") |
173b41304d97e5d4f786a95519daa88b05496d68 | ndf14685/raspberry | /clase2/ej1_led.py | 330 | 3.546875 | 4 | #!/usr/bin/python
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT, initial=GPIO.LOW)
for x in range(0,10):
GPIO.output(11, GPIO.HIGH)
sleep(1)
GPIO.output(11,GPIO.LOW)
sleep(1)
else:
print 'Programa finalizado ;)'
|
5603cab006303a3beeaa1df58df6bb6aa2f16c46 | precimilo/mcandre | /python/hanoi.py | 509 | 3.890625 | 4 | #!/usr/bin/env python3
import time
START = 0
AUX = 1
END = 2
def hanoi(n, start, aux, end):
if n == 1:
return (start, end)
return (
hanoi(n - 1, start, aux, end) +
(start, aux) +
hanoi(n - 1, aux, end, start)
)
def main():
n = int(input("N = "))
print("Running")
startt = time.time()
hanoi(n, START, AUX, END)
endt = time.time()
print("Time = %d sec" % (endt - startt))
#print("Steps = %s" % str(steps))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass |
c6fe6a7f3f9751facf75a485a20721992ac07f54 | Olena751532/homework | /cw_2.py | 1,329 | 3.984375 | 4 | # Написати скрипт, який з двох введених чисел визначить, яке з них більше, а яке менше
a = int(input("Input the number a="))
b = int(input("Input the number b="))
if a <= b:
min_value, max_value = a, b
else:
min_value, max_value = b, a
st = "The number a={0} is minimal number,the number b={1} is maximum number".format(min_value, max_value)
print(st)
# Написати скрипт, який перевірить чи введене число парне чи непарне і вивести відповідне повідомлення.
a = int(input())
if a % 2 == 0:
print("Число парне")
else:
print("Число непарне")
# Написати скрипт, який обчислить факторіал введеного числа.
n = int(input())
factorial = 1
for i in range(2, n + 1):
factorial *= i
print(factorial)
# Створити список, який містить елементи цілочисельного типу, потім за допомогою циклу перебору змінити тип даних елементів на числа з плаваючою крапкою.
spysok = [22, 1, 3, 15]
i = 0
for value in spysok:
spysok[i] = float(value)
i = i+1
print(spysok)
|
e1011b8d1acdf8a09b6219177009dbf186ac2d0c | jobiaj/Problems-from-Problem-Solving-with-Algorithms-and-Data-Structures- | /Chapter_02/stack.py | 473 | 4 | 4 | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
s = Stack()
print "PUSHING AN ITEM TO STACK" + str(s.push('shibin'))
print "CHECKING IS_EMPTY" + str(s.is_empty())
print s.peek()
print s.is_empty()
print s.pop()
print s.is_empty()
|
6bd2599edf4ef7e0b634e342982a154bbe775061 | disund/School | /Python/lottery.py | 1,598 | 3.75 | 4 | #!/usr/bin/python2
import random
print('\033[94m===========================================')
print('\033[94m++++++++++++ \033[92mLOTTERY GENERATOR \033[94m++++++++++++')
print('\033[94m++++++++++++++\033[93m[ \033[97mVERSION 1.0 \033[93m]\033[94m++++++++++++++')
print('\033[94m===========================================')
print '\n\n'
def Megamill():
integer = []
for number in range( 0 , 5 ):
integer.append(random.randint( 1 , 70))
return integer
print('\n\033[91m The MegaMillion numbers are: \033[97m{}'. format(Megamill()))
def Megaball():
integer = []
for number in range(1):
integer.append(random.randint( 1 , 25 ))
return integer
print('\033[91m The Megaball is: \033[97m{}'. format(Megaball()))
def Powernum():
integer = []
for number in range(0 , 5):
integer.append(random.randint( 1 , 69 ))
return integer
print('\n\033[91m The Powerball numbers are: \033[97m {}'. format(Powernum()))
def Powerball():
integer = []
for number in range(1):
integer.append(random.randint( 1 , 26 ))
return integer
print('\033[91m The Powerball is: \033[97m {}'. format(Powerball()))
def Pick3():
integer = []
for number in range(0 , 3):
integer.append(random.randint( 0 , 9 ))
return integer
print('\n\033[92m The Pick 3 are \033[97m{}'. format(Pick3()))
def Pick4():
integer = []
for number in range(0 , 4):
integer.append(random.randint( 0 , 9 ))
return integer
print('\n\033[92m The pick 4 are: \033[97m{}'. format(Pick4()))
print '\n\n'
print(' PICK 5 COMING SOON')
|
0f62527fcbe9de5e38ef546c7252b0b14298dbc0 | Nikkuniku/AtcoderProgramming | /ライブラリ/素数列挙(エラトステネスの篩).py | 422 | 3.5 | 4 | def sieve_of_eratosthenes(x):
nums = [i for i in range(x+1)]
root = int(pow(x, 0.5))
for i in range(2, root + 1):
if nums[i] != 0:
for j in range(i, x+1):
if i*j >= x+1:
break
nums[i*j] = 0
primes = sorted(list(set(nums)))[2:]
return primes
n = int(input())
primes = sieve_of_eratosthenes(n)
print(len(primes))
print(primes)
|
d9689701304e5c04db5acedd9d6d896785d4849e | Ipsita45/Ipsita-Assignment-Day1 | /Ipsita Assignment Day 1.py | 642 | 3.546875 | 4 | Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a = 25
>>> b = 35
>>> a+b
60
>>> A = 66
>>> B = "87"
>>> A+B
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
A+B
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> Marks = 86
>>> Name = "Ipsita"
>>> Age = 23
>>> print (f"The marks of {Name} is {Marks} and age is {Age}")
The marks of Ipsita is 86 and age is 23
>>> print ("Hello\t World")
Hello World
>>> print ("Hello\n World")
Hello
World
>>> |
527f4fab3fc48e6ebb5370afceec0de9413a7bda | ucsb-cs8-m18/code-from-class | /08-28/exceptions.py | 655 | 4.375 | 4 | while True: # try forever, potentially
try: # anything that might throw an exception goes in here
x = int(input("Please enter a number: "))
# if a ValueError exception happens in the above line,
# we DO NOT CONTINUE this try block,
# and we immediately go to the except block
break # get out of the loop once the user does the right thing
except ValueError:
# in here, we deal with any exceptions thrown
# we only got here if a ValueError happened
# in this case, we say we only know how to deal with ValueErrors
print("Oops! That was no valid number. Try again!")
|
5c44e03d38ce987905385086d53ae6f8ca6af434 | gitgitzhou/practiceCode | /python/test3.py | 1,117 | 4 | 4 | #!/usr/bin/env python
class Myclass:
i = 1234 # class variable
def f(self):
return 'Hello world'
def __init__(self, N, H):
self.name = N
self.height = H
self.weight = 20 # instance variable
def test(self, A, B):
print self.i # class variable
print self.weight # instance variable
self.x = A
self.y = B
print A + B
print self.x + self.y
def add(self, X, Y):
zz = X + Y
return zz
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
# V = Myclass('Kevin', 105)
# print V.i
# print ''
# b = V.f()
# print b
# print ''
# print V.name
# print V.height
# print V.weight
# print ''
# V.test(3, 5)
# print ''
# ZZ = V.add(3, 5)
# print ZZ
mybag = Bag()
print mybag.data
mybag.add('pen')
print mybag.data
mybag.addtwice('book')
print mybag.data
yourbag = Bag()
print yourbag.data
yourbag.add('pen')
print yourbag.data
yourbag.addtwice('apple')
print yourbag.data
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.