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 |
|---|---|---|---|---|---|---|
c15014e022fb80ead4c363acfc690774e42f906f | Breachj71440/01_area_perimeter_assessment | /03_dimensions_input.py | 3,662 | 4.34375 | 4 | # asks user to only enter the following shapes
print("choose one of the following shapes: "
"square, rectangle, "
"circle, triangle, "
"parallelogram")
# what user is allowed to input after the questions
valid_shapes = ["square", "rectangle", "circle", "triangle", "parallelogram"]
valid_ap = ["area", "perimeter"]
# shape checking function, ensures that only valid shapes can be entered
def shape_checker(question):
error = "this is not a valid shape"
valid = False
while not valid:
response = input(question)
if response.lower() in valid_shapes:
print("you chose {}".format(response.lower()))
return response
elif response.lower() not in valid_shapes:
print(error)
continue
# area and perimeter checking function, ensures only area or perimeter can be chosen
def ap_checker(question):
error = "please choose either area or perimeter"
valid = False
while not valid:
response = input(question)
if response.lower() in valid_ap:
print("you chose {}".format(response.lower()))
return response
elif response.lower() not in valid_ap:
print(error)
continue
# no letters allowed in number input function
def no_letters(question):
error = "you may only input numbers here"
valid = False
while not valid:
response = input(question)
for letter in response:
if letter.isdigit():
return response
elif not letter.isdigit():
print(error)
break
# user input for choosing shape, area or perimeter and dimensions of the shape
# shows user back the dimensions they chose
choose_shape = shape_checker("what shape do you want? ")
choose_ap = ap_checker("do you want to calculate area or perimeter? ")
if choose_shape == "rectangle":
base = no_letters("what is the base? ")
height = no_letters("what is the height? ")
print("the base is", base)
print("the height is", height)
if choose_shape == "square":
base = no_letters("what is the base? ")
height = no_letters("what is the height? ")
print("the base is", base)
print("the height is", height)
if choose_shape == "circle":
radius = no_letters("what is the radius? ")
print("the base is", radius)
if choose_shape == "rectangle":
base = no_letters("what is the base? ")
height = no_letters("what is the height? ")
print("the base is", base)
print("the height is", height)
if choose_shape == "triangle":
if choose_ap == "area":
base = no_letters("what is the base? ")
height = no_letters("what is the height? ")
print("the base is", base)
print("the height is", height)
if choose_ap == "perimeter":
side_a = no_letters("what is the side a? ")
side_b = no_letters("what is the side b? ")
side_c = no_letters("what is the side c? ")
print("the side a is", side_a)
print("the side b is", side_b)
print("the side c is", side_c)
if choose_shape == "parallelogram":
if choose_ap == "area":
base = no_letters("what is the base? ")
height = no_letters("what is the height? ")
print("the base is", base)
print("the height is", height)
if choose_ap == "perimeter":
base = no_letters("what is the base? ")
side = no_letters("what is the side? ")
print("the base is", base)
print("the side is", side)
|
3054bead64ee9c307a075cd483a1b0eb1ec8dc8a | rohanwarange/Accentures | /program6.py | 1,379 | 4.1875 | 4 | # # # -*- coding: utf-8 -*-
# # """
# # Created on Sat Jun 26 07:19:47 2021
# # @author: ROHAN
# # """
# # Problem Statement
# # A carry is a digit that is transferred to left if sum of digits exceeds 9 while adding two numbers
# from right-to-left one digit at a time
# # You are required to implement the following function.
# # Int NumberOfCarries(int num1 , int num2);
# # The functions accepts two numbers โnum1โ and โnum2โ as its arguments. You are
# required to calculate and return the total number of carries generated while adding digits of
# two numbers โnum1โ and โ num2โ.
# # Assumption: num1, num2>=0
# # Example:
# # Input
# # Num 1: 451
# # Num 2: 349
# # Output
# # 2
# # Explanation:
# # Adding โnum 1โ and โnum 2โ right-to-left results in 2 carries since ( 1+9) is 10.
# 1 is carried and (5+4=1) is 10, again 1 is carried. Hence 2 is returned.
# # Sample Input
# # Num 1: 23
# # Num 2: 563
# # Sample Output
# # 0
def NumberOfCarries(n1,n2):
count=0
carry = 0
if len(n1) <= len(n2):
l= len(n1)-1
else:
l = len(n2)-1
for i in range(l+1):
temp = int(n1[l-i])+int(n2[l-i])+carry
if len(str(temp))>1:
count+=1
carry = 1
else:
carry = 0
return count+carry
n1=input()
n2=input()
print(NumberOfCarries(n1, n2))
|
5d623063e5a43caee25e23d9adba7895e212224c | alexssssalex/Longman | /Base.py | 1,237 | 3.609375 | 4 | from config import WORDS_IN_STUDY, WORDS_KNOWN, WORDS_IN_STUDY_BAK
def read_arrange(path: str) -> set:
"""
- read file by path;
- filter empty lines;
- made unique list;
- arrange list set and save word in the same file in alphabet order;
"""
with open(path, 'r') as f:
data = [w.split(':')[0].strip() for w in f.readlines()]
word_set = set(filter(lambda x: len(x) > 0, data))
with open(path, 'w') as f:
words = list(word_set)
words.sort()
f.writelines([w+'\n' for w in words])
with open(WORDS_IN_STUDY_BAK, 'w') as f:
f.writelines([w+'\n' for w in words])
return word_set
class Base:
def __init__(self):
self.words = read_arrange(WORDS_KNOWN)
self.words.update(read_arrange(WORDS_IN_STUDY))
def __contains__(self, item):
return item in self.words
def update(self, item):
if item not in self.words:
with open(WORDS_IN_STUDY, 'a') as f:
self.words.update([item])
f.write(item+'\n')
if __name__=='__main__':
print('I am here')
b = Base()
print(b.words)
x = 'dfg'
print(x in b)
b.update(x)
print(x in b)
print(b.words)
|
d49a3de465224a2f238d09500289556e83c06d39 | GGreenBow/Python-Facul | /exercicios/aula 15 out/nao sie.py | 334 | 3.953125 | 4 | num=int(input('Digite um numero: '))
par=0
imp=0
while(num>0):
if num%2==0:
par=par+1
print('O nรบmero %d' %num, ' รฉ par')
else:
imp=imp+1
print('O nรบmero %d' %num, ' รฉ รญmpar')
num=int(input('Digite um numero: '))
print('O total de nรบmeros pares รฉ %d' %par, ' e รญmpares รฉ %d' %imp)
|
68a0e78c9d7fddeef33078c06156ead1ec265204 | HeapOfPackrats/AoC2017 | /day1b.py | 687 | 3.953125 | 4 | #http://adventofcode.com/2017/day/1
import sys
def main(argv):
#get input, otherwise prompt for input
if (len(argv) == 2):
inputStr = argv[1]
sum = 0
else:
print("Please specify an input argument (day1b.py [input])")
return
#find any char whose int value is equal to the char at the index length/2 ahead of it
#add those specific chars' int values to sum
inputLen = len(inputStr)
offset = int(inputLen/2)
for index, char in enumerate(inputStr):
nextChar = inputStr[(index+offset)%(inputLen)]
if char == nextChar:
sum += int(char)
print(sum)
if __name__ == "__main__":
main(sys.argv) |
c4d4c614b9353e8d1508a909b14ed6b96a585185 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_166/Bimestral1_166_20192/JABES_166/jabeq04.py | 179 | 3.9375 | 4 | base = float(input('Digite o tamando da base do triรขgulo: '))
h = float(input('Digite a altura do triรขgulo: ' ))
area = base * h / 2
print(' A area do triรขgulo รฉ :' , area)
|
00cee42c2eca24a213590acc92a3af917233e6a2 | LuciaIng/TIC_20_21 | /ejercicio3.py | 513 | 4.0625 | 4 | '''Escriba una funcin que reciba
un nmero entero del 1 al 7 y
escriba en pantalla el correspondiente
da de la semana.'''
def ejercicio_3():
dias_semana=["Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo"]
numero=input("Escribe un nmero: ")
while numero < 1 or numero > 7:
numero=input("Escribe un numero del 1 al 7: ")
for cont in range(0,len(dias_semana)+1):
if numero == cont :
print dias_semana[cont-1]
ejercicio_3()
|
b9d1457bfd8ac6e8135f5301d3a746b283a34ab2 | beatSpatial/isp | /isp_semi_auto/csv_xlsx_utils.py | 5,722 | 3.875 | 4 | import os
import csv
from openpyxl import load_workbook, Workbook
def _convert_csv_to_xlsx(list_loc):
# TODO: Test function with actual CSV as it would be provided
try:
csv_file = csv.reader(
open(list_loc, "r"),
quotechar='"',
delimiter=",", quoting=csv.QUOTE_ALL,
skipinitialspace=True)
except FileNotFoundError:
print("Is the csv in the 'input' folder? Have you spelled it correctly?")
return
else:
wb = Workbook(write_only=True)
ws = wb.active
for row in csv_file:
ws.append(row)
return ws
def sanitize_upload(f):
# If an xls, complain
if f.endswith(".xls"):
print('Need the file to be in .xlsx!')
return # TODO provide feedback to the uploader
# If a csv, convert to xlsx and return the worksheet
elif f.endswith(".csv"):
ws = _convert_csv_to_xlsx(f)
if not ws:
return
print("Converted from .csv to .xlsx")
# If an xlsx load the workbook and select the active sheet
elif f.endswith(".xlsx"):
ws = load_workbook(f).active
print("Using an xlsx. You didn't need to convert this yourself. You could have passed in the raw '.csv'")
# Passed a file that has no business being here
else:
_, ext = os.path.splitext(f)
print(
f'What are you doing giving this script a {ext}??!! Do you know what this script even does?! Have you read the documentation! I spent a whole morning writing it!')
return # TODO WHAT DO WE DO HERE?
return ws
def get_sign_up_items(student_list):
"""Loops through the rows in 'student_list' and creates a convenient list for use in populating student model
Useful Columns are:
C firstname
D lastname
E preferredname
Parameters
----------
student_list : str
The file location of the spreadsheet, (File type object)
enrol : bool, optional
A flag that informs the generation of a list of sign up items, or just emails for enrolment (default is False)
print_items: bool, optional
A flag that controls wether the items are output to the console, so they can be cut from the output and used directly; Used if script is run within the Repl.it (default is False)
Returns
-------
list
A list of useful items to populate a student model
"""
ws = sanitize_upload(student_list)
data = []
for row in range(2, ws.max_row + 1):
bio_list = []
for column in "ACDEJ": # firstname, lastname, preferred,
cell_name = "{}{}".format(column, row)
bio_list.append(ws[cell_name].value)
data.append(bio_list)
return data
def get_gradebook_items(gradebook):
assignment_list = []
student_fyid_list = []
ws = sanitize_upload(gradebook)
max_col = ws.max_column
max_row = ws.max_row
# The assignments we'd like to assign as part of the ISP
okList = ['Quiz:', 'Assignment:', 'Interactive Content:']
for i in range(4, max_col):
assignment = ws.cell(row=1, column=i).value
if any(s in assignment for s in okList):
assignment_list.append(assignment)
for i in range(2, max_row):
student_fyid = ws.cell(row=i, column=3).value.split("@")[0]
student_fyid_list.append(student_fyid.lower())
return assignment_list, student_fyid_list
def _pan(title):
if title[0:4] == 'Quiz':
p_title = title. \
replace('Quiz:', ''). \
replace('(Real)', ''). \
replace('Moodle', ''). \
replace('Quiz', ''). \
replace(' :', '')
elif title[0:10] == "Assignment":
p_title = title. \
replace('Assignment:', ''). \
replace('(Real)', ''). \
replace('Moodle', ''). \
replace('Assignment', ''). \
replace('Portfolio:', ''). \
replace(' :', '')
else:
p_title = title. \
replace('Interactive Content:', ''). \
replace('(Real)', '')
return p_title
def get_student_items(gradebook):
student_data_list = []
student_grade_dict = {}
fyid_lookup = {}
ws = sanitize_upload(gradebook)
okList = ['Quiz:', 'Assignment:', 'Interactive Content:']
max_row = ws.max_row
max_col = ws.max_column
for i, row in enumerate(ws.iter_rows(min_row=2, max_col=3, max_row=max_row, values_only=True)):
fyid = row[2].split("@")[0]
surname = row[1].upper()
names = row[0].split('(')
if len(names) > 1:
given = names[1].replace(')', '')
pref = f' ({names[0].strip()})'
else:
given = names[0]
pref = ""
student_grade_dict[i + 2] = fyid
student_data_list.append((fyid, surname, given, pref))
grade_dict = {}
# Slide down the row of names
for i in range(2, max_row + 1):
collector = {}
# For that row, starting at column four iterate through each cell
for j, cell in enumerate(ws.iter_cols(min_row=i,
max_row=i,
min_col=4,
max_col=max_col - 2,
values_only=True)):
assignment = ws.cell(row=1, column=j + 4).value
if any(s in assignment for s in okList):
if cell[0] not in ['-', None]:
collector[_pan(assignment)] = cell[0]
grade_dict[i] = collector
for k, v in grade_dict.items():
fyid_lookup[student_grade_dict[k]] = v
return student_data_list, fyid_lookup
|
a4313c9b45252f7171b6763301368c2b4a83e2ac | Akshata2704/APS-2020 | /121-convert_zeros_5.py | 316 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 10 22:42:51 2020
@author: AKSHATA
"""
def convertFive(n):
s=list(str(n))
for i in range(len(s)):
if(s[i]=='0'):
s[i]='5'
return ''.join(s)
for _ in range(int(input())):
print(convertFive(int(input()))) |
9503e2607ba4e738649fb72a729014a84b48ac53 | zygoh1986/FS104 | /Session6/writetofile.py | 173 | 3.578125 | 4 | file_string = str(input("Enter Text here:"))
def write(text):
file_object = open("testfile","w")
file_object.write(text)
file_object.close()
write(file_string) |
2c7d6d3c53e6ca094067f84842b29d4ee4beb886 | automata-studio/HackerRank-Solutions | /ProblemSolving/Python/Sorting/quicksort_2_sorting.py | 532 | 3.9375 | 4 | def partition(arr):
p = arr[0]
left, equal, right = [], [], []
for e in arr:
if e > p:
right.append(e)
elif e == p:
equal.append(e)
else:
left.append(e)
return left, equal, right
def quicksort(arr):
if len(arr) <= 1:
return arr
left, equal, right = partition(arr)
arr = quicksort(left) + equal + quicksort(right)
print(*arr)
return arr
n = int(input())
ar = list(map(int, input().split()))
quicksort(ar)
|
83b6d19fe07d76888e2d98a4884a59bd95c91382 | oglebee/python.learning | /rec.py | 3,342 | 4.125 | 4 | import os
os.system("clear")
import math
pi = float(math.pi)
############################################
#Load in
############################################
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def get_perimeter(self):
return 2 * (self.width + self.height)
def get_area(self):
return self.width * self.height
def my_rec():
askw = int(input("Width of your rectangle? "))
askh = int(input("Height of your rectangle? "))
myr = Rectangle(askw, askh)
what = input("Type what you need to know.\nPerimeter\nArea\nEnter: ")
if (what == "Perimeter") or (what == "perimeter"):
print(myr.get_perimeter())
elif(what == "Area") or (what == "area"):
print(myr.get_area())
else:
print("Sorry no info on that.")
class Triangle:
def __init__(self, base, height):
self.base = base
self.height = height
def get_area(self):
return (self.base * self.height)/2
def get_hyp(self):
return math.sqrt(((self.base)**2) + ((self.height)**2))
def my_tri(): #First triangle branch
def left_tri():#non right triangle path
askb = float(input("What is the base of your triangle? "))
askh = float(input("What is the height of your triangle? "))
myt = Triangle(askb, askh)
what = input("What do you need to know?\nArea\nEnter: ")
if (what == "area") or (what == "Area"):
print(myt.get_area())
else:
print("Sorry, either you messed up input or I haven't avchieved the desired functionality.")
def right_tri(): #right triangle path
what_need = input('''\n
What information do you need?\n
1 - Hypotenuse\n
2 - Side Leg given side and hypotenuse\n
3 - Side leg given side and angle\n
4 - Angles given adjacent & opposite sides\n
5 - Angles given side & hypotenuse\n
6 - Area
Enter number: ''')
def rt1():
s1ask = float(input("What is the first side of your right triangle? "))
s2ask = float(input("What is the second side to your right triangle? "))
rt = Triangle(s1ask, s2ask)
print(rt.get_hyp())
if (what_need == "1"):
rt1()
else:
print("Sorry")
rorl = input("Right triangle? y or n")
if (rorl == "y") or (rorl == "yes") or (rorl == "Y") or (rorl == "Yes"):
right_tri()
elif (rorl == "n") or (rorl == "no") or (rorl == "N") or (rorl == "No"):
left_tri()
class Circle:
def __init__(self, radius):
self.radius = radius
def get_circ(self):
return (2 * self.radius) * pi
def get_area(self):
return (self.radius * self.radius) * pi
def my_cir():
askr = float(input("What is the radius?\nEnter: "))
myc = Circle(askr)
what = input("What do you need to know?\nCircumference\nArea\nEnter: ")
if (what == "Circumference") or (what == "circumference") or (what == "perimeter"):
print(myc.get_circ())
elif (what == "Area") or (what == "area"):
print(myc.get_area())
else:
print("Sorry I don't know that yet.")
##########################################################
#The interaction
##########################################################
askgeo = input("What shape do you want information on?\nTriangle\nRectangle\nCircle\nEnter: ")
if (askgeo == "Triangle") or (askgeo == "triangle"):
my_tri()
elif (askgeo == "Rectangle") or (askgeo == "rectangle"):
my_rec()
elif (askgeo == "Circle") or (askgeo == "circle"):
my_cir()
else:
print("Sorry! I don't have what you need yet.")
|
6528887bb9d07d26056f53b32bea096d8378a41a | witkowskipiotr/Checkio | /code_2017_11_06/tickets.py | 2,240 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Task from
http://www.codewars.com/kata/555615a77ebc7c2c8a0000b8/train/python
"""
def sell_tickets_to_all_customers(*, people: list) -> str:
"""
Can you sell a ticket to each person and give the change
if you initially has no money and sells the tickets strictly
in the order people follow in the line?
Each customer buy only one ticket.
Args:
people: list of int - dollar banknotes (25, 50, 100)
Return:
"YES" if can sell to all customer else "NO"
for example:
can_sell_tickets_to_all_customers([25, 25, 50]) -> YES
can_sell_tickets_to_all_customers([25, 50, 50]) -> NO
"""
stored_bills = []
ticket_price = 25
for client_bill in people:
if client_bill == ticket_price:
stored_bills.append(ticket_price)
elif client_bill < ticket_price:
return "NO"
else:
sorted_stored_bills = sorted(stored_bills, reverse=True)
rest_to_give = client_bill - ticket_price
can_give_rest = sum(stored_bills) >= rest_to_give
if can_give_rest:
sum_to_give = 0
for bill in sorted_stored_bills:
if sum_to_give == rest_to_give:
break
sum_to_give += bill
stored_bills.remove(bill)
else:
return "NO"
return "YES"
existing_banknotes_in_hand = []
for person_bill in people:
money = 25
# no need to spend
if person_bill == money:
# you sell ticket
existing_banknotes_in_hand.append(person_bill)
else:
# You have to spend the rest
existing_banknotes_in_hand.sort(reverse=True)
for iterate, bill in enumerate(existing_banknotes_in_hand):
if bill <= person_bill - money:
money += bill
# spend the rest
existing_banknotes_in_hand[iterate] = 0
if person_bill == money:
# you sell ticket
existing_banknotes_in_hand.append(person_bill)
else:
return "NO"
return "YES"
|
191d1cffc447494dd2960277262164ae88b01f9d | fatmanursaritemur/python-numpy-pandas-tutorial | /Python/Pandas/demo.py | 301 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
notes=pd.read_csv("grades.csv")
notes.columns =["ฤฐsim","Soyisim","SSN","T1","T2","T3","T4","Final","Grade"]
print(notes)
print(type(notes))
print(notes.head())
print("*******************************")
print(notes["ฤฐsim"])
print(notes.iloc[2]) |
1f648d440c2306e012d044c7bb98d095c9a22419 | xiyuansun/Udacity_Machine_Learning_Engineer | /Numpy_Practice/np_prac_02.py | 2,443 | 4.53125 | 5 | import numpy as np
'''
The following code is to help you play with Numpy, which is a library that provides functions that are especiall useful when you have to work with
large arrays and matrices of numeric data.
Numpy is battled tested and optimized so that it runs fast, much faster than if you were working with Python lists directly.
The array object class is the foundation of Numpy, and Numpy arrays are like lists in Python, except that every thing inside an array must be of the same type,
like int or float.
'''
# Change False to True to see Numpy arrays in action.
if False:
array = np.array([1,4,5,8], float)
print array
print ""
array = np.array([[1,2,3], [4,5,6]], float) #a 2D array/Matrix
print array
'''
You can index, slice, and manipulate a Numpy array much like you would with a Python list
'''
#Change False to True to see array indexing and slicing in action
if False:
array = np.array([1,4,5,8], float)
print array
print ""
print array[1]
print ""
print array[2]
print ""
array[1] = 5.0
print array[1]
#Change False to True to see Matrix indexing and slicing in action
if False:
two_D_array = np.array([[1,2,3], [4,5,6]], float)
print two_D_array
print ""
print two_D_array[1][1]
print ""
print two_D_array[1, :]
print ""
print two_D_array[:, 2]
'''
Here are some arithmetic operations that you can do with Numpy arrays
'''
#Change False to True to see Array arithmetics in action
if False:
array_1 = np.array([1,2,3], float)
array_2 = np.array([5,2,6], float)
print array_1 + array_2
print ""
print array_1 - array_2
print ""
print array_1 * array_2
#Change False to True to see Matrix arithmetics in action
if False:
array_1 = np.array([[1,2], [3,4]], float)
array_2 = np.array([[5,6], [7,8]], float)
print array_1 + array_2
print ""
print array_1 - array_2
print ""
print array_1 * array_2
'''
In addition to the standard arithimetic operations, Numpy also has a range of
other mathematical operations that you can apply to Numpy arrays, such as
mean and dot product
Both of these functions will be useful in later programming quizzes
'''
if False:
array_1 = np.array([1,2,3], float)
array_2 = np.array([[6], [7], [8]], float)
print np.mean(array_1)
print np.mean(array_2)
print ""
print np.dot(array_1, array_2)
|
927e692401759567398ddd5edb5d5427f2dbe65e | yeboahd24/Python201 | /PYTHON LIBRARY/SUB_2/datetime_date_math.py | 385 | 3.859375 | 4 |
import datetime
today = datetime.date.today()
print('Today :', today)
one_day = datetime.timedelta(days=1)
print('One day :', one_day)
yesterday = today - one_day
print('Yesterday:', yesterday)
tomorrow = today + one_day
print('Tomorrow :', tomorrow)
print()
print('tomorrow - yesterday:', tomorrow - yesterday)
print('yesterday - tomorrow:', yesterday - tomorrow) |
edc7118c1b673353a737fb5e7dd8e65671e7b76a | cpd-central/inventor | /excel/read_write_excel.py | 963 | 3.671875 | 4 | #script to read data from mongodb, put into pandas dataframe and write to excel.
#will be similar to putting the data on the website, these may be combined at some point.
import pandas as pd
def mongo_to_dataframe(documents):
mongo_df = pd.DataFrame(documents)
#removes the mongodb id from the dataframe
#mongo_df.drop('_id', axis=1, inplace=True)
return mongo_df
def send_to_excel(df, first_columns, excel_path):
#for display purposes, doesn't actually change
#NOTE, we could have the user input the columns, and have pandas order the columns that way
df = df[first_columns + [c for c in list(df.columns) if c not in first_columns]]
df.to_excel(excel_path, index=False)
def get_from_excel(excel_path, sheet):
#get the dataframe
df = pd.read_excel(excel_path, sheet_name=sheet)
#df_json = df.to_json(orient='records')
#mongo might not like nans, so we are going to replace them with empty strings
df.fillna('', inplace=True)
return df
|
ed0e2ff55e63644321bdc7a4aff22a696d1746c6 | MiyabiTane/myLeetCode_ | /31_m_Next_Permutation.py | 646 | 3.5625 | 4 | def nextPermutation(nums):
list=[]
for i in range(len(nums)):
pointer=len(nums)-1-i
#print(pointer)
if pointer==0:
nums.sort()
return nums
list.append(nums[pointer])
if nums[pointer-1]<nums[pointer]:
list.append(nums[pointer-1])
list.sort()
#print(list)
for j in range(len(list)):
if list[j]>nums[pointer-1]:
rem_num=list.pop(j)
break
nums[pointer-1]=rem_num
nums[pointer:]=list
return nums
nums=nextPermutation([1,3,2])
print(nums)
|
bda852dd871383e39613208b313f71f60edd3db0 | uniyalnitin/competetive_coding | /Hackerrank/hackerrank_(gena).py | 1,387 | 3.640625 | 4 | '''
Problem Url: https://www.hackerrank.com/challenges/gena/problem
Idea: Use BFS to get the minimum depth from current state to final state
'''
from collections import deque
def legal_moves(x):
'''
This function is used to get the valid moves from current state
'''
for i in range(len(x)):
if x[i]:
for j in range(len(x)):
if not x[j] or x[i][-1] < x[j][-1]:
# we can move disk from i to j iff either there is not disk at pole j or
# radius of top disk on pole j is greater that the ith pole top disk
yield (i, j)
def is_goal(x):
return all(len(x[i])==0 for i in range(1, len(x)))
def bfs(x):
def tuplify(x):
# convert list to tuple
return tuple(tuple(ele) for ele in x)
def do_move(state, m):
y = [list(t) for t in state]
y[m[1]].append(y[m[0]].pop())
y[1:4] = sorted(y[1:4], key = lambda t: t[-1] if t else 0)
return tuplify(y)
visited = set()
q = deque()
start = (tuplify(x), 0)
q.append(start)
while q:
state, depth = q.popleft()
if is_goal(state):
return depth
for move in legal_moves(state):
child_state = do_move(state, move) # get the next valid state
if child_state not in visited:
visited.add(child_state)
q.append((child_state, depth+1))
n = int(input())
R = list(map(int, input().split()))
A = [[] for _ in range(4)]
for i in range(n):
A[R[i]-1] = [(i+1)] + A[R[i]-1]
print(bfs(A))
|
26c98f87fd2a3247a4c2f5274d2face8f25094e8 | valen2510/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 395 | 3.71875 | 4 | #!/usr/bin/python3
"""function that returns True
if the object is an instance of
a class that inherited from the
specified class; otherwise False
"""
def inherits_from(obj, a_class):
"""Returns True if the object is an instance
of a class or specific inherited class
"""
if (type(obj) is not a_class):
return issubclass(type(obj), a_class)
return False
|
940a8ab3f2269fcbc7e5dd34aae86dca7d431d47 | Silentsoul04/my_software_study | /Algorithm/SWEA/6323_ํจ์์_๊ธฐ์ด_4.py | 665 | 3.890625 | 4 | # 1. 10์ ์น๋ฉด 10๊ฐ์ ํผ๋ณด๋์น ์์ด์ด ๋ฆฌ์คํธ ํ์์ผ๋ก ๋ํ๋๊ฒ ํ์.
# 2. while๋ฌธ์ ์ด์ฉํด์ ์ง์ ํ ์ซ์ ํ์๋งํผ ์ด์ ์ ์ซ์์ ํฉ์ณ์ง๊ฒ ๋ง๋ค์.
# 3. ํฉ์ณ์ง ์ซ์๋ฅผ appendํ์ฌ ๋ฆฌ์คํธ๋ฅผ ์ ์ํ์.
# 4. ๋ค ํ์ผ๋ฉด return ๊ฐ์ ๋ฐ์ ์ ์๋ ํจ์๋ฅผ ์ ์ํ๊ณ ํจ์๋ฅผ ๋ง๋ค๊ณ ์ถ๋ ฅํ์.
def function():
number = int(input(''))
start_number = 1
lis = [1,1]
number_new= 0
while start_number < number-1:
number_new = lis[-1] + lis[-2]
lis.append(number_new)
start_number = start_number + 1
return lis
result = function()
print(result)
|
ea997879fddb718a7a1ea941b475934721edab75 | IamFive/note | /note/python/recipel.py | 1,313 | 3.6875 | 4 | class RomanNumeralConverter(object):
def __init__(self, roman_numeral):
self.roman_numeral = roman_numeral
self.digit_map = {
"M":1000,
"D":500,
"C":100,
"L":50,
"X":10,
"V":5,
"I":1
}
def convert_to_decimal(self):
val = 0
for char in self.roman_numeral:
val += self.digit_map[char]
return val
import unittest
class RomanNumeralConverterTest(unittest.TestCase):
def setUp(self):
print 'setup'
def tearDown(self):
print 'teardown'
def test_parsing_millenia(self):
value = RomanNumeralConverter("M")
self.assertEquals(1000, value.convert_to_decimal())
def test_no_roman_numeral(self):
value = RomanNumeralConverter(None)
self.assertRaises(TypeError, value.convert_to_decimal)
def test_empty_roman_numeral(self):
value = RomanNumeralConverter("")
self.assertTrue(value.convert_to_decimal() == 0)
self.assertFalse(value.convert_to_decimal() > 0)
if __name__ == "__main__":
unittest.main()
|
f503f4822f5b659b0d7487b723498da185e1a14b | zubie7a/Algorithms | /HackerRank/Algorithms/01_Warmup/07_Staircase.py | 211 | 3.953125 | 4 | # https://www.hackerrank.com/challenges/staircase
n = int(raw_input())
# Print a staircase like
'''
n = 6
#
##
###
####
#####
######
'''
for i in range(n):
print " "*(n - i - 1) + "#"*(i + 1)
|
570d97f8af9ef484a7b2fa761cd0563ad585ca65 | jongfranco/python-workshop-wac-5 | /day_2/list_comrehension.py | 369 | 3.625 | 4 | """
{1^2, 2^2 .....}
{x^2 | for all x in natural numbers}
{2x + 1 | for all x in integers}
{2n | n in (3, 10)}
[f(x) for x in iterable]
"""
# value = [x % 2 for x in range(1, 11)]
# print(value)
print(''.join([character.upper() for character in 'hello world']))
print(sum(n ** 2 for n in range(1, 4)))
val = min(x for x in range(1, 11))
print(val)
print(type(val))
|
6cd2f2676d43735a662606f8a8b7b6049346a270 | cfireborn/PrepCS | /backend/Database for PrepCS Courses/6 - Recursion and Dynamic Programming/Recursion and Dynamic Programming.py | 8,037 | 3.84375 | 4 | """
===================================================================================
EASY
===================================================================================
"""
#########################################
"""
A child is running up a staircase with n steps, and can hope either 1 step,
2 steps, or 3 steps at a time. Implement a method to count how many possible
ways the child can run up the stairs.
"""
def count_ways(number_of_steps):
"""
The total number of ways of reaching the last step is therefore the
sum of the number of ways of reaching the last three steps
This solution is O(3^N) since there are three recursive calls at each level
"""
if number_of_steps < 0:
return 0
if number_of_steps == 0:
return 1
return count_ways(number_of_steps-1) + count_ways(number_of_steps-2) + count_ways(number_of_steps-3)
"""
===================================================================================
MEDIUM
===================================================================================
"""
#########################################
"""
A magic index in an array A[1...n-1] is defined to be an index such that
A[i] = i. Given a sorted array of distinct integers, write a method to find a magic
index, if one exists, in array A.
"""
def find_magic_index(integer_list, start_index, end_index):
"""
There is a linear time brute force solution which examines each element in
the list and checks to see if it is equal to its index. However, an approach
similar to binary search can be used to achieve O(log n) time complexity.
This only works properly when the elements are distinct.
"""
if end_index < 0 or start_index == len(integer_list):
return None
list_length = len(integer_list)
middle_index = (start_index + end_index) // 2
middle_element = integer_list[middle_index]
if middle_element == middle_index:
return middle_index
elif middle_element < middle_index:
return find_magic_index(integer_list, middle_index+1, end_index)
else:
return find_magic_index(integer_list, start_index, middle_index - 1)
#########################################
"""
A magic index in an array A[1...n-1] is defined to be an index such that
A[i] = i. Given a sorted array of non-distinct integers, write a method to find a magic index, if one exists, in array A.
"""
def find_magic_index(sorted_array, start, end):
"""
When the elements in the sorted array are non-distinct, then we need to
search both the left and right sides recursively
"""
if sorted_array == [] or end < start or start < 0 or end == len(sorted_array):
return None
middle_index = (start + end) // 2
middle_element = sorted_array[middle_index]
if middle_element == middle_index:
return middle_index
# search right side
rightIndex = max(middle_index + 1, middle_element)
right = find_magic_index(sorted_array, rightIndex, end)
if right: #If statement not present, will return None
return right
# search left side
leftIndex = min(middle_index - 1, middle_element)
left = find_magic_index(sorted_array, start, leftIndex)
if left:
return left
#Or y'know just use an interative loop. - Aarya
"""
===================================================================================
HARD
===================================================================================
"""
#########################################
"""
Implement a function that prints all possible combinations of the characters
in a string. These combinations range in length from one to the length of the
string. Two combinations that differ only in ordering of their characters are
the same combination. In other words, "12" and "31" are different combinations
from the input string "123", but "21" is the same as "12".
"""
class Combinations:
def __init__(self, input_string):
# constructor
self.input_string = input_string
self.comb_string = ""
self.do_combinations(0)
def do_combinations(self, start):
i = start;
while i < len(self.input_string):
self.comb_string = self.comb_string + self.input_string[i]
print (self.comb_string)
self.do_combinations(i+1)
self.comb_string = self.comb_string[:-1]
i = i + 1
def combinations_solutions(input_string, i, combined_string):
while i < len(input_string):
combined_string = combined_string + input_string[i]
print (combined_string)
combinations_solutions(input_string, i+1, combined_string)
combined_string = combined_string[:-1] #Removes last letter
i = i + 1
# combinations_solutions("wxyz", 0, "")
# if __name__ == '__main__':
# combinations = Combinations("wxyz", 0)
#########################################
"""
Implement a routine that prints all possible orderings of the characters in a
string. In other words, print all permutations that use all the characters
from the original string.
For example, given the string "hat", your function should
print the strings "tha", "aht", "tah", "ath", "hta", and "hat". Treat each
character in the input string as a distinct character, even if it is repeated.
Given the string "aaa", your routine should print "aaa" six times. You may print
the permutations in any order you choose.
"""
class Permutation:
def __init__(self, string):
# create the boolean list/array that keeps track of whether a character
# has been used
self.used = {}
for character in string:
self.used[character] = False
self.string = string
self.permuted_string = ""
self.do_permutation()
def do_permutation(self):
if len(self.permuted_string) == len(self.string):
print (self.permuted_string)
return
else:
for character in self.string:
if self.used[character]:
continue
self.permuted_string = self.permuted_string + character
self.used[character] = True
self.do_permutation()
self.used[character] = False
self.permuted_string = self.permuted_string[:len(self.permuted_string)-1]
if __name__ == "__main__":
permutation = Permutation("abcd")
#########################################
"""
A robot is located at the top-left corner of a m x n grid (marked "Start" in the diagram below). The robot can only
move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid
(marked "Finish" in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space
is marked as 1 and 0 respectively in the grid.
Note: m and n will be at most 100.
Example 1:
Input:
[
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
https://leetcode.com/problems/unique-paths-ii/description/
"""
def unique_paths_with_obstacles(obstacle_grid):
if obstacle_grid[0][0] == 1:
return 0
solutions = [[0 for _ in range(len(obstacle_grid[0]))] for _ in range(len(obstacle_grid))]
solutions[0][0] = 1
for i in range(len(obstacle_grid)):
for j in range(len(obstacle_grid[0])):
if obstacle_grid[i][j] != 1:
if i-1 >= 0:
solutions[i][j] += solutions[i-1][j]
if j-1 >= 0:
solutions[i][j] += solutions[i][j-1]
return solutions[len(obstacle_grid)-1][len(obstacle_grid[0])-1]
######################################### |
84446798522f7dba59ba5c6497d330983584fd28 | mandrakean/Estudo | /Python_Guan/ex056.py | 682 | 3.53125 | 4 | print('-=-'*20)
print('')
print('-=-'*20)
print('-=-')
soma_idade = 0
NH = ''
IV = 0
mul = 0
for c in range(1, 5):
print('----- {} PESSOA ------'.format(c))
nome = str(input('nome: '))
idade = int(input('idade: '))
sexo = str(input('Sexo (M/F): '))
soma_idade += idade
if c == 1 and sexo in 'Mm:':
iv = idade
NH = nome
if sexo in 'Mm' and idade > IV:
IV = idade
NH = nome
if sexo in 'Ff' and idade < 20:
mul += 1
media = soma_idade / 4
print('A mรฉdia das idades รฉ {}'.format(media))
print('o Homem mais velho tem {} anos e se chama {}'.format(IV, NH))
print('mulheres menores de 20 anos: {}'.format(mul))
|
a912818e829dac2f84bc7b9764dfd75140d58673 | banje/acmicpc | /2440.py | 83 | 3.71875 | 4 | a=int(input())
b="*"*(a+1)
for i in range(a):
b=b+" "
b=b[:-2]
print(b) |
da7a8fc01f7066430874c17e442c4290d313705c | Sionae/Stickmen_genetic_alg | /Functions.py | 2,770 | 3.5 | 4 | from time import time
from Classes import *
def StartPopulation(total):
population = []
for ind in range(0, total):
sword_length = random.randint(2, 5)
speed = random.randint(4, 15)
evade = random.random()
strength = random.randint(4, 15)
health = random.randint(10, 50)
population.append(DNA(
sword_length,
speed,
evade,
strength,
health))
print("done")
return population
def fight(indA, indB):
tstart = time()
healthA = indA.health
healthB = indB.health
def attack(health, ind1, ind2):
global count
#ind1 attacks ind2
if ind2.evade > random.random() * ind1.sword_length:
#B evades
pass
else:
health -= ind1.strength
return health
while time() - tstart < 0.005:
if indA.speed >= indB.speed:
#A starts to attack
healthB = attack(healthB, indA, indB)
if healthB <= 0:
indA.fitness += 1
break
healthA = attack(healthA, indB, indA)
if healthA <= 0:
indB.fitness += 1
break
else:
#B starts to attack
healthA = attack(healthA, indB, indA)
if healthA <= 0:
indB.fitness += 1
break
healthB = attack(healthB, indA, indB)
if healthB <= 0:
indA.fitness += 1
break
#If they manage to evade each other's attacks
indA.fitness += 1
indB.fitness += 1
def tournament(population):
"""Tournament where all individuals fight between each other"""
for A in range(0, len(population)):
for B in range(0, len(population)):
if A != B:
fight(population[A], population[B])
def subWith0min(a, b):
if a-b<0:
return 0
return a-b
def choose(l):
i = random.randint(0, len(l) - 1)
return l[i]
def nextGen(population, rate):
"""Creates the next generation"""
newPopulation = []
pop = []
for ind in population:
for x in range(0, ind.fitness):
pop.append(ind)
for n in range(0, len(population)):
#Randomly choose the individual
ind = choose(pop)
#Cross Over
seq = ind.crossOver(choose(pop))
new_ind = DNA(seq[0], seq[1], seq[2], seq[3], seq[4])
#Mutation
new_ind.mutate(rate)
#New individual formed!
newPopulation.append(new_ind)
return newPopulation
def findBest(population):
best = population[0]
for ind in population:
if ind.fitness > best.fitness:
best = ind
return best
|
aa70b6c5bd4d7acefb332c969ea3f13a9dbeb81a | mohamedsamyfoda/Code_Camp_Python | /Conditions/Conditions_6.py | 127 | 3.765625 | 4 | value1 = 10
value2 = 10
equal = value1 == value2
if equal == True :
print ('True')
if equal == False:
print('False')
|
3bbf813cf7de045952d9669a731f82a08af7627e | Himanshuma38966/furry-octo-goggles | /107.py | 353 | 3.59375 | 4 | import pandas as pd
import plotly.graph_objects as go
df=pd.read_csv("data.csv")
#to show how groupby works
'''
x=list(df.groupby("level"))
print(x)
'''
print(df.groupby("level")["attempt"].mean())
fig=go.Figure(go.Bar(x=df.groupby("level")["attempt"].mean(),y=["level 1","level 2","level 3","level 4"],orientation='h'))
fig.show()
|
60f6d99ac3be768e739cc93f15bd5747b30dacce | charan2108/pythonprojectsNew | /Dpython/datatypes/boolean.py | 93 | 3.625 | 4 | a = True
print(a)
print(type(a))
a = 10
b = 20
print(a>b)
print(a<b)
print(a>=b)
print(a<=b) |
46c54dc0dc2e3a8ef6a20a448e93139897da84d7 | EOppenrieder/HW070172 | /Homework5/Exercise6_8.py | 389 | 4.15625 | 4 | # A program to guess the square root of numbers
import math
def nextGuess(guess, x):
g = (guess + x / guess) / 2
return g
def main():
x = float(input("Enter the number of which you want to know the square root: "))
n = int(input("Enter the number of times to improve the guess: "))
g = x / 2
for i in range(n):
g = nextGuess (g,x)
print(g)
main() |
3daee9f5943b113cc004c49ebfa8102c5d42c98a | chandanadasarii/CrackingTheCodingInterview | /Heaps/heapsort.py | 345 | 3.765625 | 4 | from Heap import Heap
# Time complexity : O(nlogn)
def heapsort(data):
heap = Heap('maxheap')
heap.build_heap(data)
for i in range(len(data)-1, 0, -1):
heap.data[i], heap.data[0] = heap.data[0], heap.data[i]
heap.n -= 1
heap.precolate_down(0)
return heap.data
print(heapsort([5,3,17,10,84,19,6,22,9])) |
a5609f4bb31a16a8615c7f3ef7d8b37914fa90cc | Duvaragesh/hello-world | /hungry.py | 227 | 3.953125 | 4 | isHungry = input("Are you hungry?")
if isHungry == 'yes':
print('eat samosa!')
else:
print('do your work')
'sample change
'abcdef
'publicKeyToken=abcdef1234
'https://github.com/Duvaragesh/hello-world/edit/master/hungry.py
|
0521922fde3d4119b6d82948aee0e21e02bb2b89 | vigneshsrinivasan9/Disease-Named-Entity-Recognition | /utils/utils.py | 823 | 3.546875 | 4 | def get_tagged_sentences(data):
'''
Objective: To get list of sentences along with labelled tags.
Returns a list of lists of (word,tag) tuples.
Each inner list contains a words of a sentence along with tags.
'''
agg_func = lambda s: [(w, t) for w, t in zip(s["Word"].values.tolist(), s["tag"].values.tolist())]
grouped = data.groupby("Sent_ID").apply(agg_func)
sentences = [s for s in grouped]
return sentences
def get_test_sentences(data):
'''
Objective: To get list of sentences.
Returns a list of lists of words.
Each inner list contains a words of a sentence.
'''
agg_func = lambda s: [w for w in s["Word"].values.tolist()]
grouped = data.groupby("Sent_ID").apply(agg_func)
sentences = [s for s in grouped]
return sentences
|
31b952b6a68b87ca8795eb6d4dc5692a93002a71 | PedroVitor1995/Algoritmo-ADS-2016.1 | /Cadeias/resolvidos_momento/Questao02.py | 367 | 3.71875 | 4 | #__*__ encoding:utf8 __*__
"""2. Leia uma frase e mostre cada palavra da frase em uma linha separada."""
def main():
frase = raw_input('Digite uma frase: ')
frase = frase.split()
for i in range(len(frase)):
print frase[i]
# espaco = ' '
# for letra in espaco:
# frase = frase.replace(letra,'\n')
# print frase
if __name__ == '__main__':
main() |
86ac1f622127f98a4a0be2b2a6428571a8c0d206 | guoliangxd/interview | /huawei/Python/count.py | 476 | 3.8125 | 4 | while True:
try:
_str = input()
alpha = 0
space = 0
digit = 0
other = 0
for char in _str:
if char.isalpha():
alpha += 1
elif char.isspace():
space += 1
elif char.isdecimal():
digit += 1
else:
other += 1
print(alpha)
print(space)
print(digit)
print(other)
except:
break |
f65706ff6527e0cd146b8ede4d3d595b819a0dda | pensebien/intro_to_programming | /fib.py | 691 | 3.765625 | 4 | # Uses python3
import random
import time
st = time.clock()
def calc_fib(n):
a,b = 0,1
if n<=0:return a
for i in range(1,n):
a, b = b, a+b
return b
def fibMatrix(n):
ar = Array(n)
for i in range(2, n):
fib_num = ar[i-1] +ar[i-2]
return fib_num
if __name__ == '__main__':
#n = int(input())
a = [random.randint(1,10) for p in range(2)]
b = int(input())
print(calc_fib(b))
print("-- %s secs"%round((time.clock()-st)))
''' for i in range(len(a)):
print(i,end=' ')
print(a[i],end = ' ')
print(calc_fib(a[i]))
'''
#\print("The Fibonaci of ",n, "is ", "F(",n,") =", calc_fib(n))
|
7d3074e3078405bac74fff36372388e2033f6c6d | Abhi-1298/practice-1 | /inhertance.py | 2,107 | 4.21875 | 4 | '''You are given two classes, Person and Student, where Person is the base class and Student is the derived class. Completed code for Person and a declaration for Student are provided for you in the editor. Observe that Student inherits all the properties of Person.
Complete the Student class by writing the following:
A Student class constructor, which has 4 parameters
1)A string, firstname.
2)A string, lastname.
3)An integer, idnumber.
4)An integer array (or vector) of test scores,scores .
5)A char calculate() method that calculates a Student object's average and returns the grade character representative of their calculated average:
Grading table:-
=========================
Letter | Average(a)
--------------------
O | 90<=a<=100
E | 80<=a<90
A | 70<=a<80
P | 55<=a<=70
D | 40<=a<=55
T | a<40
'''
class Person:
def __init__(self,firstName,lastName,idNumber): # setting the value
self.firstName=firstName
self.lastName=lastName
self.idNumber=idNumber
def printPerson(self): # getting the values
print("Name:",self.lastName + ",",self.firstName)
print("ID:",self.idNumber)
class Student(Person):
def __init__(self, firstName, lastName, idNumber,scores):
Person.__init__(firstName, lastName, idNumber)
self.scores=scores
def calculate(self):
average=(scores+scores)/2
if average>=90 and average<=100:
average='O'
elif average>=80 and average<90:
average='E'
elif average>=70 and average<80:
average='A'
elif average>=55 and average<70:
average="P"
elif average>=40 and average<55:
average="D"
else:
average="T"
return average
line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student()
s.printPerson()
print("Grade:", s.calculate()) |
acc3cccb9a89f0ea20e4ed9478bcdb67c83fa251 | rajaprerak/Algorithmic_Toolbox-Coursera-Python | /Week4/majority_element.py | 594 | 3.609375 | 4 | def majority_element(elements):
assert len(elements) <= 10 ** 5
track_count = {}
for each in elements:
if each in track_count:
track_count[each] += 1
else:
track_count[each] = 1
for value in track_count.values():
if value > len(elements) / 2:
return 1
else:
temp = 0
if temp == 0:
return 0
if __name__ == '__main__':
input_n = int(input())
input_elements = list(map(int, input().split()))
assert len(input_elements) == input_n
print(majority_element(input_elements))
|
3339ecc89f97fe272fbd23fb57a2402a682441ba | yunfei-teng/PyTorch-Tutorial-Spring-2019 | /recitation1/classification/models.py | 1,501 | 3.578125 | 4 | # PyTorch tutorial codes for course EL-9133 Advanced Machine Learning, NYU, Spring 2018
# models.py: define model structures
# read: https://pytorch.org/docs/stable/nn.html
import torch.nn as nn
import torch.nn.functional as F
class ConvNet(nn.Module):
''' convolutional neural network '''
def __init__(self):
super(ConvNet, self).__init__()
nf = 8
# Conv2d(in_channels, out_channels, kernel_size, stride=1, etc.)
self.conv1 = nn.Conv2d( 1, nf* 1, 5, 1, 0) #24
self.conv2 = nn.Conv2d(nf* 1, nf* 2, 4, 2, 1) #12
self.conv3 = nn.Conv2d(nf* 2, nf* 4, 5, 1, 0) #8
self.conv4 = nn.Conv2d(nf* 4, nf* 8, 4, 2, 1) #4
self.conv5 = nn.Conv2d(nf* 8, 10, 4, 1, 0) #1
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
x = F.relu(self.conv4(x))
x = self.conv5(x)
x = x.view(-1, 10)
return F.log_softmax(x, dim=1)
class FCNet(nn.Module):
''' fully-connected neural network '''
def __init__(self):
super(LinearNet, self).__init__()
self.fc1 = nn.Linear(784, 400)
self.fc2 = nn.Linear(400, 200)
self.fc3 = nn.Linear(200, 100)
self.fc4 = nn.Linear(100, 10)
def forward(self, x):
x = x.view(-1, 784)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return F.log_softmax(x, dim=1)
|
c4f3800d63ee2ccbd8751587280c7b896736fde3 | tribadboy/algorithm-homework | /week4/ๆฌๅท็ๆ.py | 533 | 3.59375 | 4 | # -*- coding:utf-8 -*-
from typing import List
class Solution:
def generate(self, left: int, right: int, n: int, chars: str, result: List[str]):
if left == n and right == n:
result.append(chars)
if left < n:
self.generate(left+1, right, n, chars+'(', result)
if right < left:
self.generate(left, right+1, n, chars+')', result)
def generateParenthesis(self, n: int) -> List[str]:
result = []
self.generate(0, 0, n, '', result)
return result |
8e88c367875f6cb78e4e93ef4fa07395e45bfaf3 | yamabook37/atcoder | /Library/my_sort.py | 445 | 3.84375 | 4 | # bubble
def bubble(num):
# ๆน้
# ๅพใใใ้ ใซ้ฃใๅใ่ฆ็ด ใๆฏ่ผใใใ
# ๅทฆใๅณใฎ่ฆ็ด ใซๆฏในๅคงใใๅ ดๅไบคๆใ
# ่ตฐๆป็ฏๅฒใๅใใใฒใจใค็ญใใใ
for i in range(len(num)-1):
for j in range(len(num)-1, i ,-1):
if num[j] > num[j-1]:
tmp = num[j-1]
num[j-1] = num[j]
num[j] = tmp
print(num)
return num
array = [2, 3, 5, 4, 1]
print(bubble(array)) |
7a72b5d807c2314e2c656161d08f6ed3c3e64ca8 | MichelFeng/leetcode | /118.py | 937 | 3.734375 | 4 | # coding=utf8
# 118. ๆจ่พไธ่ง
# ็ปๅฎไธไธช้่ดๆดๆฐ numRows๏ผ็ๆๆจ่พไธ่ง็ๅ numRows ่กใ
# ๅจๆจ่พไธ่งไธญ๏ผๆฏไธชๆฐๆฏๅฎๅทฆไธๆนๅๅณไธๆน็ๆฐ็ๅใ
# ็คบไพ:
# ่พๅ
ฅ: 5
# ่พๅบ:
# [
# [1],
# [1, 1],
# [1, 2, 1],
# [1, 3, 3, 1],
# [1, 4, 6, 4, 1]
# ]
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
res = []
i = 1
while i <= numRows:
j = 1
row = []
while j <= i:
if j == 1 or j == i:
row.append(1)
else:
row.append(res[i-2][j-1] + res[i-2][j-2])
j += 1
res.append(row)
i += 1
return res
s = Solution()
print s.generate(0)
print s.generate(1)
print s.generate(2)
print s.generate(3)
print s.generate(5)
|
93053cfa0b36987ceb64f9bd4c2884989fab1b87 | Sajan-Optimal-AI/self-landing-rocket-simulation | /simulator.py | 5,381 | 3.984375 | 4 | """Simple rocket simulator.
Some Physical Limits Due To My Unexperience in Physics Yet :
* The rocket is treated as point with only thrust and gravity acting on it.
* The rocket is perfectly stable with no horizontal forces acting on it.
* The rocket is indestructable.
* The rocket has infinite fuel and therefore its mass does not change as
it burns fuel.
* The rocket is able to apply any percentage of thrust instantaneously and
with perfect precision.
"""
import time
import graphics as g
import numpy as np
import tkinter as tk
from controller import OnOffController
from controller import PIDController
TITLE = 'Rockets'
WIDTH = 800
HEIGHT = 600
FPS = 60
SCALE = 2 # Pixels per meter.
GRAVITY = np.array((0, 1.62)) # In m/s^2.
GROUND_Y = 550 # In pixels.
TARGET_Y = 200 # In pixels.
class Rocket(object):
"""A rocket equipped with a bottom thruster."""
def __init__(self,
pos,
height=21.2,
diameter=3.7,
mass=167386.,
max_thrust_force=410000.,
controller=None):
self._pos = np.array(pos, dtype=np.float32)
self._vel = np.array((0., 0.))
self._mass = mass
self._thrust_max_force = np.array((0., -max_thrust_force))
self._thrust_percent = 0
self._controller = controller
self._actions = range(0, 11)
self._height = height
self._diameter = diameter
# TODO(eugenhotaj): These below were set arbitrarily. Maybe look up how
# to set them better?
self._exhaust_max_height = 12.5
self._exhaust_width = 1
self._exhaust_color = "orange"
def set_thrust(self, percent):
"""Sets the rocket's thrust."""
assert int(percent * (len(self._actions) - 1)) in self._actions
self._thrust_percent = percent
def _sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def update(self, dt):
"""Resolve the forces acting on the rocket and update position."""
if self._controller:
control_var = self._controller.tick(self._pos[1], dt)
thrust_percent = round(self._sigmoid(-control_var), 1)
self.set_thrust(thrust_percent)
acc = GRAVITY
if self._thrust_percent:
thrust_force = self._thrust_max_force * self._thrust_percent
thrust_acc = thrust_force / self._mass
acc = acc + thrust_acc
self._vel += acc * dt
self._pos += self._vel * dt
# TODO(eugenhotaj): Temporary hack for ground collision. Long term,
# figure out what the reacting force is and apply to rocket.
if self._pos[1] >= GROUND_Y:
# Do not stop the rocket if it is going up.
self._pos[1] = GROUND_Y
self._vel[1] = min(0, self._vel[1])
def drawables(self):
"""Returns a list of GraphicsObjects necessary to draw the rocket."""
# TODO(eugenhotaj): Remove hardcoded SCALE.
drawables = []
x, y = self._pos.tolist()
radius = (self._diameter * SCALE) / 2
height = self._height * SCALE
body = g.Polygon(g.Point(x - radius, y), g.Point(x + radius, y),
g.Point(x, y - height))
drawables.append(body)
exhaust_height = (self._exhaust_max_height * self._thrust_percent *
SCALE)
if exhaust_height:
exhaust = g.Line(g.Point(x, y),
g.Point(x, y + exhaust_height))
exhaust.setWidth(self._exhaust_width) # Do not scale exhaust width.
exhaust.setOutline(self._exhaust_color)
drawables.append(exhaust)
return drawables
class Simulation(object):
"""Simulates the Rocket environment."""
def __init__(self):
self._window = g.GraphWin(TITLE, WIDTH, HEIGHT, autoflush=False)
controller = PIDController(setpoint=TARGET_Y, kp=1., ki=.0001, kd=2.3)
self._rocket = Rocket(pos=(WIDTH/2, GROUND_Y), controller=controller)
def _static_drawables(self):
"""Returns GraphicsObjects that only need to be drawn once."""
ground = g.Line(g.Point(0, GROUND_Y), g.Point(WIDTH, GROUND_Y))
target = g.Line(g.Point(WIDTH/2 - 50, TARGET_Y),
g.Point(WIDTH/2 + 50, TARGET_Y))
target.setOutline("red")
return ground, target
def _draw(self, drawables):
for drawable in drawables:
drawable.draw(self._window)
def _undraw(self, drawables):
for drawable in drawables:
drawable.undraw()
def run(self):
"""Runs the simulation until the user closes out."""
self._draw(self._static_drawables())
dynamic_drawables = []
t0 = time.time()
while self._window.isOpen():
# Resolve time since last tick.
t = time.time()
dt = (t - t0) * SCALE
t0 = t
# Run simulation for 1 tick.
self._undraw(dynamic_drawables)
dynamic_drawables = []
self._rocket.update(dt)
dynamic_drawables.extend(self._rocket.drawables())
self._draw(dynamic_drawables)
g.update(FPS) # Enforce FPS.
if __name__ == '__main__':
Simulation().run() |
0e39a0ac2bd6ef04d22247058fc1c7a3a1b7b0aa | tanyalevshina/decisionengine | /src/decisionengine/framework/util/tsort.py | 2,056 | 4.0625 | 4 | """
See:
https://en.wikipedia.org/wiki/Topological_sorting
Kahn's topological sorting algorithm
L Empty list that will contain the sorted elements
S Set of all nodes with no incoming edge
while S is non-empty do
remove a node n from S
add n to tail of L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
"""
import logging
def tsort(graph):
"""
Function implementing Kahn's topological sorting algorithm
returns two lists : sorted list and cyclic lost
(if graph is acyclic second list is always None)
:type graph: :obj:`dict` that contains pairs of vertices
and adjacent edges.
:rtype: :obj:`list`
"""
logging.getLogger().debug("in tsort")
if isinstance(graph, list):
graph = dict(graph)
"""
count incoming edges for each vertex
"""
incoming_edges = {}
for vertex, edges in list(graph.items()):
incoming_edges.setdefault(vertex, 0)
for edge in edges:
incoming_edges[edge] = incoming_edges.get(edge, 0) + 1
"""
create dict of vertices that have no incoming edges
"""
empty = {v for v, count in list(incoming_edges.items()) if count == 0}
sorted_graph = []
while empty:
"""
pick a vertex w/ no incoming edges
"""
v = empty.pop()
sorted_graph.append(v)
"""
decrement edge counts for
edges that have connection from this vertex
vertex.
"""
for edge in graph.get(v, []):
incoming_edges[edge] -= 1
if incoming_edges[edge] == 0:
empty.add(edge)
cyclic_graph = [v for v, count in list(incoming_edges.items()) if count != 0]
"""
if there are no cyclic dependencies the above list is None
"""
return sorted_graph, cyclic_graph
|
e795bea0ba602aeecac5be55eadb7ecdfe156847 | arsamigullin/problem_solving_python | /leet/amazon/trees_and_graphs/1334_Find_the_City_With_the_Smallest_Number_of_Neighbors_at_a_Threshold_Distance.py | 3,641 | 3.609375 | 4 | import collections
import heapq
from typing import List
class SolutionWrong:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
# a deque is faster at removing elements from the front
graph = collections.defaultdict(dict)
for u, v, dist in edges:
if dist < distanceThreshold:
graph[u][v] = dist
graph[v][u] = dist
# print(graph)
def find_dist(start):
distances = {vertex: float('inf') for vertex in graph}
pq = []
pq_update = {}
distances[start] = 0
for vertex, value in distances.items():
entry = [vertex, value]
heapq.heappush(pq, entry)
pq_update[vertex] = entry
while pq:
getmin = heapq.heappop(pq)[0]
for neighbour, distance_neigh in graph[getmin].items():
dist = distances[getmin] + distance_neigh
if dist < distances[neighbour]:
distances[neighbour] = dist
pq_update[neighbour][1] = dist # THIS LINE !!!
# print(distances)
return distances
# def find_dist(start):
# destinations = {start:0}
# queue = collections.deque([start])
# while queue:
# u = queue.popleft()
# dist = destinations[u]
# for v, vdist in graph[u].items():
# vdist+=dist
# if vdist > distanceThreshold:
# continue
# if v not in destinations:
# queue.append(v)
# destinations[v] = vdist
# elif vdist < destinations[v]:
# destinations[v] = vdist
# destinations.pop(start)
# return destinations
reachable_cities = float('inf')
curr_node = -1
# print(find_dist(1))
for key in range(n):
dists = find_dist(key)
if len(dists) < reachable_cities:
curr_node = key
reachable_cities = len(dists)
elif len(dists) == reachable_cities and curr_node < key:
curr_node = key
return curr_node
from heapq import heappush, heappop
class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
# this for fast taking weight of the edge
cost = [[float('inf')] * n for _ in range(n)]
graph = collections.defaultdict(list)
for a, b, c in edges:
cost[a][b] = cost[b][a] = c
graph[a].append(b)
graph[b].append(a)
def dijkstra(i):
dis = [float('inf')] * n
dis[i], pq = 0, [(0, i)]
heapq.heapify(pq)
while pq:
d, i = heapq.heappop(pq)
if d > dis[i]: continue
for j in graph[i]:
this_cost = d + cost[i][j]
if this_cost < dis[j]:
dis[j] = this_cost
heapq.heappush(pq, (this_cost, j))
return sum(d <= distanceThreshold for d in dis) - 1
res = {dijkstra(i): i for i in range(n)}
return res[min(res)]
if __name__ == '__main__':
s = Solution()
s.findTheCity(4, [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], 4)
|
19c231cad39b0cee44f5264a3eaf78ac4294bfd6 | xuweixinxxx/HelloPython | /nowcoder/foroffer/Solution10.py | 1,449 | 3.578125 | 4 | '''
Created on 2018ๅนด1ๆ30ๆฅ
้ข็ฎๆ่ฟฐ
่พๅ
ฅไธๆฃตไบๅๆ็ดขๆ ๏ผๅฐ่ฏฅไบๅๆ็ดขๆ ่ฝฌๆขๆไธไธชๆๅบ็ๅๅ้พ่กจใ่ฆๆฑไธ่ฝๅๅปบไปปไฝๆฐ็็ป็น๏ผๅช่ฝ่ฐๆดๆ ไธญ็ป็นๆ้็ๆๅใ
@author: minmin
'''
class Solution10:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
if not pRootOfTree.left and not pRootOfTree.right:
return pRootOfTree
if pRootOfTree.right:
#ๅฆๆๅณ่็นๅญๅจ๏ผ้่ฟ้ๅฝๆพๅฐๅณ่็น้พ่กจ็้ฆ่็น๏ผๅฐๅ
ถไธpRootOfTree่ฟๆฅ่ตทๆฅ
rightNode = self.Convert(pRootOfTree.right)
rightNode.left = pRootOfTree
pRootOfTree.right = rightNode
if pRootOfTree.left:
#ๅฆๆๅทฆ่็นๅญๅจ๏ผ้่ฟ้ๅฝๆพๅฐๅทฆ่็น้พ่กจ็ๅฐพ่็น๏ผๅฐๅ
ถไธpRootOfTree่ฟๆฅ่ตทๆฅ
leftNode = self.Convert(pRootOfTree.left)
leftNode_last = self.FindLastNode(leftNode)
leftNode_last.right = pRootOfTree
pRootOfTree.left = leftNode_last
return leftNode
else:
#ๅฆๆๅทฆ่็นไธๅญๅจ๏ผๅ่ฏดๆpRootOfTreeๅทฒ็ปๆฏ้ฆ่็นไบ
return pRootOfTree
def FindLastNode(self, treeNode):
if not treeNode:
return None
while treeNode.right:
treeNode = treeNode.right
return treeNode |
c507ff6dbf30213e74ff53cbf4cd8ffc635b900d | GabrielAbdul/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,530 | 4.5 | 4 | #!/usr/bin/python3
"""
class Square that defines a square based on 5-square.py
"""
class Square:
""" Class of square that has no size
Attributes:
__size (int): size of square
"""
def __init__(self, size=0, position=(0, 0)):
"""
Initialization of square size
Args:
size (int): input square size
position (tuple): input (x, y) position(s) of square
"""
if type(size) != int:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
else:
self.__size = size
if type(position) != tuple:
raise TypeError("position must be a tuple of two positive integer\
s")
else:
self.__position = position
def area(self):
"""
Method of class Square that computes are
"""
return (self.__size * self.__size)
@property
def size(self):
"""
Method of class Square that retrieves square size
"""
return self.__size
@property
def position(self):
"""
Method of class Square that retrieves square position
"""
return self.__position
@size.setter
def size(self, value):
"""
Method of class Sqaure that sets size
Args:
value: value to set size to
"""
if type(value) != int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
@position.setter
def position(self, value):
"""
Method of class Square that sets position
Args:
value: value to set position to
"""
if value[0] < 0 or value[1] < 0:
raise TypeError("position must be a tuple of 2 positive integers")
else:
self.__position = value
def my_print(self):
"""
Method of class Square that prints the square with the # char
"""
if self.__size == 0:
print()
else:
for newlines in range(self.__position[1]):
print()
for rows in range(self.__size):
for space in range(self.__position[0]):
print(' ', end="")
for cols in range(self.__size):
print('#', end='')
print()
|
ea9ac4d8272067629e5bf89cbbd5f9e4feb694b0 | yareddada/CSC101 | /CH-06/Programming-Exercises/ex_6-3.py | 376 | 3.96875 | 4 | '''\
Rev: 1
Name: silentshadow
Description:
Reference: exercise 6.3
Page: 203 (PDF 223)
'''
def palindrome( n):
if ( n[ ::-1] ) == n :
print( "Found one!")
else:
print( "Sorry")
def main():
print( "Let's find us a Palindrome number!")
n = input( "Give a number: ")
palindrome( n)
if __name__ == '__main__': main() |
af634cb835cafe23a9f4b0fc908c0b64d5f7d197 | cmychina/Leetcode | /leetcode_ๅๆoffer_65.็ฉ้ตไธญ็่ทฏๅพ.py | 912 | 3.765625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
M = len(matrix)
N = len(matrix[0])
d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
self.visited = set()
def dfs(x, y, k):
if not (0 <= x < M and 0 <= y < N and matrix[x][y] == path[k] and (x, y) not in self.visited):
return False
if matrix[x][y] == path[k] and k == len(path) - 1:
return True
self.visited.add((x, y))
k = dfs(x + 1, y, k + 1) or dfs(x - 1, y, k + 1) or dfs(x, y + 1, k + 1) or dfs(x, y - 1, k + 1)
self.visited.remove((x, y))
return k
for i in range(M):
for j in range(N):
if matrix[i][j] == path[0]:
res = dfs(i, j, 0)
if res == True:
return True
return False
|
d86cde7e61e0da90fd7bd945e844c7b49a773772 | Tanmay53/cohort_3 | /submissions/sm_026_rohit-kumar/week_14/day_3/evaluation/average_diff.py | 394 | 4 | 4 | num_list = [1,2,3,4,5,6]
def average_diff(arr):
even_sum = 0
odd_sum = 0
# sum of nums present at even index
for i in range(0, len(arr), 2):
even_sum = even_sum + arr[i]
# sum of nums present at odd index
for i in range(1, len(arr), 2):
odd_sum = odd_sum + arr[i]
return even_sum - odd_sum
# call the function
print(average_diff(num_list)) |
f9d2421622ee9395094068198a00bc86fb5f0bd1 | JeffersonKaioSouza/Exercicios-de-Python | /ex015.py | 217 | 3.609375 | 4 | dias = int(input('Digite a quantidade de dias: '))
km = float(input('Digite a quantida de km rodados: '))
cdias = dias * 60
ckm = km * 0.15
print('O valor a ser pago pelo aluguel รฉ de R$:{:.2f}'.format(cdias + ckm)) |
60b8da3f24a2f2c1467986682e36994eb3218f33 | tathamitra/TathaPython | /tut12.py | 497 | 3.90625 | 4 | #for loops
#
# l1 = ["jack", "jill", "mark", "paul"]
#
# for name in l1:
# print(name)
# l1 = [["jack", 1], ["jill", 2], ["mark", 7], ["paul", 9]]
#
# for name, wife in l1:
# print(name, "number of wives", wife)
#
# d1 = dict(l1)
# for name in d1:
# print(name)
# for name, wives in d1.items():
# print(name, "number of wives", wives)
l1 = [1, 2, "jack", "jill", 7, 11]
for item in l1:
if str(item).isnumeric() and item > 6:
print(item)
|
58eb5d25a58bb203ead30bf25e1cbddb6940840e | Smithmichaeltodd/Learning-Python | /Gregorian Epact.py | 359 | 3.65625 | 4 | #Tis program determines the vale of the epact
#By Michael Smith
import math
def main():
print('Gregorian epact calculator!')
print()
Y = eval(input('Please input a 4 digit year your would like to calculate for: '))
C = Y//100
epact = (8 + (C//4) - C + ((8*C + 13)//25) + 11*(Y%19))%30
print('Your epact number is', epact)
main() |
3e1c4963fa0f1a654975f3e41c4a489f81604f5e | ddiana/CellECT | /CellECT/seg_tool/seg_utils/union_find.py | 1,985 | 3.53125 | 4 | # Author: Diana Delibaltov
# Vision Research Lab, University of California Santa Barbara
# Imports
import pdb
"""
Implementation of union find.
This is used by the nuclei collection for merging segments.
"""
class UnionFind(object):
def __init__ (self, number_lements):
self.parents = range(number_lements)
self.set_size = [1] * number_lements
self.is_deleted = [0] * number_lements
def add_one_item_to_union(self):
"Add an item to the existing union."
self.parents.append(len(self.parents))
self.set_size.append(1)
self.is_deleted.append(0)
def find(self, element):
"Find the head of the set that 'element' is in."
while (self.parents[element] != element):
element = self.parents[element]
return element
def delete_set_of(self, element):
root = self.find(element)
self.is_deleted[root] = 1
# TODO check if you need to call find for set size.
def union (self, element1, element2):
"Union of two elements."
"If one is deleted, then both are deleted."
root_element1 = self.find(element1)
root_element2 = self.find(element2)
if root_element1 != root_element2:
# if self.set_size[root_element1] < self.set_size[root_element2]:
# self.parents[root_element1] = root_element2
# elif self.set_size[root_element1] > self.set_size[root_element2]:
# self.parents[root_element2] = root_element1
# else:
# self.parents[root_element2] = root_element1
# self.set_size[root_element1] = self.set_size[root_element1] +1
if self.set_size[root_element1] > self.set_size[root_element2]:
self.set_size[root_element1] += self.set_size[root_element2]
self.parents[root_element2] = root_element1
else:
self.set_size[root_element2] += self.set_size[root_element1]
self.parents[root_element1] = root_element2
self.is_deleted[root_element1] = self.is_deleted[root_element1] or self.is_deleted[root_element2]
self.is_deleted[root_element2] = self.is_deleted[root_element1] or self.is_deleted[root_element2]
|
a0d2609ccac235d7813b02a7bae4998854cf69e1 | tuxlimr/sonu1 | /Beautifulsoup/Sports-firstpost.py | 636 | 3.53125 | 4 | from bs4 import BeautifulSoup as soup
from urllib.request import Request, urlopen
# req = Request('https://www.firstpost.com/firstcricket/', headers={'User-Agent': 'Mozilla/5.0'})
# webpage = urlopen(req).read()
# page_soup = soup(webpage, "html.parser")
# containers13 = page_soup.find("div", {"class": "first-story"})
# print(containers13.h1.text)
req = Request('https://www.firstpost.com/firstcricket/', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()
page_soup = soup(webpage, "html.parser")
containers12 = page_soup.find("div", {"class": "first-story"})
containers13 = containers12.h1.text
print(containers13) |
26953e85da92204fa396de840c4a76cc6b1a5cf7 | Makoto-Taguchi/kadai1 | /kadai1_4.py | 827 | 3.703125 | 4 | import csv
input_path = './csv_files/input_file.csv'
output_path = './csv_files/output_file.csv'
with open(input_path, 'r') as f :
reader = csv.reader(f)
for source in reader :
print(source)
# # ๆค็ดขใฝใผใน
# source=["ใญใใ","ใใใใใ","ใใใใใ
ใใ","ใใใ","ใใใ","ใใชใ","ใใใใค"]
### ๆค็ดขใใผใซ
def search():
word =input("้ฌผๆป
ใฎ็ปๅ ดไบบ็ฉใฎๅๅใๅ
ฅๅใใฆใใ ใใ >>> ")
### ใใใซๆค็ดขใญใธใใฏใๆธใ
if word in source:
print("{}ใ่ฆใคใใใพใใ".format(word))
else:
print("{}ใ่ฆใคใใใพใใใงใใ".format(word))
source.append(word)
print(source)
if __name__ == "__main__":
search()
with open(output_path, 'w') as f:
writer = csv.writer(f)
writer.writerow(source) |
52995eba75dcc5c0564e0e5cfe585ba305d56d7c | poc7667/internal-training-python-course | /05-file_io/sort.py | 165 | 3.53125 | 4 | import pprint
people = [
["Apple", 500, 1000],
["Zebra", 5000,500],
["Carlos", 5, 3]
]
print sorted(people, key = lambda x : x[-1])
print sorted(people) |
edf61aab9e90a59b4b70b3eb24a16785b571f19e | bitromortac/plottoterminal | /plottoterminal/lib/utils.py | 364 | 3.734375 | 4 | PI = 3.14159265359
def linspace(start: float, end: float, steps: int = 100):
assert start < end
return [start + (end - start) * i / steps for i in range(steps + 1)]
def rint(f: float) -> int:
"""
Rounds to an int.
rint(-0.5) = 0
rint(0.5) = 0
rint(0.6) = 1
:param f: number
:return: int
"""
return int(round(f, 0))
|
55982d0837bb9a8288fb9261c5ea7f00690f1327 | PROxZIMA/Python-Projects | /User_Packages/amult.py | 236 | 4.125 | 4 | def mult():
L=[]
b=1
num=int(input("Enter how many numbers you are multiplying : "))
for i in range(num):
n=float(input("Enter the numbers : "))
L.append(n)
b=b*n
print('Multiplication of the numbers is =',b) |
8c067bbb8ba826cb9fbde1fb58c737583f9f06e2 | AlexArango/PythonExercises | /ex6.py | 859 | 4.28125 | 4 | # Just trying things out
#print "%r print = 'does this work?' and again 'works?' "+'let us see'+' "no?"'
# Declaring variables in Python. It seems like there are not different types
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
# Combines the previous strings declared above
print "I said: %r." % x
print "I also said: '%s'." % y
# Toying with Boolean values
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
# Long way of writing: print "Isn't that joke so funny?! %r" % hilarious
print joke_evaluation % hilarious
# Adding strings like they're math
w = "This is the left side of..."
e = "a string with a right side."
# Shorter way of writing:
# print "This is the left side of..." + "a string with a right side."
print w + e |
ac33a7a35c7e28a521d1f41838e9097687d887f3 | akcauser/Python | /PythonCharArrayMethods/index()&&rindex().py | 439 | 3.875 | 4 |
#index metodu bize 1. parametrede girdiฤimiz deฤerin ilk hangi indexkste karลฤฑlaลฤฑldฤฑฤฤฑ bilgisini verir
#2. ve 3. parametreleri ise aralฤฑk belirtir
city = "alanya"
print(city.index("a")) # รงok da iyi bir metod deฤildir , yerine aลaฤฤฑdaki algoritma iล gรถrรผyor
counter = -1
for i in city:
counter += 1
if i == "a":
print(counter)
## rindex metodu da aynฤฑ ลeyi saฤdan sola doฤru yapmaktadฤฑr.
|
210f281cb2c0dc5ea11841ad1b2ccfc028ae7dbd | jvano74/advent_of_code | /2015/day_05_test.py | 3,819 | 4.03125 | 4 | import re
def nice(word):
"""
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Santa needs help figuring out which strings in his text file are
naughty or nice.
A nice string is one with all of the following properties:
It contains at least three vowels (aeiou only), like aei, xazegov,
or aeiouaeiouaeiou.
It contains at least one letter that appears twice in a row, like xx, abcdde
(dd), or aabbccdd (aa, bb, cc, or dd).
It does not contain the strings ab, cd, pq, or xy, even if they are part
of one of the other requirements.
For example:
ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...),
a double letter (...dd...), and none of the disallowed substrings.
aaa is nice because it has at least three vowels and a double letter,
even though the letters used by different rules overlap.
jchzalrnumimnmhp is naughty because it has no double letter.
haegwjzuvuyypxyu is naughty because it contains the string xy.
dvszwmarrgswjxmb is naughty because it contains only one vowel.
How many strings are nice?
"""
if re.match(".*(ab|cd|pq|xy)", word):
return False
if len(re.findall("(a|e|i|o|u)", word)) > 2:
if re.match(r".*(.){1}\1", word):
return True
return False
def test_nice():
assert re.match(r".*(.){1}\1", "abb")
assert nice("ugknbfddgicrmopn")
assert nice("aaa")
assert not (nice("jchzalrnumimnmhp"))
assert not (nice("haegwjzuvuyypxyu"))
assert not (nice("dvszwmarrgswjxmb"))
def test_wrapping_paper_sub():
with open("./input_day_5.txt", "r") as fp:
total = 0
line = fp.readline()
while line:
if nice(line):
total += 1
line = fp.readline()
assert total == 238
def nice2(word):
"""
--- Part Two ---
Realizing the error of his ways, Santa has switched to a better model
of determining whether a string is naughty or nice.
None of the old rules apply, as they are all clearly ridiculous.
Now, a nice string is one with all of the following properties:
It contains a pair of any two letters that appears at least twice in
the string without overlapping, like xyxy (xy) or aabcdefgaa (aa),
but not like aaa (aa, but it overlaps).
It contains at least one letter which repeats with exactly one letter
between them, like xyx, abcdefeghi (efe), or even aaa.
For example:
qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj)
and a letter that repeats with exactly one letter between them (zxz).
xxyxx is nice because it has a pair that appears twice and a letter
that repeats with one between, even though the letters used by each
rule overlap.
uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat
with a single letter between them.
ieodomkazucvgmuy is naughty because it has a repeating letter with
one between (odo), but no pair that appears twice.
How many strings are nice under these new rules?
"""
if re.match(r".*(..){1}.*\1", word):
if re.match(r".*(.){1}(.){1}\1", word):
return True
return False
def test_nice():
assert re.match(r".*(..){1}.*\1", "xyxy")
assert re.match(r".*(..){1}.*\1", "aabcdefgaa")
assert not (re.match(r".*(..){1}(.*)\1", "aaa"))
assert nice2("qjhvhtzxzqqjkmpb")
assert nice2("xxyxx")
assert not (nice2("uurcxstgmygtbstg"))
assert not (nice2("ieodomkazucvgmuy"))
def test_wrapping_paper_sub():
with open("./input_day_5.txt", "r") as fp:
total = 0
line = fp.readline()
while line:
if nice2(line):
total += 1
line = fp.readline()
assert total == 69
|
55dad0e3e2d982533beaddc6a6034b09737aa893 | celestialized/Machine-Learning | /Part 1 - Data Preprocessing/data preprocessing_missing_spliting_categorical_scaling_pythin.txt | 2,684 | 3.625 | 4 | #data preprocessing
"""
Spyder Editor
This is a temporary script file.
"""
import numpy
import matplotlib.pyplot
import pandas
dataset = pandas.read_csv('Data.csv')
x= dataset.iloc[:,:-1].values #.iloc[] is primarily integer position based selection
y= dataset.iloc[:,3].values
x= dataset.iloc[:,:-1].values
#take care of missing data
#it is better replace missing data by means or medion or friquent data ..removing causes information loss
from sklearn.preprocessing import Imputer # importing library
imputer= Imputer(missing_values = 'NaN', strategy='mean', axis=0) # axis 1(row), 0(column)..here column fitting is better at missing position
imputer = imputer.fit(x[:,1:3]) #fitting missing value by means columnwise
x[:,1:3]= imputer.transform(x[:,1:3]) #transform data by means of that column
# catogerical data
#two column contain categorical data which contain category
#here we will convvert categorical varaible into number
from sklearn.preprocessing import LabelEncoder, OneHotEncoder #library import LabelEncoder(use for encoding categorical variable in one column), OneHotEncoder use for convert different categorivcal into different column
labelencoder_x = LabelEncoder() #call LabelEncoder class
x[:,0]=labelencoder_x.fit_transform(x[:,0]) #fit_transform method , we can not compart 0,1,2 as one is greater then other because there are categorical variable
onehotencoder= OneHotEncoder(categorical_features = [0]) #calling OneHotEncoder
x= onehotencoder.fit_transform(x).toarray() # for independent variable
labelencoder_y = LabelEncoder() #since it is dependent variable having one column , python encode it as 0,1
y =labelencoder_y.fit_transform(y) #for dependent variable
# Splitting the Dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
x_train,x_test,y_train,y_test= train_test_split(x,y, test_size=0.3, random_state=0)
#feature scale scaling
#machine learning depend upon eucleian distance so there must bbe scaling between different variabel(age,,salary)
from sklearn.preprocessing import StandardScaler
sc_x= StandardScaler() #(standardization, normalization) method
x_train= sc_x.fit_transform(x_train)# first fit in above function then transform it
x_test= sc_x.transform(x_test)
#scaling dummy variiable depend , what type of data we have, we can scale dummy variable in order to increase accuracy but they can loose there identities.
# scaling will be in between -1 to +1.
#some time we use scaling in decision tree also although it's not based upon eucleian distance
#dependent variable if is in categorical variable then , no need to apply scaling but if not then we can apply
|
34ad0d747fbd3544130ffc39f6b01057937eadc0 | SneakBug8/Python-tasks | /num2.py | 277 | 3.65625 | 4 | x1=float(input())
y1=float(input())
x2=float(input())
y2=float(input())
x=float(input())
y=float(input())
res=""
if (y>y1) and (y>y2):
res=res+"N"
if (y<y1) and (y<y2):
res=res+"S"
if (x<x1) and (x<x2):
res=res+"W"
if (x>x1) and (x>x2):
res=res+"E"
print (res)
|
b89c831ce9f4a4e87f68b334f770b687e434a88d | yuzuponikemi/project_euler | /p32.py | 1,335 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 02:18:04 2018
@author: fiction
p32
We shall say that an n-digit number is pandigital if it makes use of all
the digits 1 to n exactly once; for example, the 5-digit number, 15234,
is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 ร 186 = 7254,
containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product
identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure
to only include it once in your sum.
"""
from itertools import permutations
perms = ["".join(p) for p in permutations('123456789')]
ansset=set()
for perm in perms:
for kakeru in range(1,8):
for equ in range(kakeru+1,9):
a = int(perm[:kakeru])
b = int(perm[kakeru:equ])
c = int(perm[equ:])
if a*b==c:
ansset.add(c)
print(sum(ansset))
#def pandigitalcheck(s):
# numlist = range(1,10)
# for num in s:
# if int(num) in numlist:
# numlist.remove(int(num))
# if numlist == []:
# return True
# else:
# return False |
501eafb185dafd832d185e7d533a151ee217712f | 1949commander/training_apps | /testArray.py | 200 | 3.625 | 4 |
carMakes = ["Dodge", "Studebaker", "Packard", "Mercury", "Nash"]
for x in carMakes:
print(x)
carMakes.append("Nash")
y = carMakes.count("Nash")
print(y)
carMakes.sort()
print(carMakes)
|
50021fe072c5789e91ec0afc99913b536010b5fd | rowaishanna/Intro-Python-II | /src/player.py | 1,035 | 3.9375 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room):
self.name = name
self.current_room = current_room
# day two code
self.inventory = []
def __str__(self):
items = []
for item in self.inventory:
items.append(item.name) # prints out the objects name instead of the object
return f"Player: {self.name}, Current Room: {self.current_room}, Inventory: {items}"
def __repr__(self):
return f"Name: {self.name}, Current Room: {self.current_room}"
# day two code
def grab(self, item):
self.inventory.append(item)
def drop(self, item):
self.inventory.remove(item)
'''# test code
from item import Item
flashlight = Item('Flashlight')
player = Player('Ace', 'Office', inventory=[flashlight])
phone = Item('Phone')
backpack = Item('Backpack')
player.grab(phone)
player.grab(backpack)
print(player)
player.drop(phone)
print(player)
''' |
3e20cb941aa1fc3e9238cbc25ee267651c3c56d8 | kedar-shenoy9/PIP-1BM17CS041 | /Third-lab/2a_search.py | 147 | 3.765625 | 4 | def search(arr, n):
return n in arr
l = list(map(int, input("Enter the list ").split()))
n = int(input("Enter the number "))
print(search(l, n))
|
911762c29e544ff29dd1504772802d294eb3a8e7 | Ran-oops/python_notes2 | /9/่ฎค่ฏ็ฌ่ซ-่ฏพไปถ-v1/Py็ฌ่ซ่ฏพไปถ/1-09็ฌ่ซไปฃ็ /spider_day6/2.bs4_demo.py | 2,316 | 3.8125 | 4 | from bs4 import BeautifulSoup
import re
html = """
<html><head><title><p>The Dormouse's <br> story</p></title></head>
<body>
<p class="title" name="dromouse" id="p1"><b class="title">The Dormouse's story</b></p>
<p class="story1">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister1" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister2" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister3" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
# ๆ ผๅผๅ็html
html = BeautifulSoup(html,'lxml')
# print(html.prettify())
# print(html.title) # ่ฟๅไธไธชbs4ๅฏน่ฑก๏ผไธไธชๆ ็ญพ
# print(html.title.name)
# print(html.title.string) # ่ฟๅbs4ๅฏน่ฑก
# print(html.title.text) # ่ฟๅๅญ็ฌฆไธฒ
# print(html.p.text) # ่ฟๅ็ฌฌไธไธชๆ ็ญพ
# print(html.p.attrs) # ่ทๅไธไธชๆ ็ญพๆๆๅฑๆง
# print(html.p['name']) # ่ทๅๅไธชๅฑๆง
tags = html.body.contents #่ฟๅๆๆๅญ่็น ็ฑปๅๅ่กจ
tags = html.body.children # ่ฟๅๆๆๅญ่็น ็ฑปๅ ่ฟญไปฃๅจ
# for tag in tags:
# print(tag)
# ่ทๅๆๆๅญๅญ่็น
# for tag in html.body.descendants:
# print(tag)
# res = html.find_all('p') # ่ทๅๆๆpๆ ็ญพ
# res = html.find_all(re.compile(r'^b')) # ๆฏๆๆญฃๅๅน้
ๆ ็ญพ
# ๆ็
งๅฑๆง่ฟๆปคๆ ็ญพ
# res = html.find_all('p',attrs={'name' : 'dromouse' ,'id' : 'p1'})
# res = html.find_all(['p','b'],attrs={'class': 'story'}) # ๆๆp ๆ ็ญพๅbๆ ็ญพ
# for a in res[0].find_all('a'):
# print(a.text)
# ้ๅบๆๆclass=title็pๆ ็ญพ
# res = html.select('p.title')
# res = html.select('p .title') # pๆ ็ญพไธ็class=title็ๆ ็ญพ
# res = html.select('#p1')
# res = html.select('head > p') # ๅฏปๆพhead ไธ็ ๅญ่็น
# res = html.select('head p') # ๅฏปๆพheadไธ็ ๆๆๅญๅญ่็น
# res = html.select('p#p1 , p.story') # ๆ่
็ๅ
ณ็ณป
# res = html.select('p#p1 , p.story') # ๆ่
็ๅ
ณ็ณป
# res = html.select('a[class="sister"]')
# res = html.select('a[class]') # ็ญ้ๆๆๅ
ๅซclass็aๆ ็ญพ
# res = html.select('a[class*="sister"]') # ๆจก็ณๆฅ่ฏข
# res = html.select('a[class^="sister"]') # sisterๅผๅคด็
# res = html.select('a[class$="sister"]') # sister็ปๅฐพ็
#print() |
4a5fc30ac43c0f01ff80833787154dd2abf94c62 | haoxuez/python | /pythonxiangmu/study.py | 1,387 | 3.859375 | 4 | print('ๅฅฝๅ้่ฎฏๅฝ๏ผ')
a={'ๅฐๆ':(1,'ๅนฟๅท'),'ๅฐ็บข':('002','ๆทฑๅณ'),'ๅฐ็':('003','ๅไบฌ')}
print(a)
x="""""
่ฏท่พๅ
ฅๆฐๅญๅฏนๅฅฝๅ้่ฎฏๅฝ่ฟ่กๅขๅ ๆนๆฅๆไฝ๏ผ
่ฏท่พๅ
ฅๆฐๅญ1่ฟ่กๅฅฝๅๆทปๅ ๏ผ
่พๅ
ฅๆฐๅญ2ๅ ้คๅฅฝๅ๏ผ
่พๅ
ฅๆฐๅญ3ไฟฎๆนๅฅฝๅ๏ผ
่พๅ
ฅๆฐๅญ4ๆฅ่ฏขๅฅฝๅ๏ผ
"""""
print(x)
while True:
b=int(input())
if b==1:
b1=input('่ฏท่พๅ
ฅๅฅฝๅ็ๅงๅ๏ผ็ต่ฏ๏ผๅฐๅ๏ผ๏ผไปฅ้ๅท้ๅผ๏ผ\n')
b2=tuple(b1.split(',',2))
a[b2[0]]=b2[1:3]
print('ไฝ ่ฆๆทปๅ ็ไฟกๆฏๆฏ๏ผ',b2,'\n',a)
continue
elif b==2:
b3=input('่ฏท่พๅ
ฅ่ฆๅ ้ค็ๅฅฝๅๅงๅ๏ผ\n')
del a[b3]
elif b==2:
b3=input('่ฏท่พๅ
ฅ่ฆๅ ้ค็ๅฅฝๅๅงๅ๏ผ\n')
del a[b3]
print('ไฝ ่ฆๅ ้ค็ๆๅๆฏ๏ผ',b3,'\n',a)
continue
elif b==3:
b4=input('่ฏท่พๅ
ฅ้่ฆไฟฎๆน็ๅฅฝๅๅงๅ๏ผ็ต่ฏ๏ผๅฐๅ๏ผ\n')
b5=tuple(b4.split(',',2))
a[b5[0]]=b5[1:3]
print('ไฝ ่ฆๆดๆฐ็ไฟกๆฏๆฏ๏ผ',b5,'\n',a)
continue
elif b==4:
b6=input('่ฏท่พๅ
ฅๆฅ่ฏข็ๅฅฝๅ็ๅงๅ๏ผ\n')
b7=a.get(b6)
print(b6,'็็ต่ฏๅๅฐๅๆฏ๏ผ',b7)
continue
elif b==0:
print('ๅ่ง')
break
else:
print('ไฝ ็่พๅ
ฅ้่ฏฏ๏ผ่ฏท้ๆฐ่พๅ
ฅ๏ผ')
continue
|
1fa5d7b7f8616053be154a211554615630da7cab | sadhanabhandari/learn_python_hard_way | /weekend_assignments/ex4.py | 335 | 4.125 | 4 | #With a given list With a given list [12,24,35,24,88,120,155,88,120,155]
# write a program to print this list after removing all duplicate values with original order reserved.
given_list=[12,24,35,24,88,120,155,88,120,155]
new_list=[]
for i in given_list:
if i not in new_list:
new_list.append(i)
print new_list[::-1]
|
d8cb71cc11faa6e20f10b70063b4d56baca4ba03 | JobCollins/NanoDSA | /UnscrambleCS/Task1.py | 975 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
# def test(uniq):
# symmetric_diff = set([list(line)[0] for line in texts]).symmetric_difference(set([list(line)[0] for line in calls]))
# common_vals = set([list(line)[0] for line in texts]).intersection(set([list(line)[0] for line in calls]))
# assert len(symmetric_diff)+len(common_vals) == len(uniq)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
unique_numbers = set([list(line)[0] for line in texts]).union(set([list(line)[0] for line in calls]))
print("There are {} different telephone numbers in the records.".format(len(unique_numbers)))
# test(unique_numbers) |
93e4b0a6c135f88b825aa9e689d0591ad8bf9969 | shreyasabharwal/Data-Structures-and-Algorithms | /LinkedList/2.5SumLists.py | 3,349 | 3.890625 | 4 | ''' 2.5 Sum Lists: You have two numbers represented by a linked list, where each node contains a single
digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a
function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (7-> 1 -> 6) + (5 -> 9 -> 2) .Thatis, 617 + 295.
Output: 2 - > 1 - > 9. That is, 912.
FOLLOW UP
Suppose the digits are stored in forward order. Repeat the above problem.
Input: (6 -> 1 -> 7) + (2 -> 9 -> 5).Thatis, 617 + 295.
Output: 9 - > 1 - > 2. That is, 912.
'''
from NodeInsertion import Node, LinkedList
def length(current):
"Return length of linked list"
count = 0
while current:
count += 1
current = current.next
return count
def sumList(l1, l2, carry):
'Sum the linked list with digits stored in reverse order'
# Base case
if not l1 and not l2 and carry == 0:
return None
value = carry
if l1:
value += l1.data
if l2:
value += l2.data
# calculate carry over for next node
carry = value//10
# calculate data of the node
value = value % 10
sumNode = Node(value)
if l1 and l2:
nextNode = sumList(l1.next if l1 else None,
l2.next if l2 else None, carry)
sumNode.next = nextNode
return sumNode
def padZeros(ll, num_of_zeros):
'Pad linked list with number of zeros specified'
for i in range(num_of_zeros):
zeroNode = Node(0)
zeroNode.next = ll
ll = zeroNode
return ll
def callRecSumList(l1, l2, carry=0):
sumNode = Node()
if l1.next and l2.next:
sumNode.next, carry = callRecSumList(l1.next, l2.next)
value = carry
if l1:
value += l1.data
if l2:
value += l2.data
carry = value//10
#print(value, ',', carry, '\n')
value = value % 10
sumNode.data = value
return sumNode, carry
def sumListFwd(l1, l2):
'Sum the linked list with digits stored in forward order'
# if lengths are not equal, pad the smaller one with zeros
num_of_zeros = length(l1)-length(l2)
if num_of_zeros > 0:
# pad l2 with zeros
l2 = padZeros(l2, abs(num_of_zeros))
elif num_of_zeros < 0:
# pad l1 with zeros
l1 = padZeros(l1, abs(num_of_zeros))
node, carry = callRecSumList(l1, l2, carry=0)
node.data += carry
return node
if __name__ == "__main__":
# Creating nodes
node1 = Node(7)
node2 = Node(1)
node3 = Node(6)
node4 = Node(5)
node5 = Node(9)
node6 = Node(2)
node7 = Node(1)
node1.next = node2
node2.next = node3
node4.next = node5
node5.next = node6
node6.next = node7
# Creating 1st Linkedlist
l1 = LinkedList(node1)
# Creating 2nd Linkedlist
l2 = LinkedList(node4)
print("Digits store in reverse order")
l1.printElements()
print('+')
l2.printElements()
sumNode = sumList(l1.head, l2.head, 0)
ll = LinkedList(sumNode)
print('=')
ll.printElements()
print("\nDigits store in forward order")
l1.printElements()
print('+')
l2.printElements()
sumNode1 = sumListFwd(l1.head, l2.head)
ll1 = LinkedList(sumNode1)
print('=')
ll1.printElements()
|
adb32b7df8222a454606487870eac46753d13d4e | buptwxd2/leetcode | /Round_1/191. Number of 1 Bits/solution_2.py | 459 | 3.65625 | 4 | # naive solution
class Solution:
def hammingWeight(self, n: int) -> int:
num_bits = 0
mask = 1
for _ in range(32):
if (n & mask) != 0:
num_bits += 1
mask = mask << 1
return num_bits
"""
Results:
Runtime: 24 ms, faster than 92.07% of Python3 online submissions for Number of 1 Bits.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Number of 1 Bits.
""" |
115b82c08d69c9dba28635dad1d5de4563578b3d | viethien/misc | /random_x.py | 389 | 3.8125 | 4 | #!/usr/bin/python3
# Will keep print lines of x where each line contains random characters of x from 5 to 19 inclusive until a line is printed with 16 or more characters
from random import randint
def main():
rand_x()
def rand_x():
stringSize = 0
while (stringSize < 16):
stringSize = randint(5,19)
output = "x" * stringSize
print(output)
main()
|
c049d8e6f20dcd6e18f3da8b8aedd2cd8ef42790 | atnsf/Problems | /excercise_005/excercise_005.py | 213 | 4.03125 | 4 | # excercise_005
arr1 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
arr3 = []
for index in arr1:
if index in arr2 and index not in arr1:
arr3.append(inndex)
print(arr3) |
c8b4dda3508e2ef3427578205e366c8a41fca139 | chetanpachpohe/Bookyourmovie_Project | /main.py | 651 | 3.796875 | 4 | from book import Movie
global row
global seats
row=int(input("Enter the number of rows: "))
seats=int(input("Enter the number of seats in each row: "))
while True:
print("*** Welcome to Bookyourmovies ***")
catlog=input("1. show seats\n2. Buy tickets\n3. view statistics\n4. show booked tickets customer info\n0.exit\n\n")
obj=Movie()
if catlog == "1":
obj.show_seats(row,seats)
elif catlog == "2":
obj.buy_tickets(row,seats)
elif catlog == "3":
obj.show_statistics(row,seats)
elif catlog =="4":
obj.show_booked_tickets()
elif catlog == "0":
break
|
3dc1026bd3c5dd6da05dad74d8531fa0c2cadc0e | ojhaanshu87/LeetCode | /249_group_string_shift.py | 865 | 4.21875 | 4 | '''
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of non-empty strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
Example:
Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
'''
class Solution(object):
def groupStrings(self, strings):
res = collections.defaultdict(list)
for s in strings:
code = ''
for i in range(1, len(s)):
x = ord(s[i]) - ord(s[i-1])
if x < 0:
x += 26
code += str(x)
res[code] += [s]
return res.values()
|
4975171e2af8e32688bb9d170855b37e9af1df2d | NikBomb/2021-strategy-parameters | /exchange.py | 1,864 | 4.0625 | 4 | """
Simple module that simulates an exchange.
"""
class ExchangeConnectionError(Exception):
"""Custom error that is raised when an exchange is not connected."""
class Exchange:
"""Basic exchange simulator."""
def __init__(self) -> None:
self.connected = False
def connect(self) -> None:
"""Connect to the exchange."""
print("Connecting to Crypto exchange...")
self.connected = True
def check_connection(self) -> None:
"""Check if the exchange is connected."""
if not self.connected:
raise ExchangeConnectionError()
def get_market_data(self, symbol: str) -> list[float]:
"""Return fake market price data for a given market symbol."""
self.check_connection()
price_data = {
"BTC/USD": [
35842.0,
34069.0,
33871.0,
34209.0,
32917.0,
33931.0,
33370.0,
34445.0,
32901.0,
33013.0,
],
"ETH/USD": [
2381.0,
2233.0,
2300.0,
2342.0,
2137.0,
2156.0,
2103.0,
2165.0,
2028.0,
2004.0,
],
}
return price_data[symbol]
def buy(self, symbol: str, amount: float) -> None:
"""Simulate buying an amount of a given symbol at the current price."""
self.check_connection()
print(f"Buying amount {amount} in market {symbol}.")
def sell(self, symbol: str, amount: float) -> None:
"""Simulate selling an amount of a given symbol at the current price."""
self.check_connection()
print(f"Selling amount {amount} in market {symbol}.")
|
d9da9874a3bde340dd32f1798cb31fcf7c976741 | RowiSinghPXL/IT-Essentials | /6_strings/opgave3.py | 229 | 3.59375 | 4 | zin_1 = input("Zin1: ")
zin_2 = input("Zin2: ")
if len(zin_1) < len(zin_2):
kleinste = len(zin_1)
else:
kleinste = len(zin_2)
for i in range(kleinste):
if zin_2[i] == zin_1[i]:
print(zin_1[i], "op index", i) |
8a59c5107818e9b0408a051ef02ff07b4bf64c74 | awesometime/learn-git | /Data Structure and Algorithm/Data Structure/Tree/binary_heap.py | 4,884 | 3.5625 | 4 | # from pythonds.trees.binheap import BinHeap
#
# bh = BinHeap()
# bh.insert(5)
# bh.insert(7)
# bh.insert(3)
# bh.insert(11)
#
# print(bh.delMin())
#
# print(bh.delMin())
#
# print(bh.delMin())
#
# print(bh.delMin())
"""
ๅ ้กบๅบๅฑๆง:
1.ๆ ็ๆ นๆฏๆ ไธญ็ๆๅฐ(ๅคง)้กน ๆ น่็นๆฏๅญ่็นๅฐ(ๅคง)
2.ๆๅคง๏ผๆๅฐ๏ผๅ ๆฏไธๆฃตๆฏไธไธช่็น็้ฎๅผ้ฝๅคงไบ๏ผๅฐไบ๏ผๅ
ถๅญ่็น้ฎๅผ็ๆ ,ๅทฆๅณๅญ่็นๅคงๅฐๆฒกๆ้กบๅบ
3.็ถไธคๅญ่็น็ดขๅผๅๅซไธบ n ใ2n ใ2n+1
4.n = ๅถ่็นไธชๆฐ + ๅบฆๆฐไธบ1่็นไธชๆฐ + ๅบฆๆฐไธบ2่็นไธชๆฐ ,ไธๅบฆๆฐไธบ 1่็นไธชๆฐไธบ 0ๆ 1
ๅ ็ปๆๅฑๆง
alist [5 33 14 ]
currentSize 0 1 2 3 4 5 6 7 8 9 10
heapList 0 5 9 11 14 18 19 21 33 17 27
"""
# this heap takes key value pairs, we will assume that the keys are integers
class BinHeap(): # ๆญคๅค่ฎจ่ฎบๆ นๆฏ่็นๅฐ็ๅ
def __init__(self):
self.heapList = [0]
self.currentSize = 0 # ๅฏไปฅ็่งฃไธบ็ดขๅผ
def buildHeap(self, alist):
"""ไปไธไธชๅ่กจๅปบ็ซไธไธชๅ ็ๆนๆณ
ๆ่ทฏ:
ไปๆ ็ไธญ้ดi=len(alist)//2ๅผๅง๏ผๆฏๆฌก่ฐ็จpercDown(i)ๆนๆณ,ไฝฟๅญๅ ๆปก่ถณๅ ็ปๆ,i-1็ดๅฐๅไธ่ฟๅๅฐๆ น่็นใ
ไนๅฐฑๆฏไปๆๅไธไธช่็น[len(alist)ๅฏนๅบ็่็น]็็ถ่็น[i]ๅผๅง,
่ฟ็จpercDown(i)ๆนๆณ:ๅฆๆ iๅคงไบๅ
ถๅญ่็น,ๅฐiๅไธไบคๆข,็ดๅฐๆพๅฐๅ
ถๆญฃ็กฎ็ไฝ็ฝฎ
"""
# iไธบๆๅไธไธช่็น็็ถ่็น
i = len(alist) // 2 # ๅบๅทlen(list)ๅฏนๅบๆๅไธไธช่็น, len(alist)//2ๅณๆๅไธไธช่็น็็ถ่็น
self.currentSize = len(alist)
self.heapList = [0] + alist[:]
# print(len(self.heapList), i)
# ไปๆๅไธๅฑ(ๆ ๅญ่็น้ฃๅฑ)็ไธไธๅฑ(่ฟไธๅฑๅผๅงๆๅญ่็น)ๅผๅง่ตฐๅพช็ฏ,
# ่ตฐๅฎไธๆฌกๅพช็ฏๅไธ่พน็ๅฑๅทฒ็ปๆปก่ถณๅ ็ๅคงๅฐ้กบๅบ่ฆๆฑ,็ดๅฐๆ น่็นi=1
while (i > 0):
# print(self.heapList, i)
# ็ถ่็นไธๆๅฐๅญ่็นไบคๆข
self.percDown(i)
i = i - 1
# print(self.heapList, i)
def percUp(self, i):
"""ๅฐ้กถๅ :ๆฏ่พๆฐๆทปๅ ็่็นiไธๅ
ถ็ถ่็น๏ผๅฆๆๆฐๆทปๅ ็้กนiๅฐไบๅ
ถ็ถ่็น๏ผๅไธๅ
ถ็ถ่็นไบคๆข,ๅฑๅฑๅพไธใ
"""
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2
def insert(self, k):
"""ๆ่ทฏ:
1 ๅ
ๅฐk่ฟฝๅ ๅฐๅ่กจๆๅ
2 ้่ฟ percUp()ๆนๆณ:ๅฆๆkๆฏๅ
ถ็ถ่็นๅฐ,ๅไธไบคๆข,็ดๅฐๆพๅฐๆญฃ็กฎ็ไฝ็ฝฎ
"""
# kๅ
่ฟฝๅ ๅฐๅ่กจๆๅ
self.heapList.append(k)
self.currentSize = self.currentSize + 1
# ๆฏ่พๅ
ถ็ถ่็น ๅไธไบคๆข
self.percUp(self.currentSize)
def percDown(self, i):
"""ไผ ๅ
ฅ่็น i ๅ ๅ
ถๆๅฐๅญ่็นไบคๆข,็ฅ้็ดขๅผ่ถ็ ๅๆฐ -->ๆ น่็นๅบๅท i """
# ๆ น่็น*2 ไธบๅญ่็น
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
# ๅฐ้กถๅ : ๅฝๅ่็นไธๅ
ถๅญ่็นๅผๆฏ่พ,ๅฆๆๅคงๅไบคๆข
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def minChild(self, i):
"""ๅฏนไบไธไธช่็นi,่ฟๅๅ
ถๅญ่็น(2i,2i+1)ไธญๅผ่พๅฐ็้ฃไธชๅฏนๅบ็็ดขๅผ
"""
# ๆพๅฐๆๅฐ้กนๅฏนๅบ็็ดขๅผ
# (i * 2) <= self.currentSize ้ฃๆญฅ่ทณ่ฟๆฅ็,ๆไปฅไธ็จๆ
ๅฟ็ดขๅผ่ถ็
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i * 2] < self.heapList[i * 2 + 1]:
return i * 2
else:
return i * 2 + 1
def delMin(self):
"""
ๅ ้คๆๅฐ้กน,ๅฏนไบๅฐ้กถๅ ๅณๅ ้ค heapList[1],่ฟๅๅ
ถๅผ
ๆ่ทฏๆฏ:
1 ๅฐ heapList ๅ่กจๆๅไธ้กน็ๅผ่ต็ป็ฌฌไธ้กน
2 ไป heapListไธญ popๅบๆๅไธ้กน
3 ้่ฟ percDown(1)ๆนๆณ:ๅฆๆ็ฌฌไธ้กนๅคงไบๅ
ถๅญ่็น,ๅฐ็ฌฌไธ้กนๅไธไบคๆข็ดๅฐๆพๅฐๅ
ถๆญฃ็กฎ็ไฝ็ฝฎ
"""
# ๆ นไฝ็ฝฎๅณๆๅฐ้กน
retval = self.heapList[1]
# ่ทๅๅ่กจไธญ็ๆๅไธไธช้กนๅนถๅฐๅ
ถ็งปๅจๅฐๆ นไฝ็ฝฎๆฅๆขๅคๆ น้กน
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize = self.currentSize - 1
# ๆๅไธไธช้กนpopๅบๅป
self.heapList.pop()
# ็ฌฌไธ้กน ๆฏ่พๅ
ถๅญ่็น ๅไธไบคๆข
self.percDown(1)
return retval
def isEmpty(self):
if self.currentSize == 0:
return True
else:
return False
|
b5f9967782f0b81d836ae9de920fe5576c83ade9 | er-aditi/Learning-Python | /List Working Programs/List_Indenting Unnecessarily.py | 208 | 3.5 | 4 | magicians = ['david', 'aleen', 'tom']
for magician in magicians:
print("I Like to see magic: " + magician)
print("I am very Grateful to see: " + magician + "\n")
print("It is Best: " + magician) |
6fe61d45cdd4bd00bdb8b7a6dd574a322e19f70e | kedpak/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/100-weight_average.py | 271 | 3.6875 | 4 | #!/usr/bin/python3
def weight_average(my_list=[]):
if my_list is None or my_list == []:
return (0)
score = 0
weight = 0
for i, j in my_list:
score = score + i * j
weight = weight + j
average = score/weight
return (average)
|
090d943c4ddf3d3ae6b76ce165f6d2cb8d9e72cf | atshaya-anand/LeetCode-programs | /Easy/pathSum.py | 960 | 3.859375 | 4 | # https://leetcode.com/problems/path-sum/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
def pathsum(root, sum_, target, hassum):
if root == None:
return
sum_ += root.val
if root.left == None and root.right == None:
if sum_ == target:
hassum.append(True)
return
pathsum(root.left, sum_, target, hassum)
pathsum(root.right, sum_, target, hassum)
hassum = []
if root == None:
return False
pathsum(root, 0, targetSum, hassum)
if True in hassum:
return True
else:
return False |
6ced1797ded915215bc4082233910b3bbe9f9668 | t-yuhao/py | /ๆงๅถๆต/if.py | 271 | 3.96875 | 4 | # ็ๆฐๅญ
number = 37
guess = int(input('Enter an integer : '))
if number == guess:
print('congratulations,you gussed it.')
elif guess < number :
print('No ,it\'s a little higher than that.')
else:
print ('No, it is alittle lower than that')
print('done') |
4c2527ebaf713ab8804cc314e06596a37693d927 | StanislavBubnov/Python | /Lesson7/Hometask_7.1.py | 825 | 3.625 | 4 | class Matrix:
def __init__(self, my_list = []):
self.my_list = my_list
def __str__(self):
str_1 = ' '.join(str(e) for e in self.my_list[0])
str_2 = ' '.join(str(e) for e in self.my_list[1])
str_3 = ' '.join(str(e) for e in self.my_list[2])
return '|{}|\n|{}|\n|{}|'.format(str_1,str_2,str_3)
def __add__(self, other):
str_1 = [a + b for a, b in zip(self.my_list[0], other.my_list[0])]
str_2 = [a + b for a, b in zip(self.my_list[1], other.my_list[1])]
str_3 = [a + b for a, b in zip(self.my_list[2], other.my_list[2])]
return Matrix([str_1,str_2,str_3])
matrix_a = Matrix([[1,4,5],[6,7,9], [4,7,3]])
print(matrix_a)
print('~'*150)
matrix_b = Matrix([[7,-3,5],[2,-1,9], [2,-2,3]])
print(matrix_b)
print('~'*150)
print(matrix_a+matrix_b) |
62e6790d4fbb7536c1d18899e2d3a7afcae254ce | yichuanma95/leetcode-solns | /python3/twoSum.py | 1,815 | 3.9375 | 4 | '''
Problem 1. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such
that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the
same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
* 2 <= nums.length <= 105
* -109 <= nums[i] <= 109
* -109 <= target <= 109
* Only one valid answer exists.
'''
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
''' (Solution, list of ints, int) -> list of ints
Return the indices of two numbers in the given list such that those two numbers in
the list add up to the given target.
>>> soln = Solution()
>>> soln.twoSum([2, 7, 11, 15], 9)
[0, 1]
'''
# Set up a dictionary to store numbers and their respective indices in nums.
num_to_index = {}
# Loop through nums to find a pair of indices that refer to numbers in nums that add
# up to target.
length = len(nums)
for i in range(length):
num = nums[i]
diff_from_target = target - num
# If the difference between the current number and target is in num_to_index,
# a solution has been found.
if diff_from_target in num_to_index:
return [num_to_index[diff_from_target], i]
# Otherwise, add the current number and its index to num_to_index.
num_to_index[num] = i
|
94a2319431d5a1836af583129c04d896ed455287 | CompetitiveCode/hackerrank-python | /Practice/Numpy/Concatenate.py | 983 | 4 | 4 | #Answer to Concatenate
import numpy
n,m,p=input().split()
a,b=[],[]
for i in range(int(n)):
a.append(list(map(int,input().split())))
for i in range(int(m)):
b.append(list(map(int,input().split())))
a,b=numpy.array(a),numpy.array(b)
print(numpy.concatenate((a,b),axis=0))
"""
Concatenate
Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined:
import numpy
array_1 = numpy.array([1,2,3])
array_2 = numpy.array([4,5,6])
array_3 = numpy.array([7,8,9])
print numpy.concatenate((array_1, array_2, array_3))
#Output
[1 2 3 4 5 6 7 8 9]
If an array has more than one dimension, it is possible to specify the axis along which multiple arrays are concatenated. By default, it is along the first dimension.
import numpy
array_1 = numpy.array([[1,2,3],[0,0,0]])
array_2 = numpy.array([[0,0,0],[7,8,9]])
print numpy.concatenate((array_1, array_2), axis = 1)
#Output
[[1 2 3 0 0 0]
[0 0 0 7 8 9]]
""" |
4935489703e8f8b6de9d08a700a6dca89993defb | kdragonkorea/TIL | /Bigdata_analysis_course_20201228/2_Python/Python_exam/day3(20210106)/whileTest1.py | 465 | 3.71875 | 4 | student = 1
while student <= 5:
print(student, "๋ฒ ํ์์ ์ฑ์ ์ ์ฒ๋ฆฌํ๋ค.")
student += 1
print("์ํ์ข
๋ฃ")
# 2021-01-09 ๋ณต์ต
# ์๋์ ๊ฐ์ด ์ถ๋ ฅ๋๋ค.
# '1๋ฒ ํ์์ ์ฑ์ ์ ์ฒ๋ฆฌํ๋ค.'
# '2๋ฒ ํ์์ ์ฑ์ ์ ์ฒ๋ฆฌํ๋ค.'
# ...
# '5๋ฒ ํ์์ ์ฑ์ ์ ์ฒ๋ฆฌํ๋ค.' ๋ฅผ ์ถ๋ ฅํ๋ค.
# '์ํ์ข
๋ฃ'
for student in range(1, 6) :
print(student, "๋ฒ ํ์์ ์ฑ์ ์ ์ฒ๋ฆฌํ๋ค.")
print("์ํ์ข
๋ฃ") |
b4a2e3192b4732f68658d91688bd6ce449689efa | trimcao/intro-python-rice-university | /week-5/memory.py | 3,485 | 3.765625 | 4 |
"""
Name: Tri Minh Cao
Email: trimcao@gmail.com
Date: October 2015
implementation of card game - Memory
"""
import simplegui
import random
no_turn = 0
first_open = -1 # index of the card player opens first
second_open = -1 # index of the card player opens second
# initialize a deck of cards, with each card appearing twice
deck = range(8)
deck.extend(range(8))
# exposed list to represent a card is exposed (1) or not (0)
exposed = [0 for idx in range(len(deck))]
random.shuffle(deck)
#exposed[7] = 1
state = 0 # game has three states
# helper function to initialize globals
def new_game():
global exposed, deck, first_open, second_open, no_turn, state
deck = range(8)
deck.extend(range(8))
random.shuffle(deck)
exposed = [0 for idx in range(len(deck))]
no_turn = 0
first_open = -1
second_open = -1
state = 0
label.set_text("Turns = " + str(no_turn))
# define event handlers
def mouseclick(pos):
# add game state logic here
global state, no_turn, first_open, second_open
card_index = pos[0] // 50
if not (exposed[card_index] == 1):
#print "State: ", state
if (state == 0):
state = 1
exposed[card_index] = 1
first_open = card_index
elif (state == 1):
state = 2
no_turn += 1
exposed[card_index] = 1
second_open = card_index
elif (state == 2):
#print (first_open)
#print second_open
#print
# check if two recently exposed cards are the same
if (deck[first_open] == deck[second_open]):
exposed[first_open] = 1
exposed[second_open] = 1
else:
exposed[first_open] = 0
exposed[second_open] = 0
# reset second_open
second_open = -1
state = 1
#no_turn += 1
exposed[card_index] = 1
first_open = card_index
label.set_text("Turns = " + str(no_turn))
# cards are logically 50x100 pixels in size
def draw(canvas):
# draw the number associates with each card on canvas
#pos = [20, 50]
cover_pos = [0, 100]
for idx in range(len(deck)):
if (exposed[idx] == 1):
canvas.draw_polygon([cover_pos, (cover_pos[0] + 100, cover_pos[1]),
(cover_pos[0] + 100, cover_pos[1] - 100),
(cover_pos[0], cover_pos[1] - 100)],
2, 'Yellow', 'Black')
canvas.draw_text(str(deck[idx]), (cover_pos[0] + 20, cover_pos[1] - 40),
30, "Yellow")
else:
canvas.draw_polygon([cover_pos, (cover_pos[0] + 100, cover_pos[1]),
(cover_pos[0] + 100, cover_pos[1] - 100),
(cover_pos[0], cover_pos[1] - 100)],
2, 'Yellow', 'Green')
#pos[0] += 50
cover_pos[0] += 50
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = " + str(no_turn))
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
# Always remember to review the grading rubric
|
7633b1754d757f0f5c99617f7c1ad25464b3310b | mdaiyub/Codeforces | /1389A.py | 140 | 3.515625 | 4 | for _ in range(int(input())):
a,b = map(int,input().split())
if a*2 <= b:
print(a,a*2)
else:
print("-1 -1") |
74ab68d4b27c11034b666a4b0b5aee7db0c89822 | sfox1975/Udacity-I2P-Stage3 | /entertainment_center.py | 2,971 | 3.5625 | 4 | # Udacity Introdution to Programming Nanodegree
# Stage 3 Project: Movies Website
# By Stephen Fox (with heavy assistance from Udacity!)
# Movie storylines are courtesy of www.imdb.com
# import media tells the program to use the contents of media.py
import media
import fresh_tomatoes
# Media.Movie() implies the class Movie inside the file called media
# Each movie listed below is an instance of the class Movie
bourne_identity = media.Movie("The Bourne Identity",
"A man is picked up by a fishing boat, bullet-riddled and suffering from amnesia, before racing to elude assassins and regain his memory.",
"https://www.movieposter.com/posters/archive/main/106/MPW-53157",
"https://www.youtube.com/watch?v=cD-uQreIwEk")
hurt_locker = media.Movie("The Hurt Locker",
"During the Iraq War, a Sergeant recently assigned to an army bomb squad is put at odds with his squad mates due to his maverick way of handling his work.",
"http://www.impawards.com/2009/posters/hurt_locker.jpg",
"https://www.youtube.com/watch?v=2GxSDZc8etg")
no_country = media.Movie("No Country for Old Men",
"Violence and mayhem ensue after a hunter stumbles upon a drug deal gone wrong and more than two million dollars in cash near the Rio Grande.",
"https://upload.wikimedia.org/wikipedia/en/8/8b/No_Country_for_Old_Men_poster.jpg",
"https://www.youtube.com/watch?v=YBqmKSAHc6w")
platoon = media.Movie("Platoon",
"A young recruit in Vietnam faces a moral crisis when confronted with the horrors of war and the duality of man.",
"http://ecx.images-amazon.com/images/I/51GecejycjL._AC_UL320_SR228,320_.jpg",
"https://www.youtube.com/watch?v=hGsyEkfjhQk")
shawshank = media.Movie("The Shawshank Redemption",
"Two imprisoned men bond over a number of years, " +
"finding solace and eventual redemption through acts of common decency.",
"""https://www.movieposter.com/posters/archive/main/12/A70-6457""",
"https://www.youtube.com/watch?v=NmzuHjWmXOc")
lost_ark = media.Movie("Raiders of the Lost Ark",
"Archaeologist and adventurer Indiana Jones is hired by the US government to find the Ark of the Covenant before the Nazis.",
"https://www.movieposter.com/posters/archive/main/157/MPW-78987",
"https://www.youtube.com/watch?v=gz4crpFaW4M")
movies = [bourne_identity, hurt_locker, no_country, platoon, shawshank, lost_ark]
# open_movies_page is a function inside fresh_tomatoes.py that generates
# a website from the preceding list of movies (function input)
fresh_tomatoes.open_movies_page(movies)
|
181118291b209768b69767cfd1293294768ae3f8 | Man0j-kumar/python | /tup-dict.py | 107 | 4.125 | 4 | #Python program to convert a tuple to a dictionary
tup=((2,'w'),(3,'r'))
print(dict((x,y)for y,x in tup)) |
178e85c3f6c4652042c765568ff27a480417b307 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/ec6269b2b00444a2b493f8a9d756b49a.py | 812 | 3.8125 | 4 | RESPONSETO = {
'question': 'Sure.',
'shouting': 'Whoa, chill out!',
'nothing': 'Fine. Be that way!',
'other': 'Whatever.'
}
def main():
what_I_say = input('Say something to Bob:')
while not (what_I_say.lower() == 'exit'):
if (what_I_say.lower().startswith('exit') or
what_I_say.lower().startswith('quit')):
print('Type "exit" to leave Bob alone.')
else:
response = hey(what_I_say)
print(response)
what_I_say = input('Say something else to Bob:')
print('Whatever, bye.')
def hey(what_I_say):
if what_I_say.strip() == '':
return(RESPONSETO['nothing'])
elif what_I_say.isupper():
return(RESPONSETO['shouting'])
elif what_I_say.endswith('?'):
return(RESPONSETO['question'])
else:
return(RESPONSETO['other'])
if __name__ == '__main__':
main()
|
0083d2fa8e4fb448a2cc825b8cb3925850f6ce68 | Elena-Zhao/Leetcode-Practice | /LeetCode/Best_Time_to_Buy_and_Sell_Stock.py | 1,297 | 4 | 4 | # Say you have an array for which the ith element is the price of a given stock on day i.
#
# If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock),
# design an algorithm to find the maximum profit.
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# Not enough time to earn profit
if len(prices) < 2: return 0
# The maximum price from here to the end
maxFromHere = prices[-1]
# The maximum profit, we could earn.
# Could initialize it with any valid profit.
maxProfit = prices[1] - prices[0]
for index in xrange(len(prices)-2, -1, -1):
price = prices[index]
# The maximum profit, if we buy it here.
profit = maxFromHere - price
maxProfit = max(maxProfit, profit)
maxFromHere = max(maxFromHere, price)
# If maxProfit is negative, we would not take
# any transaction.
#
# If we initialize the maxProfit with 0, this
# step is not necessary.
maxProfit = max(0, maxProfit)
return maxProfit
s = Solution()
print s.maxProfit([1,2,3,65,2,5,6,87,1,34,57,78,34,342,22]) |
af3c4cea15a354c0014d421632e099fd2b212afa | gokul-raghuraman/algorithms | /rotate-left.py | 191 | 3.828125 | 4 | def rotateLeft(string, k):
n = len(string)
k = k % n
string = string[k:] + string[:k]
return string
if __name__ == "__main__":
k = 4
string = "ABCDEFGHIJ"
print(rotateLeft(string, k)) |
93614a460d42a63c94f857372b10a50954e83ad7 | JannaKim/PS | /GRAPH/review/2056_์์
_1125.py | 702 | 3.546875 | 4 | # ํ์ฌ ์์
์ ์ํด ํ์ํ ์ ๋ณด๊ฐ ์ด์ ์ ๋ชจ๋ ์ฃผ์ด์ง๋ฏ๋ก,
# ๋ฐ๋ก ์ฐ๊ฒฐ๋ผ์๋ ๋
ธ๋์ ์ต๋ ์๊ฐ๋ง ๊ฐ์ ธ์์ ์์ ๊ณผ ๋ํ๋ฉด ๋๋ค
N = int(input())
edge = [[]for _ in range(N+1)]
time = [0]*(N+1)
for i in range(1,N+1):
*L,=map(int, input().split())
time[i]=L[0]
for v2 in L[2:]:
edge[i].append(v2)
total = time[:]
total[1]=time[1]
for i in range(2,N+1):
for v2 in edge[i]:
total[i]=max(total[i], total[v2]+time[i])
print(max(total))
'''
7
5 0
1 1 1
3 1 2
6 1 1
1 2 2 4
8 2 2 4
4 3 3 5 6
'''
'''
In this problem,
The necessary info to define accum[v] is always perfectly defined before the attempt to define accum[v].
''' |
e98d1afa9218836cde50c13761aacaf26356b2da | Aasthaengg/IBMdataset | /Python_codes/p02862/s481582144.py | 1,032 | 3.59375 | 4 | import sys
from math import factorial
input = sys.stdin.readline
def log(*args):
print(*args, file=sys.stderr)
def main():
x, y = map(int, input().rstrip().split())
# ๅ
จ้จ i + 1, j + 2ใๆๅใ ใฃใใจใใ
# a + 2b = x, 2a + b = y
# =>
# a = x - 2b
# b = y - 2a
# =>
# b = y - 2x + 4b
# 3b = 2x - y
# b = (2x - y) / 3
# a = (2y - x) / 3
if (2 * x - y) % 3 != 0 or (2 * y - x) % 3 != 0:
print(0)
return
a = (2 * x - y) // 3
b = (2 * y - x) // 3
if a < 0 or b < 0:
print(0)
return
# (a + b) C min(a, b)
# => (a + b)! / (min(a, b) ! * (a + b - min(a, b)) !
mod = 10**9 + 7
ans = (factorial_mod(a + b, mod) * pow(factorial_mod(min(a, b), mod), mod - 2, mod)
* pow(factorial_mod(a + b - min(a, b), mod), mod - 2, mod)) % mod
print(ans)
def factorial_mod(a, mod):
ans = 1
for v in range(1, a + 1):
ans *= v
ans %= mod
return ans
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.