blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7b95a8588f581ec38cc1b50875b9b2c88c4691d7 | SIMELLI25/esercizi_python | /es34.py | 1,679 | 4.15625 | 4 | input("ES 34")
#Le prenotazioni per la partecipazione a un convegno sono memorizzate secondo l'ordine di arrivo. Scrivi un programma che comprenda due funzionalità
#- L'operazione per registrare i dati dei partecipanti;
#- L'operazione per visualizzare i nomi dei partecipanti a cui si deve inviare una lettera di conferma:
# si tratta dei nomi dell'elenco, eliminando quelli ai quali la lettera è già stata inviata e che sono registrati in un apposito elenco.
# La funzione che produce l'elenco deve anche aggiornare l'elenco dei partecipanti ai quali è già stata inviata la lettera
dict_part_orar = {}
list_orari = []
dict_def = {}
list_cas = [] # lista per eliminare gli elementi dal dizionario
while True:
print("Se i partecipanti sono terminati, inserisci STOP")
partecipante = input("Inserisci il nome del partecipante: ")
if partecipante == "STOP":
break
orario = input("Inserisci l'orario di arrivo: ")
dict_part_orar[orario] = partecipante
list_orari.append(orario)
list_orari.sort() # metto in ordine crescente gli orari di entrata
for i in list_orari:
dict_def[i] = dict_part_orar[i]
print("Elenco in ordine di arrivo:")
for j in dict_def:
print("ore", j, ":", dict_def[j])
for d in dict_def:
print(dict_def[d], "entrato alle ore", d)
conferma = input("La letterea di conferma è già stata inviata? ")
if conferma == "si" or conferma == "SI":
list_cas.append(d)
for q in list_cas:
del dict_def[q] # elimino dal dizionario dict_def chi ha già avuto la lettera di conferma
print("I partecipanti ai quali va data la lettera di conferma sono i seguenti: ")
for u in dict_def:
print(dict_def[u]) | false |
381b57be748331cf095cef78336c4f31b780da43 | Talleyman/Test-list-generator | /TestListGeneratorV1-1.py | 1,344 | 4.25 | 4 | #!/usr/bin/python
#Stephen Talley
#Date: July 11, 2014
#Program for generating random ranked lists
import random
import csv
import doctest
#This declaration creates a two-dimensional list i.e. a list of lists (the number of lists varies up to 100)
Listoflists=[[] for _ in range(random.randrange(100))]
#ListCreator function establishes an ordered list of a random length
def ListCreator(list1):
for number in range(0,random.randint(25,100)):
list1.append(number)
'''ListShuffle takes the ordered list from ListCreator
and shuffles the order to simulate a ranked list'''
def ListShuffle(list1):
"""
>>> random.seed(10)
>>> list2=[1,2,3,4]
>>> random.shuffle(list2)
>>>list2
[1, 4, 2, 3]
"""
random.shuffle(list1)
def main():
"""
>>> random.seed(10)
>>> Randomlist=[[] for _ in range(random.randrange(5))]
>>> Randomlist
[[], []]
"""
outfile=open('TestLists.csv','wt')
writer=csv.writer(outfile,lineterminator='\n')
for element in Listoflists:
ListCreator(element)
ListShuffle(element)
writer.writerow(element)#This command writes each list to the .csv file TestLists
print(Listoflists)#Prints the entire two-dimensional list to verify that everything worked correctly
outfile.close()
if __name__ == "__main__":
main()
| true |
e12892267cb47dfa68507b4caec7008743e39231 | Alb4tr02/holbertonschool-machine_learning | /math/0x00-linear_algebra/2-size_me_please.py | 365 | 4.125 | 4 | #!/usr/bin/env python3
"""function def matrix_shape(matrix): returns the shape of a matrix:"""
def matrix_shape(matrix=None):
"""INPUT: a matrix
OUTPUT: the shape of the given matrix
"""
shape = []
aux = matrix
while matrix is not None and type(aux) == type(matrix):
shape.append(len(aux))
aux = aux[0]
return shape
| true |
76e79bf0976170c8a9087ab269fe47df156476f2 | DeeMATT/PythonExercises | /park_ride.py | 1,770 | 4.40625 | 4 | """
A program for park users of all ages to select a ride of choice
"""
available_rides = {'1': "Scenic River Cruise", '2': "Carnival Carousel",
'3': "Jungle Adventure Water Splash",
'4': "Downhill Mountain Run",
'5': "The Regurgitator", }
print("Welcome to our Theme Park", "\n\nThese are the available rides:\n")
# A loop to display the available rides
for numb, ride in available_rides.items():
print(numb + '.' + ride)
# Ask the user's choice of ride and age
selected_num = int(input("\nPlease enter the ride number you want: "))
age = int(input("Kindly enter your age real age in numbers"))
eligibility = "You are eligible to take this ride"
permit = "Go on and enjoy your ride"
denial = "Sorry, you are ineligible to take this ride"
if selected_num == 1:
print("You have selected the " + available_rides['1'])
print("There are no age limits for this ride")
print(permit)
elif selected_num == 2:
print("You have selected the " + available_rides['2'])
if age >= 3:
print(eligibility)
print(permit)
else:
print(denial)
elif selected_num == 3:
print("You have selected the " + available_rides['3'])
if age >= 6:
print(eligibility)
print(permit)
else:
print(denial)
elif selected_num == 4:
print("You have selected the " + available_rides['4'])
if age >= 12:
print(eligibility)
print(permit)
else:
print(denial)
elif selected_num == 5:
print("You have selected the " + available_rides['5'])
if age >= 12 or age < 70:
print(eligibility)
print(permit)
else:
print(denial)
| true |
5a3f793f5db44a632508b7ef9b8b4448d65c0944 | jcclarke/learnpythonthehardwayJC | /python2/exercise15/ex15.py | 506 | 4.4375 | 4 | #!/usr/bin/env python2
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the file name again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
# NOTE
# You can run "python 2.7" in the terminal to get a python terminal.
# There you can run the following just like in this exercise.
# file = "blah"
# text = open(file)
# text.read()
# It will execute like running this file
| true |
3d3e594708c6121e03611aa3a011bb580dc2f59e | jcclarke/learnpythonthehardwayJC | /python3/exercise15/ex15.py | 508 | 4.46875 | 4 | #!/usr/bin/env python3
from sys import argv
script, filename = argv
txt = open(filename)
print (f"Here's your file {filename}")
print (txt.read())
print ("Type the file name again:")
file_again = input("> ")
txt_again = open(file_again)
print (txt_again.read())
# NOTE
# You can run "python 3.6" in the terminal to get a python terminal.
# There you can run the following just like in this exercise.
# file = "blah"
# text = open(file)
# text.read()
# It will execute like running this file.
| true |
c27554e7a83f20a5ab5b1dc729e110640e16254f | cvhs-cs-2017/practice-exam-LeoCWang | /Loops.py | 310 | 4.1875 | 4 | """Use a loop to make a turtle draw a shape that is has at least 100 sides and
that shows symmetry. The entire shape must fit inside the screen"""
import turtle
sven = turtle.Turtle()
def hectagon():
sven.speed(0)
for i in range(100):
sven.fd(10)
sven.left(3.6)
input()
hectagon()
| true |
60d6c96bd3f2d9223c7905bb3932820be07a857d | younkyounghwan/python_class | /lab5_8.py | 412 | 4.21875 | 4 | """
쳅터: day 5
주제: 함수
문제:
작성자: 윤경환
작성일: 18 10 04
"""
#매대변수의 수정 여부 확인을 위한 하수 정의
#call-by-value 방식으로 매개변수 값을 전달
#매개변수 값을 복사(copy)하여 전달
def modify(s):
s+=" to you"
return s
msg = "Happy Birthday"
print("호출 전 msg =",msg)
re=modify(msg)
print("호출 후 msg =",msg)
print("re=",re) | false |
16014b857535a0016ab74b31beb8f333a16bbbaf | alexlouden/tetris-ai | /fileops.py | 1,262 | 4.15625 | 4 | #-------------------------------------------------------------------------
# Name: Tetris File Operations
# Purpose: Functions to read and write to disk
#
# Version: Python 2.7
#
# Author: Alex Louden
#
# Created: 28/04/2013
# Copyright: (c) Alex Louden 2013
# Licence: MIT
#-------------------------------------------------------------------------
from shapeops import valid_shape_id
def read_input_file(filename):
"""Read input file and populate a list of recognised pieces."""
# An empty list to contain our input numbers
numbers = []
# Open input file in read only mode
with open(filename, 'r') as f:
# Iterate through each line in the file
for line in f:
# Use list comprehension to filter only character digits
# Then convert each character to an integer
digitsonly = [int(char) for char in line if char.isdigit()]
# Strip out zeros
nozeros = [i for i in digitsonly if valid_shape_id(i)]
# And add these numbers to the list
numbers.extend(nozeros)
return numbers
def write_output_file(filename, output):
# Open output file in write mode
with open(filename, 'wb') as f:
f.write(output)
| true |
65d525337644b19c4eac0260d06f40205390865c | swap9047/Machine-Learning-by-Andrew-Ng-Coursera | /exercise_2/ex2.py | 2,978 | 4.125 | 4 | """
Machine Learning Online Class - Exercise 2: Logistic Regression
"""
## Initialization
import pandas as pd
import numpy as np
from scipy.optimize import minimize
from ex2_utils import *
## Load Data
# The first two columns contains the exam scores and the third column
# contains the label.
data = pd.read_csv('ex2data1.txt', names=['x1','x2','y'])
X = np.asarray(data[["x1","x2"]])
y = np.asarray(data["y"])
## ==================== Part 1: Plotting ====================
# We start the exercise by first plotting the data to understand the
# the problem we are working with.
print("Plotting data with + indicating (y = 1) examples and o indicating",
" (y =0) examples.")
fig, ax = plotData(X, y)
# Specified in plot order
ax.legend(['Admitted', 'Not admitted'])
fig.show()
input('\nProgram paused. Press enter to continue.\n')
## ============ Part 2: Compute Cost and Gradient ============
# In this part of the exercise, you will implement the cost and gradient
# for logistic regression. You neeed to complete the code in
# costFunction.m
# Setup the data matrix appropriately, and add ones for the intercept term
# Add intercept term to x and X_test
X = np.hstack((np.ones_like(y)[:,None],X))
# Initialize fitting parameters
initial_theta = np.zeros(3)
# Compute and display initial cost and gradient
cost, grad = costFunction(initial_theta, X, y)
print('Cost at initial theta (zeros): \n', cost)
print('Gradient at initial theta (zeros): \n',grad)
input('\nProgram paused. Press enter to continue.')
## ============= Part 3: Optimizing using fminunc =============
# In this exercise, you will use a built-in function (fminunc) to find the
# optimal parameters theta.
res = minimize(costFunction,
initial_theta,
method='Newton-CG',
args=(X,y),
jac=True,
options={'maxiter':400,
'disp':True})
theta = res.x
# Print theta to screen
print('Cost at theta found by minimize: \n', res.fun)
print('theta: \n', theta)
# Plot Boundary
plotDecisionBoundary(theta, X, y)
input('\nProgram paused. Press enter to continue.\n')
## ============== Part 4: Predict and Accuracies ==============
# After learning the parameters, you'll like to use it to predict the outcomes
# on unseen data. In this part, you will use the logistic regression model
# to predict the probability that a student with score 45 on exam 1 and
# score 85 on exam 2 will be admitted.
#
# Furthermore, you will compute the training and test set accuracies of
# our model.
#
# Your task is to complete the code in predict.m
# Predict probability for a student with score 45 on exam 1
# and score 85 on exam 2
prob = sigmoid(np.dot([1,45,85],theta))
print('For a student with scores 45 and 85, we predict an ',
'admission probability of ', prob)
# Compute accuracy on our training set
p = predict(theta, X)
print('Train Accuracy: \n', np.mean(p==y)*100)
input('Program paused. Press enter to continue.\n')
| true |
b9be744e56c2b91c70b1da3ceda69023022ba57d | mahajany/Python | /05_for_loop_1.py | 422 | 4.5625 | 5 | # Example 'for' loop
# First, create a list to loop through:
newList = [45, 'eat me', 90210, "The day has come, the walrus said, \
to speak of many things", -67]
print ("newList[]", newList)
# create the loop:
# Goes through newList, and seqentially puts each bit of information
# into the variable value, and runs the loop
print ("List elements, through for loop:")
for value in newList:
print ( value )
| true |
b2955d88653469995e6e438ef683425e4d783e5a | moshix/mvs | /hanukkah.py | 922 | 4.34375 | 4 | from datetime import datetime
from calendar import monthrange
def hanukkah_dates(year):
# Calculate the date of Hanukkah for the given year
# Hanukkah always falls on the 25th day of the Jewish month of Kislev
# and the Jewish calendar is based on lunar cycles
a = (year * 12 + 17) % 19
b = (year - 1) // 100
c = (year - 1) % 100
d = b // 4
e = b % 4
f = (b + 8) // 25
g = (b - f + 1) // 3
h = (19 * a + b - d - g + 15) % 30
i = c // 4
k = c % 4
l = (32 + 2 * e + 2 * i - h - k) % 7
m = (a + 11 * h + 22 * l) // 451
month = (h + l - 7 * m + 114) // 31
day = ((h + l - 7 * m + 114) % 31) + 1
# Return the date as a string in the format "Month Day, Year"
return datetime(year, month, day).strftime("%B %d, %Y")
# Print the dates of Hanukkah for the next 10 years
for year in range(datetime.now().year, datetime.now().year + 10):
print(f"Hanukkah {year}: {hanukkah_dates(year)}")
| false |
0a7c5b48c2556bd0bbd7cdd8bbc9eb960cfd0c63 | Mgrdich/algorithms_data_structures | /util/Lib.py | 598 | 4.1875 | 4 | import math
class Lib:
"""
Checks a number whether it is prime or not
"""
@staticmethod
def isPrime(n: int) -> bool:
if n == 1 or n == 0 or n % 2 == 0:
return False
limit = math.ceil(math.sqrt(n))
for i in range(3, limit, 2):
if n % i == 0:
return False
return True
"""
Gets the next prime after a given parameter
"""
@staticmethod
def getPrime(n: int) -> int:
if n % 2 == 0:
n += 1
while not Lib.isPrime(n):
n += 2
return n
| true |
ca711f0bd15c40cca23664045ac3974474af2ec1 | sujith1919/TCS-Python | /classroom examples/strings7.py | 666 | 4.375 | 4 | #string indexing
#string slicing
a = "Good Morning"
print(a[0]) #prints the first character
print(a[1]) #prints the second character
print(a[-1]) #prints the last character
print(a[-3]) #prints the third last character
#slicing
print(a[5:8]) #prints from index 5 to 7
print(a[:8]) #prints from index 0 to 7
print(a[5:]) #prints from index 5 to end of string
print(a[0:10:2]) #prints every alternate char from index 0 to 9
print(a[0:10:1]) #prints every char from index 0 to 9
print(a[:]) #prints whole string
print(a[::1]) #prints whole string
print(a[::]) #prints whole string
print(a[::-1]) #prints whole string in reverse
| true |
13ef039681bb8fd37e1a48ea757ae81b98a3fe56 | sujith1919/TCS-Python | /classroom examples/lists2.py | 629 | 4.21875 | 4 | #working with lists
#lists are like C arrays
#but a lot more flexible
b = [3,6,8,4,5,6,7]
#append to a list
print(b)
b.append(9)
print(b)
#insert into a list
print(b)
b.insert(1,200)
print(b)
#remove from a list
print(b)
b.remove(200)
print(b)
#pop from a list
print(b)
c = b.pop()
print(c)
print(b)
c = b.pop(2)
print(c)
# reverse a list
print(b)
b.reverse()
print(b)
# sort
print(b)
b.sort()
print(b)
# sort descending
print(b)
b.sort(reverse = True)
print(b)
print(b.index(3)) #find where 3 is in the list
print(b.count(3)) #find how many times 3 is in the list
| true |
02c5be09f721a6986d414c8366a58bb791d75eb4 | shashanka2a/LeetCode | /addDigits.py | 428 | 4.15625 | 4 | """
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
"""
def addDigits(self, num):
while num>9:
num=sum(int(c) for c in str(num))
return num
def addDigitsFast(self, num):
return (num % 9 or 9) if num else 0
| true |
b6ddfd1034f68fcb04d7dd7367c60d64d74c567f | xujinshan361/python_study_code | /01_Python基础/05_高级数据类型/study_17_字符串的查找和替换.py | 666 | 4.59375 | 5 | hello_str = "hello word"
# 1.判断是否以指定字符串开始
print(hello_str.startswith("he"))
# 2.判断是否以指定字符串结束
print(hello_str.endswith("word"))
# 3.查找指定字符串
# index同样可以查找指定的字符串在大字符串中的索引
print(hello_str.find("lo"))
# index 如果指定的字符串不存在,会报错
# find如果指定的字符串不存在,会返回-1
# print(hello_str.index("abc"))
print(hello_str.find("abc"))
# 4.替换字符串
# replace 方法执行完成后,会返回一个新的字符串
# 注意:不会修改原有的字符串内容
print(hello_str.replace("word", "python"))
print(hello_str)
| false |
c4cf6fa16df4a73d079865b40c23c2a7a721179c | wntbrian/python-course1 | /task2/function_2_while.py | 788 | 4.15625 | 4 | ###
### Задание 2, Вариант 2, Функции №2
###
'''
Дано действительное положительное число a и целоe число n.
Вычислите a в степени n. Решение оформите в виде функции power(a, n).
Стандартной функцией возведения в степень пользоваться нельзя.
'''
def power(a,n):
pw, ls=1
if n<0:
ls=n
n=-n
while n > 0:
pw=pw*a
n=n-1
if ls<0:
return 1/pw
return pw
###map применяет функцию на каждый аргумент списка(списков)
a, n = map(float, input("Введите a и n, через пробел: ").split())
print (power(a,int(n)))
| false |
b609cdd515877e36fe6b0550783c0dcb7195f44e | birdming22/python_examples | /strategy/strategy_class.py | 1,298 | 4.21875 | 4 | """strategy Example
ref. https://sourcemaking.com/design_patterns/strategy/python/1
"""
class StrategyExample(object):
"""Strategy Example class"""
def __init__(self):
self.op1 = 0
self.op2 = 0
self.result = 0
self.operation = ""
def operate(self, op1, op2):
"""operate"""
self.op1 = op1
self.op2 = op2
def print_result(self):
"""print result"""
print self.op1, self.operation, self.op2, '=', self.result
class AddStrategy(StrategyExample):
"""Implement add operation"""
def __init__(self):
super(AddStrategy, self).__init__()
self.operation = "+"
def operate(self, op1, op2):
"""operate"""
super(AddStrategy, self).operate(op1, op2)
self.result = op1 + op2
class SubStrategy(StrategyExample):
"""Implement sub operation"""
def __init__(self):
super(SubStrategy, self).__init__()
self.operation = "-"
def operate(self, op1, op2):
"""operate"""
super(SubStrategy, self).operate(op1, op2)
self.result = op1 - op2
if __name__ == '__main__':
SOLVER = AddStrategy()
SOLVER.operate(2, 1)
SOLVER.print_result()
SOLVER = SubStrategy()
SOLVER.operate(2, 1)
SOLVER.print_result()
| false |
4c205e21356cf91cde27a0c8e474bab67c202961 | eduohe/PythonCodeSnippets | /05-conditional/conditional.py | 250 | 4.1875 | 4 | #!/usr/bin/python3
def main():
x, y = 2,2
if x < y:
print("x < y")
elif x == y:
print("x = y")
else:
print("x > y")
result = "<=" if x <= y else ">="
print(result)
if __name__ == "__main__" : main() | false |
bf4ced295b6e35c862ddb594a3ff2ee65123d688 | jacquewhitaker/jacquewhitaker.github.io | /my_website/whitsshipsv1.py | 2,345 | 4.3125 | 4 | ''' import statements '''
from random import randint
''' declare global variables '''
# constants
BOARD_LENGTH = 8 # set row cell length
TURN_COUNT = 5 # number of guesses a user gets
# parameter names
board = [] # 1D array
ship_row = 0 # default size
ship_col = 0 # default size
''' initialize board to all 0s '''
for x in range(BOARD_LENGTH):
board.append(["O"] * BOARD_LENGTH)
def print_board(board):
''' print the entire board use
0 for not guessed and x for already quessed space '''
for row in board:
print (" ".join(row))
''' Play the game and print the board '''
print ("\n\nLet's play Battleship!")
1
''' print the board to the screen '''
print_board(board)
def random_row(board):
''' select a random row '''
return randint(0, len(board) - 1)
def random_col(board):
''' select a random column '''
return randint(0, len(board[0]) - 1)
def set_ship_location():
''' computer sets the ship's location '''
ship_row = random_row(board)
ship_col = random_col(board)
set_ship_location()
# prompt user for row and column guess
for turn in range(TURN_COUNT):
guess_row = int(input("Guess Row: "))
guess_col = int(input("Guess Col: "))
# if the user's right, the game ends
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sunk my battleship!")
break
else:
# board boundary check
if (guess_row < 0 or guess_row > (len(board)-1) or guess_col < 0 or guess_col > (len(board)-1)):
# out of bounds warning
print ("Oops, that's not even in the ocean. Please try again.")
# warning if the guess was already made
elif(board[guess_row][guess_col] == "X"):
print ("You guessed that one already. Please try a new location.")
# guess missed, mark location with an X, and continue play
else:
print ("Miss!")
board[guess_row][guess_col] = "X"
# print current turn number and board
print ("\nTurn " + str(turn+1) + " out of " + str(TURN_COUNT) + ".")
print_board(board)
# end game when player reaches allotted guess attemtps
if (turn+1) >= TURN_COUNT-1:
print ("Game Over") | true |
87906c497e3967e58098bcb2686a7b0a72b8ec1c | devilist/FirstProject | /数据类型.py | 2,571 | 4.125 | 4 | #! /usr/bin/env python3
counter = 100 # 整型变量
miles = 1000.0 # 浮点型变量
name = "runoob" # 字符串
print(counter)
print(miles)
print(name)
a, b, c, d = 20, 5.5, True, 4 + 3j
print(type(a), type(b), type(c), type(d))
print(8 / 3)
print(8 // 3)
str = 'Runoob'
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始的后的所有字符
print(str * 2) # 输出字符串两次
print(str + "TEST") # 连接字符串
print('Ru\noob')
print(r'Ru\noob')
print(str[0], str[5])
print(str[-1], str[-6])
list = ['abcd', 786, 2.23, 'runoob', 70.2]
tinylist = [123, 'runoob']
print(list) # 输出完整列表
print(list[0]) # 输出列表第一个元素
print(list[1:3]) # 从第二个开始输出到第三个元素
print(list[2:]) # 输出从第三个元素开始的所有元素
print(tinylist * 2) # 输出两次列表
print(list + tinylist) # 连接列表
print('\n')
tuple = ('abcd', 786, 2.23, 'runoob', 70.2)
tinytuple = (123, 'runoob')
print(tuple) # 输出完整元组
print(tuple[0]) # 输出元组的第一个元素
print(tuple[1:3]) # 输出从第二个元素开始到第三个元素
print(tuple[2:]) # 输出从第三个元素开始的所有元素
print(tinytuple * 2) # 输出两次元组
print(tuple + tinytuple) # 连接元组
print('\n')
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print(student) # 输出集合,重复的元素被自动去掉
# 成员测试
if 'Rose' in student:
print('Rose 在集合中')
else:
print('Rose 不在集合中')
# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')
print(a)
print(a - b) # a和b的差集
print(a | b) # a和b的并集
print(a & b) # a和b的交集
print(a ^ b) # a和b中不同时存在的元素
print('\n')
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2] = "2 - 菜鸟工具"
tinydict = {'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
print(dict['one']) # 输出键为 'one' 的值
print(dict[2]) # 输出键为 2 的值
print(tinydict) # 输出完整的字典
print('keys are: ', tinydict.keys()) # 输出所有键
print(tinydict.values()) # 输出所有值
print({x: x**2 for x in (2, 4, 6)})
print('\n')
print("我叫 %s 今年 %d 岁!" % ('小明', 10))
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print(para_str)
| false |
1e409c70a2dbeedd726e6f22c409f8ea4e2cf1e8 | pkr26/Machine-Learning | /Home Works/HW2/HomeWork(2)-Question 02.py | 2,611 | 4.1875 | 4 |
# <h3> Implementing Perceptron Algorithm
# <h5> Assumption in Perceptron Algorithms:<br>
# <br><br>
# <b>The Data should be Linearly Separable<br><br><br>
# <b> The hyperplane or the line should pass through the origin<br>
import numpy as np
import pandas as pd
import os
#checking the path directory
print("Previous directory",os.getcwd())
#Now changing the path directory
path=r"C:\Users\Pavan\Desktop\Machine Learning Github\Home Works\HW2"
os.chdir(path)
print("Current directory",os.getcwd())
col=['a','b','c','d','y']
perceptron=pd.read_table("perceptrons.txt",header=None,names=col)
perceptron
#First thing you have to do in Perceptrons is to change all the labels into a 1 class
for i in range(len(perceptron)):
if(perceptron['y'].iloc[i]==(-1)):
perceptron.iloc[i]=(-1)*perceptron.iloc[i]
#Now you can see that all the values are converted into the Positive Class
perceptron
len(perceptron)
y=perceptron['y']
y
del perceptron['y']
perceptron
total_number_weights=(len(perceptron.columns))
total_number_weights
#First initialize then to some random values
w=[0 for i in range(total_number_weights)]
for i in range(total_number_weights):
w[i]=np.random.uniform(-20,20)
w
w_new=np.reshape(w,(4,1))
w_new
##since in perceptrons we dont have any closed from we can solve them only by using Iteration Methods
n=int(input("Enter the Number of Iterations you want to perform\n"))
LR=0.00005
for i in range(n):
count_misclassified=0
for j in range(len(perceptron)):
out=((perceptron.iloc[j]).dot(w_new))#since this value is 1 and -1
if(out<=0):
count_misclassified=count_misclassified+1
for k in range(total_number_weights):
w_new[k]=w_new[k]+(LR*(perceptron.iloc[j][k]))
print("Iteration:",i)
print("Missclassified:",count_misclassified)
# <h5>Practically speaking we always need to find the right combination of w's and learning rate
# <h5>If the learning rate is very less then the number of iterations should be increased to find the Convergence
# <h5>If the learning rate is high then it is diificult to find the convergence because this moves like crazy
# <h5>So It comes down to finding the appropriate learning rate
# <h3> You can see that as the number of iterations are increasing the number of points that are misclassified gradually decreases
# <h3>If the data is Linealy Separable then you can find the hyperplane that has zero misclassification(Theoretically Speaking)
w_new
| true |
0dd2757122f6f48a2a5f93398c69fe7885f779b7 | sln-dns/lesson1 | /dictionary.py | 352 | 4.25 | 4 | weather = {
"city" : "Москва",
"temperature" : "20"
}
print(weather["city"])
decrease = int(input('Введите уменьшение температуры '))
weather["temperature"] = int(weather["temperature"]) - decrease
print(weather)
print(weather.get("contry", "Россия"))
weather["date"] = "27.05.2019"
print(len(weather))
| false |
9ad8538c59667f174c2b664e7bec9b66571b8d71 | achalesh27022003/sortlinkedlist | /sortlinkedlist.py | 2,719 | 4.34375 | 4 | # Represent a node of the singly linked list
class Node:
def __init__(self,data):
self.data = data
self.next = None
class SortList:
# Represent the head and tail of the singly linked list
def __init__(self):
self.head = None
self.tail = None
# addNode() function will add a new node to the list
def addNode(self, data):
# Create a new node
newNode = Node(data)
# Checks if the list is empty
if(self.head == None):
# If list is empty, both head and tail will point to new node
self.head = newNode
self.tail = newNode
else:
# newNode will be added after tail such that tail's next will point to newNode
self.tail.next = newNode;
# newNode will become new tail of the list
self.tail = newNode
# sortList() will sort nodes of the list in ascending order
def sortList(self):
# Node current will point to head
current = self.head
index = None
if(self.head == None):
return;
else:
while(current != None):
# Node index will point to node next to current
index = current.next;
while(index != None):
# If current node's data is greater than index's node data, swap the data between them
if(current.data > index.data):
temp = current.data
current.data = index.data
index.data = temp
index = index.next
current = current.next
# display() function will display all the nodes present in the list
def display(self):
# Node current will point to head
current = self.head;
if(self.head == None):
print("List is empty")
return;
while(current != None):
# prints each node by incrementing pointer
print(current.data),
current = current.next
print (" ")
sList = SortList()
# adding data to the list
sList.addNode(13)
sList.addNode(4)
sList.addNode(2)
sList.addNode(5)
sList.addNode(6)
# displaying original list
print("Original list: ")
sList.display()
# Sorting list
sList.sortList()
# displaying sorted list
print("Sorted list: ")
sList.display() | true |
da01108bec94e563d5915681a1835b310fe83908 | Miheel/PY_lab | /Lab1/sten_sax_påse/kai_bai_bo.py | 1,925 | 4.1875 | 4 | """
kai bai bo
"""
import random
def rand():
"""'
Simple randomizer
"""
rng = random.randint(1, 3)
return rng
def main():
"""
main funktion
"""
moves = ["Rock", "Paper", "Scissor"]
player_points = 0
pc_points = 0
play_loop = True
print("Welcome to the Game ROCK-PAPER-SCISSORS!\n")
name = input("Please type your name ")
print("Welcome ", name, " What's your choise\n")
while play_loop:
print("ROCK(1), PAPER(2), SCISSORS(3), or end game(q or quit)")
player_input = input("input: ") #input to str
pc_choice = str(rand()) #convert value from rand int to str
if player_input in ("1", "2", "3"):
if player_input == pc_choice: #Argument for a draw
print("it'a draw\npc: ", moves[int(pc_choice)-1])
print(name, ":", moves[int(player_input)-1], "\n")
#Argument for a player wim
elif player_input == "1" and pc_choice == "3" or player_input == "2" and pc_choice == "1" or player_input == "3" and pc_choice == "2":
#takes value from list moves to write out move instead number
print("congrats you win\npc: ", moves[int(pc_choice)-1])
print(name, ":", moves[int(player_input)-1], "\n")
player_points += 1
else: #Argument for a player win
print("you loose\npc: ", moves[int(pc_choice)-1])
print(name, ":", moves[int(player_input)-1], "\n")
pc_points += 1
elif player_input in ("q", "quit"): #Argument to end th game
print(name, "have", player_points, "points.\nPc have ", pc_points, "points.")
print("Exiting game")
input("Press enter exit")
play_loop = False
else:
print("invalid input\n")
if __name__ == "__main__":
main()
| false |
813edeb4b243842e4bfbb4a1d0a20e705300fea8 | dundunmao/lint_leet | /mycode/lintcode/Array/two sum/625 partition-array-ii.py | 1,222 | 4.125 | 4 | # -*- encoding: utf-8 -*-
# Partition an unsorted integer array into three parts:
# The front part < low
# The middle part >= low & <= high
# The tail part > high
# Return any of the possible solutions.
#
# 注意事项:low <= high in all testcases.
# 样例
# Given [4,3,4,1,2,3,1,2], and low = 2 and high = 3.
#
# Change to [1,1,2,3,2,3,4,4].
#
# ([1,1,2,2,3,3,4,4] is also a correct answer, but [1,2,1,2,3,3,4,4] is not)
#
class Solution:
"""
@param nums: The integer array you should partition
@param k: As description
@return: The index after partition
"""
def partitionArray(self, nums, low, high):
if nums is None or len(nums) <= 1:
return
le = len(nums)
l = 0
r = le - 1
i = 0
while i <= r:
if nums[i] < low:
nums[i],nums[l] = nums[l],nums[i]
l += 1
i += 1
elif nums[i] > high:
nums[i],nums[r] = nums[r],nums[i]
r -= 1
else:
i += 1
return nums
if __name__ == '__main__':
list = [4,3,4,1,2,3,1,2]
low = 2
high = 3
s = Solution()
print s.partitionArray(list, low, high) | true |
3967db398f71847ed2cb8424a207c154bb3cea64 | dundunmao/lint_leet | /mycode/leetcode_old/1 array(12)/hard/42. Trapping Rain Water.py | 1,214 | 4.15625 | 4 | # -*- encoding: utf-8 -*-
# 3级
# 内容:能积多少水.Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
# For example,
# Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
# ^
# 3| ■ □: water
# 2| ■ □ □ □ ■ ■ □ ■ ■: elevation map
# 1| ■ □ ■ ■ □ ■ ■ ■ ■ ■ ■
# ————————————————————————>
# 左右两边开始跑,水位线minHeight开始为0,左边遇到比水位线低的,就开始储水,直到遇到比水位线高的结束,这个比水位线高的位置一会要跟右边的这个高度比较取最小.
# 右边同理
def trap(height):
n = len(height)
l, r, water, minHeight = 0, n - 1, 0, 0
while l < r:
while l < r and height[l] <= minHeight:
water += minHeight - height[l]
l += 1
while r > l and height[r] <= minHeight:
water += minHeight - height[r]
r -= 1
minHeight = min(height[l], height[r])
return water
if __name__ =="__main__":
height = [0,1,0,2,1,0,1,3,2,1,2,1]
print trap(height)
| false |
d713e35608ec089ee02f2f307c9860dacb53cb30 | dundunmao/lint_leet | /mycode/lintcode/DFS template.py | 1,003 | 4.125 | 4 | # -*- encoding: utf-8 -*-
# bfs的模板
class Node:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
# 1: traverse
def traverse(root):
if root is None:
return None
traverse(root.left)
traverse(root.right)
# 2: divid & conquer
def traversal(root):
if root is None:
return None
left = traversal(root.left)
right = traversal(root.right)
result = merge(left, right)
return result
def merge():
return None
if __name__ == '__main__':
# TREE 1
# Construct the following tree
# 26
# / \
# 10 10
# / \ / \
# 4 6 6 4
# / \
# 3 3
P = Node(26)
P.left = Node(10)
P.left.left = Node(4)
P.left.left.left = Node(3)
P.left.right = Node(6)
P.right = Node(10)
P.right.right = Node(4)
P.right.right.right = Node(3)
P.right.left = Node(6)
print BFS_level_order(P) | false |
458a1517122fe9f0b347d3064bdf5284f5244742 | dundunmao/lint_leet | /mycode/leetcode2017/Hash/350. Intersection of Two Arrays II.py | 1,850 | 4.125 | 4 | # Given two arrays, write a function to compute their intersection.
#
# Example:
# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
#
# Note:
# Each element in the result should appear as many times as it shows in both arrays.
# The result can be in any order.
# Follow up:
# What if the given array is already sorted? How would you optimize your algorithm?
# What if nums1's size is small compared to nums2's size? Which algorithm is better?
# What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if nums1 is None or len(nums1) == 0:
return []
if nums2 is None or len(nums2) == 0:
return []
nums1.sort()
nums2.sort()
i,j = 0,0
result = []
while i<len(nums1) and j<len(nums2):
if nums1[i] == nums2[j]:
# if len(result) == 0 or result[-1] != nums1[i]:
result.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return result
from collections import Counter
class Solution1(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
# corner case
if nums1 is None or nums2 is None:
return []
# main part
hash = Counter(nums1)
res = []
for ele in nums2:
if ele in hash and hash[ele]:
res.append(ele)
hash[ele] -= 1
return res | true |
5810283138b8e106e5ed704d29342c33b7ff4fa8 | dundunmao/lint_leet | /mycode/leetcode2017/String/451. Sort Characters By Frequency.py | 918 | 4.375 | 4 | # -*- encoding: utf-8 -*-
# Given a string, sort it in decreasing order based on the frequency of characters.
#
# Example 1:
#
# Input:
# "tree"
#
# Output:
# "eert"
#
# Explanation:
# 'e' appears twice while 'r' and 't' both appear once.
# So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
# Example 2:
from collections import Counter
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
hash = Counter(s)
# hash = {'e':2,'d':1}
temp = sorted(hash.items(), key=lambda x: x[1], reverse=True)
res = []
for k, v in temp:
for i in range(v):
res.append(k)
return ''.join(res)
if __name__ == "__main__":
a = "tree"
b = "AATTCCGG"
c = ["AATTCCGG","AACCTGGG","AACCCCGG","AACCTACC"]
s = Solution()
print s.frequencySort(a) | true |
833b8754318f239d9cc34385fe2bca9640d8fc07 | dundunmao/lint_leet | /mycode/leetcode_old/2 string(9)/125. Valid Palindrome.py | 1,012 | 4.1875 | 4 | # -*- encoding: utf-8 -*-
# 2级
# 题目:回文正反都能读
# 例如:"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome.
# 思路:str.isalnum()判断是否为非数字字母的str。两个指针,分别从前和后往前遍历。记住这段code
class Solution:
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
if not s:
return True
s = s.lower()
cl = 0
cr = len(s)-1
while cl <= cr:
if not s[cl].isalnum(): # 判断str.isalnum()是为了让出空格
cl += 1
continue
if not s[cr].isalnum():
cr -= 1
continue
if s[cl] != s[cr]:
return False
cl += 1
cr -= 1
return True
def isPalindrome1(x):
return x==x[::-1] #不能用这个,因为中间有标点符号和空格
if __name__ == "__main__":
x = 'a.'
print isPalindrome1(x) | false |
3e43d498d3ed43cec67f25ed8d59623f8cf13f59 | Aaqib925/Assignment | /assignment 5.py | 2,883 | 4.25 | 4 | # Question 1
# Write a Python function to calculate the factorial of a number (a non-negative
# integer). The function accepts the number as an argument.
def fact(num):
""" functions which finds a factorial value of the number """
factorial = 1
if num < 0:
return "The factorial of the negative number doesn't exist."
elif num == 0 or num == 1:
return "The factorial of {} is 1".format(num)
elif num > 1:
for i in range(1, num + 1):
factorial = factorial * i
return factorial
number = int(input("Enter the number you want to find the factorial: "))
print("The factorial of {} is:".format(number), fact(number))
# Question:2
# Write a Python function that accepts a string and calculate the number of upper
# case letters and lower case letters.
#
sent = input("Enter the String: ")
lower_letters = "abcdefghijklmnopqrstuvwxyz"
upper_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
upper_count = 0
lower_count = 0
for i in sent:
if i in lower_letters:
lower_count += 1
elif i in upper_letters:
upper_count += 1
print("The number of upper case letters are: ", upper_count)
print("The number of lower case letters are: ", lower_count)
# Question:3
# Write a Python function to print the even numbers from a given list.
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = []
for i in lst:
if i % 2 == 0:
even_numbers.append(i)
print("The even numbers in given lists are:", even_numbers)
# Question:4
# Write a Python function that checks whether a passed string is palindrome or not.
# Note: A palindrome is a word, phrase, or sequence that reads the same
# backward as forward, e.g., madam
word = input("Enter any word: ")
reverse_word = word[-1::-1]
if word == reverse_word:
print("The word {} is palindrome".format(word))
else:
print("The word {} is not palindrome".format(word))
Question: 5
# Write a Python function that takes a number as a parameter and check the
# number is prime or not.
def prime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
print("The number {} is not prime number".format(num))
print(str(i), "*", str(num // i), "=", num)
break
else:
print("The number {} is a prime number".format(num))
number = int(input("Enter any number: "))
prime(number)
# Question: 6
# Suppose a customer is shopping in a market and you need to print all the items
# which user bought from market.
# Write a function which accepts the multiple arguments of user shopping list and
# print all the items which user bought from market.
def items(*names):
""" This functions accept multiple argument and print it """
print("The items customer bought are as follows: ")
for item in names:
print(item)
items("Chocolate", "Mango juice", "Vegetables")
| true |
b9afcbbeb6631087b2352ca2423406ff4fb850c9 | maxitaxi03/Python_stuff | /conditions.py | 268 | 4.28125 | 4 | #num= input("Enter number: ")this generates an error because the input function assumes it's a string type
num = int(input("Enter number: "))
if num > 0:
print(f"{num} is positive.")
elif num < 0:
print(f"{num} is negative.")
else:
print(f"{num} is zero.") | true |
6931ae5dafc4d5d0d8b29b879e53098c28edfde7 | acepele/PRG105 | /retirement_savings_calculator.py | 1,049 | 4.15625 | 4 | age = int(input("How old are you currently?"))
retire_age = int(input("At what age do you want to retire?"))
income = float(input("What is your yearly income?"))
percentage = float(input("What percent of your income do you save?"))
savings = float(input("How much money do you currently have in your savings?"))
pay_raise = .03
investment = .06
years_until_retirement = retire_age - age
print("You have " + str(years_until_retirement) + " years left until you retires")
year = 0
print("This projection assumes a 3% raise each year and a 6% yearly return on investment")
print(" YEAR INCOME SAVINGS CONTRIBUTIONS TOTAL SAVINGS")
while year < years_until_retirement:
year += 1
income += pay_raise * income
total_savings = savings * investment
contribution = income * percentage
years_until_retirement -= 1
total_savings += contribution
print(format(year, "8,.0f") + format(income, "14,.0f") + format(contribution, "25,.0f")
+ format(total_savings, "30,.0f"))
| true |
0e9382996e3c3ac4abbec2697973755b74af3451 | DongmeeKim/Python-Study | /dictionary set/set.py | 1,307 | 4.15625 | 4 | # 집합 (Sets)
ss = set(['a','b','c'])
print(ss)
ss = set([1,2,3])
print(ss)
ss = set("Good Morning")
print(ss)
# 집합을 인덱싱하기 -> list 사용
ss1 = set([1,2,3])
li = list(ss1)
print(li[2])
# 교집합, 합집합, 차집합
s1 = set([1,2,3,4,5,6,7])
s2 = set([3,5,6,8,9])
# 교집합 : &
print(s1 & s2)
# 합집합 :| or .union()
print(s1 | s2)
print(s1.union(s2))
# 차집합 : - or .difference()
print(s1-s2)
print(s1.difference(s2))
# 집합에 값을 추가하기
# 1개 일 때 : .add()
s1 = set([1,3,4])
s1.add(100)
print(s1)
# 여러개를 동시에 추가할 때 : .update()
s1 = set([1,2,3,4])
s1.update([10,100,1000])
print(s1)
# 집합에서 값을 삭제하기 : .remove() / .discard()
# .remove() : 집합 내에 없는 요소를 제거요청하면 에러 메세지가 뜸
s1 = set([1,2,3,4,5])
s1.remove(5)
print(s1)
# .discard() : 집합 내에 없는 요소를 제거요청해도 에러가 뜨지 않음
s1.discard(6)
s1.discard(2)
print(s1)
# 대칭차집합 : ^
# 두 집합이 있을 때, 둘 중 한 집합에만 있는 요소(항목)을 나타냄
s = set("Good Morning")
t = set("Good Night")
print(s ^ t)
# 집합 내 요소의 개수를 구하는 방법 : len()
length = len(t)
print(length)
s = set("Good Morning")
length = len(s)
print(length) | false |
c2b339938731d8d089f33f03fe5bbde22a5719e5 | OdessaRadio/Complete_Python_Developer_in_2020-Zero-to-Mastery | /Python_Basics_3/formatted_strings.py | 996 | 4.375 | 4 | # formatted strings
# name = "Johnny"
# age = 55
# # print('Hi '+ name + '. You are ' + str(age))
# print(f'Hi, {name}. You are {age} yers old') # f tells Python that this is formatted string
# print('Hi, {}. You are {} yers old'.format('Johnny', '55'))
# print('Hi, {}. You are {} yers old'.format(name, age))
# print('Hi, {1}. You are {0} yers old'.format(name, age))
# print('Hi, {1}. You are {0} yers old'.format(name, age))
# print('Hi, {new_name}. You are {new_age} yers old'.format(new_name='Sasha', new_age=32))
# string indexes
# selfish = '01234567'
# #01234567
# print(selfish[0])
# print(selfish[7])
# print(selfish)
# # [start:stop:stepover]
# print(selfish[0:8:3])
# print(selfish[1:])
# print(selfish[:5])
# print(selfish[::2])
# print('#')
# print(selfish[-2]) # Negative index means to start from the end of the string
# print(selfish[::-1])
# print(selfish[::-2])
# immutability
selfish = '01234567'
print(selfish)
selfish = selfish + '8'
print(selfish)
| false |
c107ab318900e779ad761d01eae972b8e4ffccbf | OdessaRadio/Complete_Python_Developer_in_2020-Zero-to-Mastery | /Python_Basics_3/built_in_functions_methids.py | 335 | 4.125 | 4 | print(len('0123456789')) # len -> lenght ofthe string
greet = '0123456789'
print(greet[1:])
print(greet[0:len(greet)])
quote = "to be or not to be"
print(quote.upper())
print(quote.capitalize())
print(quote.find('be'))
print(quote.replace('be','me'))
print(quote) # strings are immutable. So it will print "to be or not to be"
| true |
dd3c00d69811963353e85a59072c510846c7a4dd | ananddasani/Python_Practice_Course | /Quick_Basic/9.practice_List_and_tuples.py | 782 | 4.4375 | 4 | # Take DOB from user as a format DD-MM-YYYY and print the name of month the user is born in
months = ["january", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
# taking input as a string
DOB = input("Enter your DOB in DD-MM-YYYY formate :: ")
# calculated the index and converted into int because can't be string
index = int((DOB[3:5])) - 1 # index starts form 0 so substract one
bd_month = months[index]
print("You are born in ", bd_month)
'''
QUESTION 2 ::
Ask user his name and append that name into the predefined list of names
'''
people = ["Anand ", "jay", "Ria", " Karina"]
name = input("Enter your name to add it in the list :: ")
people.append(name)
print("here's the list : ", people)
| true |
c3b32a9a5281c3c2b56d9125376718f943199953 | ananddasani/Python_Practice_Course | /Quick_Basic/20.functions.py | 698 | 4.40625 | 4 | # program to demonstrate the functions in python
# function without args
def say_hello():
print("Hello python :)")
say_hello()
# function with args
def say_hello_args(arg1, arg2):
print("Hello " + arg1 + " how are you doing ? " +
arg2 + " is waiting for you :)")
say_hello_args("anand", "om")
# different way of passing args
def say_hello_args1(arg1, arg2="jay"):
print("Hello " + arg1 + " how are you doing ? " +
arg2 + " is waiting for you :)")
say_hello_args1("anand")
def fah2celsius(fah):
celsius = (5 * (fah - 32)) / 9
return celsius
print("Celsius : ", round(fah2celsius(100), 2))
print("Kelvin : ", round(fah2celsius(100) + 273.5, 2))
| false |
ebcbeabb3bb8a028da820c2ad96e33eefa3b7982 | xukangjune/Leetcode | /solved/23. 合并K个排序链表.py | 1,952 | 4.15625 | 4 | """
这道题有好多解法。首先我写的是将所有链表的第一个节点值(如果有的话)放在一个临时的数组中,然后再这个数组中找到最小的值,将这个
最小值当作返回链表的下一个节点,然后找出这个数在临时数组的下标,只是临时数组和链表数组一一对应的,就可以映射到链表数组中,接着
判断对应的链表下一个节点是否为空,如果为空则是一番操作,不是另一番操作。
其实,这道题用暴力法是最简单的,也是最快的。直接将所有链表的所有节点值加入一个数组,然后直接排序。
还有一个就是将所有的链表两两合并,然后将新的链表与下一个链表合并,直到结束。
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
# 这么写反而时间慢,内存大,不如暴力法
# head = ListNode(None)
# node = head
# lists = [l for l in lists if l]
# if lists:
# temp = [node.val for node in lists]
# while temp:
# num = min(temp)
# node.next = ListNode(num)
# node = node.next
# i = temp.index(num)
# if lists[i].next:
# lists[i] = lists[i].next
# temp[i] = lists[i].val
# else:
# del lists[i]
# del temp[i]
# return head
# 暴力法,这种方法是最暴力的也是最快的
ret = []
if lists:
for node in lists:
while node:
ret.append(node.val)
node = node.next
ret.sort()
return ret | false |
f460de727a2021b774bdb3a4d1f3b870dcfa6f5b | xukangjune/Leetcode | /solved/334. 递增的三元子序列.py | 1,540 | 4.15625 | 4 | """
有时候能想到好想法,却在一些细节方面没有做到优化。这一题由于只要三个数递增就好了,所以先设置两个数为无穷大,当有数
大于第二个数时说明有三个数递增。假如大于第一个数而小于第二个数,那么就第二个的数替换成num。因为大于second的一定会
大于num,这样就扩大了查找的范围。假如num小于第一个数,那么将first换成num,因为不影响second的取值范围,这样如果
后面的数小于second而大于现在的num,那就将second替换,这样原来的first和second就换成了更小的两个数,这样扩大了查
找的范围。
"""
class Solution:
def increasingTriplet(self, nums):
# 没必要用stack
# n = len(nums)
# if n < 3:
# return False
# stack = [float("inf"), float("inf")]
# for num in nums:
# if num > stack[1]:
# return True
# elif stack[0] < num < stack[1]:
# stack[1] = num
# elif num < stack[0]:
# stack[0] = num
# print(stack)
# return False
# 直接用两个数代替
first = second = float("inf")
for num in nums:
if num > second:
return True
elif first < num < second:
second = num
elif num < first:
first = num
return False
solve = Solution()
nums = [5,10,6,4,3]
print(solve.increasingTriplet(nums)) | false |
1133aecb5df8171f339f47e4c997bc86771c36a2 | leandrolimasp/python-apps | /calculator.py | 926 | 4.1875 | 4 |
class Calculator:
def __init__(self):
pass
def calculate(f):
while True:
print('\n===== CALCULATOR =====\n')
print(' 1 -- Addition')
print(' 2 -- Subtraction')
print(' 3 -- Multiplication')
print(' 4 -- Division')
print(' 5 -- Percentage')
print(' 6 -- Exponentiation')
print(' 7 -- Floor Division')
print(' 8 -- Exit\n')
x = int(input('Choice an option: '))
if x == 8:
print('Byee...'); exit()
elif x not in range(1,8):
print('Invalid Option')
else:
a = float(input('1° Number: '))
b = float(input('2° Number: '))
if x==1:
print('Result:',a+b)
elif x==2:
print('Result:',a-b)
elif x==3:
print('Result:',a*b)
elif x==4:
print('Result:',a/b)
elif x==5:
print('Result:',int(a*b)/100)
elif x==6:
print('Result:',a**b)
elif x==7:
print('Result:',a//b)
x = Calculator()
x.calculate()
| false |
7bd95ca78d13d09d3c902766e58f37d251ad9d7d | jc2c2/pygameTIII2020 | /Introduccion a Python/ejemplo2.py | 1,048 | 4.25 | 4 | # Estructuras de Control
"""
Operadores Relacionales
== igual
!= no es igual
< menor
> mayor
<= menor igual
>= mayor igual
Operadores Logicos
and -> y logico -> &&
or -> o logico -> ||
not -> negacion -> !
Operadores de identidad
is -> pertence a
is not -> no pertenece
Operadores de membresia
in -> aparece en
not in -> no aparece en
"""
# Bifurcacion (if)
#edad = int(input("Ingrese su edad: "))
"""
if edad >= 18 :
print("Usted es Mayor de Edad")
print("Sigo en el if")
if edad >= 60:
print("Usted es Adulto Mayor")
else:
print("Usted Es Menor de Edad")
print("Sigo fuera del if")
"""
# Ciclos
# while (mientras)
"""
while edad > 0:
print("valor: " + str(edad))
#edad = edad - 1
edad -= 1
"""
# for (iterable)
# for variable_iteracion in variable_iterable:
"""
variable_iterable = ["azul", "rojo", "negro", "gris", "blanco"]
for i in variable_iterable:
print("Valor: " + str(i))
"""
# range(n) -> [0,n-1]
# range(n,m) -> [n, m-1]
for i in range(1,10):
print("Valor: " + str(i))
| false |
2dbf8950e0e0401f7d63d8050560c09e5f16e210 | jboe10/python_practice | /Sorting_Algorithms/Insertion_Sorts/insert.py | 280 | 4.15625 | 4 | def insertion_sort(array):
for i in range(1,len(array)):
key = array[i]
follow = i -1
while follow >= 0 and key < array[follow]:
array[follow+1] = array[follow]
follow -= 1
array[follow+1] = key
array= [1,3,411,23,142,33,21,9]
insertion_sort(array)
print(array) | true |
71b0a1c14c7ce3d51fc7fbb8efcac58303efa61f | jboe10/python_practice | /Trees/Max_heap/max_heap2.py | 1,609 | 4.3125 | 4 | class node:
def __init__(self, value = None, color = "black"):
self.value = value
self.left = None
self.right = None
self.color = color
class red_black:
def __init__(self):
self.root = None
#this makes it so we dont have to worry about root/parent being empty
def insert(self, value):
if self.root == None:
self.root = node(value)
else:
self._insert(value, self.root)
######################################
def _insert(self, value, cur_node):
#insert left obj if less than
if value < cur_node.value:
if cur_node.left == None:
if cur_node.color == "black":
cur_node.left = node(value, "red")
else:
cur_node.left = node(value)
else:
self._insert(value, cur_node.left)
#insert right of object if greater than
elif value > cur_node.value:
if cur_node.right == None:
if cur_node.color == "black":
cur_node.right = node(value, "red")
else:
cur_node.right = node(value)
else:
self._insert(value, cur_node.right)
else:
print("value in tree")
def print_tree(self):
self._print_tree(self.root)
####################################
def _print_tree(self, current_node):
if current_node != None:
print(str(current_node.value) + " " + current_node.color)
self._print_tree(current_node.left)
self._print_tree(current_node.right)
heap = red_black()
heap.insert(1)
heap.insert(2)
heap.insert(3)
heap.insert(4)
heap.insert(5)
heap.insert(6)
heap.insert(7)
heap.insert(8)
heap.print_tree()
#root is black ------------
#all NIL are black---------
#if a node is red children are black | true |
d8558d872368bce9acbce46503b5fc0f0e23d1d9 | gmcapra/Python-Data-Structures | /Array Sequences/dynamic_array_example.py | 2,089 | 4.28125 | 4 | """
--------------------------------------------------------------------------------
Dynamic Array Exercise Project
--------------------------------------------------------------------------------
Gianluca Capraro
Created: July 2019
--------------------------------------------------------------------------------
The purpose of this project is to demonstrate how to create and implement a
Dynamic Array class using the built-in ctypes library.
--------------------------------------------------------------------------------
"""
import ctypes
class DynamicArray(object):
def __init__(self):
#count of elements (default 0)
self.n = 0
#how much it can hold (default 1, we will use dynamic style to get larger capacities)
self.capacity = 1
#initialize A as array of capacity 1
self.A = self.make_array(self.capacity)
def __len__(self):
#return num elements in array
return self.n
def __getitem__(self,k):
if not 0 <= k < self.n:
#check if index is within range
return IndexError('K index out of bounds!')
#if it is in range, return the array value at index k
return self.A[k]
def append(self,element):
#add element to end of array
#check if capacity is full
if self.n == self.capacity:
self._resize(2*self.capacity) # multiply by 2 if capacity isnt enough
#otherwise
self.A[self.n] = element
self.n += 1
def _resize(self,new_capacity):
#private method to resize internal array to a new capacity
B = self.make_array(new_capacity)
for k in range(self.n):
B[k] = self.A[k]
self.A = B
self.capacity = new_capacity
def make_array(self,new_capacity):
#return new array with new capacity
return(new_capacity*ctypes.py_object)()
"""
--------------------------------------------------------------------------------
Test the Dynamic Array Object
--------------------------------------------------------------------------------
"""
arr = DynamicArray()
print("\nDynamic Array Object (Arr) Successfully Created.\n")
arr.append(2)
print("Append Function Verified.\n")
arr._resize(50)
print("Resize Function Verified.\n")
| true |
6564c454e3c628e6ac4d72af5a0d29bc5da62368 | emanmacario/dsa | /ctci-solutions/ch-08-recursion-and-dynamic-programming/01-triple-step.py | 2,071 | 4.53125 | 5 | # Triple Step: A child is running up a staircase with n steps and can hop 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.
# Hints: #152, #178, #217, #237, #262, #359
# -- Solution
# Here is a general solution for climbing n steps with advance limit of k steps
def number_of_ways_to_top(top, maximum_step):
"""
Solution has O(n) time complexity, and O(n) space complexity
We use the formula given below to understand the problem:
F(n, k) = sum F(n - i, k) for i = 1,..,k
where F(0) = 1
Where
n: total number of steps to climb
k: maximum number of steps to advance at a time (i.e. step-size in [1, k])
"""
def compute_number_of_ways_to_h(h):
# Differs from Fibonacci in sense that base case F(0) = 1, not 0
if h <= 1:
return 1
if number_of_ways_to_h[h] == 0:
number_of_ways_to_h[h] = sum(
compute_number_of_ways_to_h(h - i)
for i in range(1, maximum_step + 1) if h - i >= 0)
return number_of_ways_to_h[h]
number_of_ways_to_h = [0] * (top + 1)
return compute_number_of_ways_to_h(top)
# Here is a specific solution for k = 3 (not using general solution as a subroutine)
def triple_step(n):
"""
Computes the total number of ways to climb a total of n
steps, climbing only 1, 2, or 3 steps at a time
Solution has O(n) time complexity, and O(n) space complexity.
Could make it O(1) space complexity if we choose to use three
variables instead of an array of size O(n)
"""
if n <= 1:
return 1
dp = [1, 1] + [0] * (n - 1)
for i in range (2, n + 1):
dp[i] = sum(dp[k] for k in range(i - 3, i) if k >= 0)
return dp[n]
# -- Testing
if __name__ == "__main__":
for top in range(1, 50):
general = number_of_ways_to_top(top, 3)
specific = triple_step(top)
print(f'{general:10} {specific:10} {general == specific}')
| true |
0fcd282fe6957aeff00209bc387b709feb439706 | emanmacario/dsa | /ctci-solutions/ch-01-arrays-and-strings/01-is-unique.py | 449 | 4.15625 | 4 | # Implement an algorithm to determine if a string has all unique characters. What if you
# cannot use additional data structures?
# Hints: #44, #117, #732
def is_unique(string):
seen = set()
for char in string:
if char in seen:
return False
seen.add(char)
return True
def main():
s1 = 'hello'
s2 = 'world'
print(is_unique(s1))
print(is_unique(s2))
if __name__ == "__main__":
main()
| true |
8c40a3d75548b9ad23854b29281296897b64d6ea | emanmacario/dsa | /ctci-solutions/ch-01-arrays-and-strings/09-string-rotations.py | 912 | 4.59375 | 5 | # String Rotation: Assume you have a method isSubstring which checks if one word is a substring
# of another. Given two strings, sl and s2, write code to check if s2 is a rotation of s1 using only one
# call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat").
# Hints: #34, #88, #104
def is_substring(string, substring):
return substring in string
def string_rotation(s1, s2):
"""
Runtime varies on runtime of is_substring
Assuming is_substring is O(A + B), then
this algorithm has O(N) time complexity
"""
assert(len(s1) == len(s2) and s1 and s2)
return is_substring(s1 + s1, s2)
if __name__ == "__main__":
s1 = 'erbottlewat'
s2 = 'waterbottle'
print(string_rotation(s1, s2))
s3 = 'macarioemmanuel'
s4 = 'emmanuelmacario'
print(string_rotation(s3, s4))
s5 = 'hello joseph'
s6 = 'joseph hello'
print(string_rotation(s5, s6))
| true |
c371018c53ce4f396ac65f2ed3738a0c4088866e | emanmacario/dsa | /epi-solutions/ch-11-searching/06-search-2d-sorted-array.py | 1,829 | 4.3125 | 4 | # Call a 2D array sorted if its rows and its columns are nondecreasing.
# For example:
# -1 2 4 4 6
# 1 5 5 9 21
# 3 6 6 9 22
# 3 6 8 10 24
# 6 8 9 12 25
# 8 10 12 13 40
# Design an algorithm that takes a 2D sorted array and a number and checks
# whether that number appears in the array. For example, if the input is the
# 2D sorted array in the example and the number is 7, your algorithm should
# return false; if the number is 8, your algorithm should return true.
# Hint: Can you eliminate a row or a column per comparison?
# -- Solution
def matrix_search(A, x):
"""
Idea is to start at top right corner of matrix,
and eliminate columns or rows that cannot contain x,
iteratively.
This is effectively a unique path starting from the top
right of the matrix, moving only down or left, to either
the element (if it exists), or to one unit outside of
the left or bottom edge of the matrix.
Hence, time complexity is O(M + N), where M is total rows
and N is total columns.
"""
# Sanity check
assert(A and A[0])
# Perform search
row, col = 0, len(A[0]) - 1
while row < len(A) and col >= 0:
if x == A[row][col]:
# Target found
return True
elif A[row][col] > x:
# Matrix value larger than target, move left
col -= 1
else:
# Matrix value smaller than target, move down
row += 1
return False
# -- Testing
from pprint import pprint
if __name__ == '__main__':
A = [[-1, 2, 4, 4, 6],
[1, 5, 5, 9, 21],
[3, 6, 6, 9, 22],
[3, 6, 8, 10, 24],
[6, 8, 9, 12, 25],
[8, 10, 12, 13, 40]]
pprint(A)
print(matrix_search(A, 8)) # True
print(matrix_search(A, 7)) # False
| true |
3f0b3b2ee8f5a58f4f1fc25114c095461bce3a37 | emanmacario/dsa | /ctci-solutions/ch-04-trees-and-graphs/03-list-of-depths.py | 1,825 | 4.28125 | 4 | # List of Depths: Given a binary tree, design an algorithm which creates a
# linked list of all the nodes at each depth (e.g., if you have a tree with
# depth D, you'll have D linked lists).
# Hints: #107, #123, #135
# -- Auxiliary data structures
# Definition for singly-linked list
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
# Returns a string representation of the linked list
s = ''
tmp = self
while tmp:
s += f"{tmp.val}->"
tmp = tmp.next
s += 'NULL'
return s
@classmethod
def from_list(cls, vals):
# Creates a linked list given a list of values
if not vals:
return None
nodes = [ListNode(val) for val in vals]
for n1, n2 in zip(nodes, nodes[1:] + [None]):
n1.next = n2
return nodes[0]
# -- Solution
def list_of_depths(root):
"""
Creates a linked list for each depth level in a binary search tree
"""
if not root:
return []
lists = []
queue = [root]
while queue:
depth = queue
queue = [c for p in queue for c in [p.left, p.right] if c]
# NB: In real interview, generate lists properly with dummy heads
dummy_head = tail = ListNode()
for node in depth:
tail.next = ListNode(node.val)
tail = tail.next
lists.append(dummy_head.next)
return lists
# -- Testing
from binary_search_tree import TreeNode
from random import randint
if __name__ == "__main__":
tree = TreeNode(10)
for _ in range(20):
tree.insert(randint(0, 20))
tree.display()
print('\n' + '-' * 25)
lists = list_of_depths(tree)
for depth in lists:
print(depth)
| true |
72d54cbbf3fac238508d8d9ef2770035577768ce | emanmacario/dsa | /ctci-solutions/ch-02-linked-lists/04-partition.py | 1,831 | 4.3125 | 4 | # Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
# before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
# to be after the elements less than x (see below). The partition element x can appear anywhere in the
# "right partition"; it does not need to appear between the left and right partitions.
# EXAMPLE
# Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition = 5]
# Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
# Hints: #3, #24
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
s = ''
tmp = self
while tmp:
s += f"{tmp.val}->"
tmp = tmp.next
s += 'NULL'
return s
@classmethod
def from_list(cls, vals):
if not vals:
return None
nodes = [ListNode(val) for val in vals]
for n1, n2 in zip(nodes, nodes[1:] + [None]):
n1.next = n2
return nodes[0]
# TODO: Check correctness wrt. answer in book
def partition(head, x):
"""
Solution is O(N) time complexity in length of original list
and O(1) additional space
"""
lesser = less_tail = ListNode()
greater_equal = great_tail = ListNode()
while head:
if head.val < x:
less_tail.next = head
less_tail = less_tail.next
else:
great_tail.next = head
great_tail = great_tail.next
head = head.next
less_tail.next = greater_equal.next
great_tail.next = None
return lesser.next
if __name__ == "__main__":
head = ListNode.from_list([3, 5, 8, 5, 10, 2, 1])
print(head)
new_head = partition(head, 8)
print(new_head)
| true |
6c53d466477ed42be9fd961c9d748cc004e08fd2 | pierre-ecarlat/algorithms_experiments | /leetcode_mess/q3.py | 1,130 | 4.28125 | 4 | """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
------------------------------
Find All Duplicates in an Array
------------------------------
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some
elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
import numpy as np
examples = [
{ 'array': [4,3,2,7,8,2,3,1], 'result': [2,3] },
]
def solve(params):
array = params['array']
already_seen = []
for item in array:
if array[abs(item)-1] > 0:
array[abs(item)-1] *= -1
else:
already_seen.append(abs(item))
return already_seen
def main():
# Check all the study cases
for ix, ex in enumerate(examples):
out = solve(ex)
assert out == ex['result'], \
'Wrong result for example {} ({}, should be {})'.\
format(ix+1, out, ex['result'])
print('Success!\n')
if __name__=='__main__':
main()
| true |
0e22de1ec890cf31a9ee06053a8e9e7e06e235d5 | projectPythonator/portfolio | /ProjectEuler/Python/p4.py | 1,139 | 4.125 | 4 |
def is_palindrome(num):
return (str(num) == str(num)[::-1])
def sol2(limit):
largest = 0
a = 999
lim = 100
while lim <= a:
b = 999
while a <= b:
ab = a*b
if ab < largest:
break
if is_palindrome(ab):
largest = ab
b -= 1
a -= 1
print('largest palindrone of three digit multile below {} is {}'.format(limit, largest))
def make_palin(fh):
return int(str(fh) + str(fh)[::-1])
def sol3(limit):
'''improved version studying from other solutions'''
found = False
first_half = 998
palin = 0
factors = [0]*2
while not found:
first_half -= 1
palin = make_palin(first_half)
i = 999
while i > 99:
if (palin // i) > 999 or i*i < palin:
break
if 0 == palin%i:
found = True
factors[0] = palin // i
factors[1] = i
break
i -= 1
print('largest palin drome of 3 digits is {}'.format(palin))
def main():
sol3(1000)
sol2(1000)
main()
| true |
78e7ebb88d26be732ccf0d5cdf68d1ace21449fa | JJWren/Python_UniversityStudyGroup_ConsoleApps | /pythonGraphicPrograms/drawObjectsTest.py | 941 | 4.125 | 4 | import graphics
from graphics import *
def main():
print("\n***** Graphics Test *****\n")
print("This program generates a window\nwith some shapes drawn in.\n")
# Open a graphics window
win = graphics.GraphWin('Shapes')
# Draw a red circle centered at point (100, 100) with radius 30
center = Point(100, 100)
circ = Circle(center, 30)
circ.setFill('red')
circ.draw(win)
# Put a textual label in the center of the circle
label = Text(center, "Red Circle")
label.draw(win)
# Draw a square using a Rectangle object
rect = Rectangle(Point(30, 30), Point(70, 70))
rect.draw(win)
# Draw an oval using the Oval object
oval = Oval(Point(20, 150), Point(180, 199))
oval.draw(win)
# Wait for the user input to terminate the program
input("Press any key to terminate the program")
print("\n***** End of Program *****\n")
if __name__ == '__main__':
main()
| true |
4fa3c4eef05f5c4bd508b40bcde7c34aab5c7f0f | gurhanPro/Interview_questions_python | /array_manipulation.py | 1,669 | 4.3125 | 4 | """ Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in your array.
For example, the length of your array of zeros
. Your list of queries is as follows:
a b k
1 5 3
4 8 7
6 9 1
Add the values of k between the indices a and b inclusive:
index-> 1 2 3 4 5 6 7 8 9 10
[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0]
The largest value is 10 after all operations are performed.
Function Description
Complete the function arrayManipulation in the editor below. It must return an integer, the maximum value in the resulting array.
arrayManipulation has the following parameters:
n - the number of elements in your array
queries - a two dimensional array of queries where each queries[i] contains three integers, a, b, and k.
"""
def arrayManipulation(n, d):
arr = [0]*(n+2) # initializing my empty array with zeroes, n+2 is to avoid array of out range later when I am updating
for a in d:
# initializing the first index and last plus one index further of the range, and then the value
first ,last,value= a[0] ,a[1]+1,a[2]
# updating the start index which is i and end index which is k+1
arr[first]+=value
arr[last] = arr[last]-value
# converting the array to prefix sum
for i in range(1,len(arr)-1):
arr[i] = arr[i] + arr[i-1]
return max(arr)
| true |
0bb193c09a34cbee9919ab598d8bcd91842bccad | Simiopolis/exercises | /reddit_dailyprogrammer/challenge_1_difficult.py | 862 | 4.125 | 4 | # Objective:
# we all know the classic "guessing game" with higher or lower prompts.
# lets do a role reversal; you create a program that will guess numbers
# between 1-100, and respond appropriately based on whether users say that
# the number is too high or too low. Try to make a program that can guess
# your number based on user input and great code!
# Link:
# http://www.reddit.com/r/dailyprogrammer/comments/pii6j/difficult_challenge_1/
import random
roof_num=100
floor_num=1
while(1):
num_guess = random.randint(floor_num,roof_num)
is_right = raw_input("Is your number " + str(num_guess) + "? (type y/n)")
if is_right is 'y':
break
else:
is_high_or_low = raw_input(
"Is the guess too high or low?(type h/l)")
if is_high_or_low is 'h':
roof_num = num_guess
else:
floor_num = num_guess
print "Your number is " + str(num_guess)
| true |
0e6734de8f1b69456245db2093565f394b336064 | ShivaGanapathy/PascalsTriangleGenerator | /PascalsTriangle.py | 2,247 | 4.375 | 4 | '''
create a program that will result in an output of n rows of Pascal's Triangle
ex. if n is 3 the out put should look like this:
1
1 1
1 2 1
'''
def get_input():
"""
This Function handles the user input process, ensuring that the user enters an positive integer.
The Function has no arguments and returns an integer that the user enters.
"""
#this while loops ensures the user enters an input
inputFetched = False
while inputFetched == False:
#this try-except statement validates the entry of a string
try:
n = int(input("How many rows of Pascal's Triangle do you need?"))
#this if block validates the number inputted is positive
if n <0:
print("Please enter a positive number")
else:
inputFetched = True
return n
except:
print("Please enter a number")
def populateList(n):
'''
This function populates a list of lists, each list containing a row of Pascal's Triange
The function expects a positive integer, n, and returns n rows of Pascal's Triangle
'''
allRows = []
#if no rows are wanted, the function returns an empty list
if n == 0 :
return allRows
for rowNumber in range(1,n+1):
#rowList stores all numbers in each row of the Triangle. It is initalized with a 1
rowList = [1,]
#if the current row is one, the else code is Not Applicable
if rowNumber == 1:
pass
else:
#stores the previous row of the triangle in previousRow
previousRow = allRows[rowNumber-2]
for i in range(len(previousRow)):
#if there are no new numbers to add, end loop
if i == len(previousRow)-1:
break
#adds two numbers and appends it to new row
else:
sumNumber= previousRow[i] + previousRow[i+1]
rowList.append(sumNumber)
#after end of adding numbers, add an aditional 1
rowList.append(1)
#adds row to list of rows after the new row is formed
allRows.append(rowList)
return allRows
def prettyPrint(array):
'''
This function takes a list of lists, and prints in a nicer, more readable and triangular manner
'''
size = len(array)
for i in range(len(array)):
space = " "
print((size-i)*space, array[i], (size-i)*space)
def main():
n = get_input()
data = populateList(n)
prettyPrint(data)
main()
| true |
ab04240722c919c0951f3619a7743ec7e51ad9b8 | Abulero/Sorting-Algorithms | /SelectionSort.py | 422 | 4.1875 | 4 | def selection_sort(numbers):
for i in range(len(numbers)):
for index in range(len(numbers) - i):
if numbers[index + i] < numbers[i]:
swap(numbers, index + i, i)
def swap(numbers, a, b):
numbers[a], numbers[b] = numbers[b], numbers[a]
if __name__ == '__main__':
numbers = [17, 41, 5, 22, 54, 6, 29, 3, 13]
print(numbers)
selection_sort(numbers)
print(numbers) | true |
63408a0a5e0bb8a9532957f0bacea05370a46753 | anuragpatil94/Python-Practice | /cracking-the-coding-interview/StacksAndQueues/3.3_StackOfPlates.py | 2,654 | 4.15625 | 4 | """
Stack of Plates:
Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold.
Implement a data structure SetOfStacks that mimics this.
SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity.
SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is, pop () should return the same values as it would if there were just a single stack).
FOLLOW UP Implement a function popAt ( int index) which performs a pop operation on a specific sub-stack.
"""
class StackOfPlates:
def __init__(self, n):
"""n is the height of stack"""
self.masterStack = []
self.stackHeight = 0
self.capacity = n
def _createStack(self):
self.masterStack.append([])
pass
def _isEmpty(self):
if not len(self.masterStack):
return True
return False
def _stackPacked(self):
if not self._isEmpty() and len(self.masterStack[-1]) == self.capacity:
return True
return False
def push(self, data):
if self._isEmpty() or self._stackPacked():
self._createStack()
self.masterStack[-1].append(data)
self.stackHeight += 1
def pop(self):
if len(self.masterStack[-1]) == 0:
self.masterStack.pop()
element = self.masterStack[-1].pop()
self.stackHeight -= 1
return element
def popAt(self, index):
""" Considering Index from 1 to number of Stacks"""
index = index - 1
if index > len(self.masterStack):
print("Stack Number should be less than Number of Stacks")
return
if len(self.masterStack[index]) == 0:
print("The Stack is Already Empty")
return
self.masterStack[index].pop()
self.stackHeight -= 1
def show(self):
print(self.masterStack)
if __name__ == "__main__":
s = StackOfPlates(5)
s.push(1)
s.push(1)
s.push(1)
s.push(1)
s.push(1)
s.show()
s.pop()
s.show()
s.push(1)
s.push(1)
s.show()
s.pop()
s.show()
s.push(1)
s.push(1)
s.push(1)
s.push(1)
s.push(1)
s.push(1)
s.push(1)
s.show()
print(s.stackHeight)
s.popAt(2)
s.show()
print(s.stackHeight)
s.popAt(3)
s.popAt(3)
s.popAt(3)
| true |
e08f6a2482e6bf944979357d204e771a706a4e26 | anuragpatil94/Python-Practice | /cracking-the-coding-interview/ArraysAndStrings/CTCI_01_IsUnique.py | 738 | 4.1875 | 4 | """
Is Unique: Implement an algorithm to determine if a string has all unique characters.
What if you cannot use additional data structures?
My Solution With additional data structure
- using set to check if a duplicate character exists
"""
class Solution:
def isUnique(string):
"""
- Book Solution
Time Complexity: O(n)
Space Complexity: O(1)
"""
vector = 0
for char in string:
charInt = ord(char)
if vector & 1 << charInt > 0:
return False
vector |= 1 << charInt
print(bin(vector))
return True
if __name__ == "__main__":
s = Solution
Solution.isUnique("abce")
| true |
8d5c88069762040ae079b394dd8edb7be0b4d51e | anuragpatil94/Python-Practice | /cracking-the-coding-interview/LinkedList/2.5_SumLists.py | 2,976 | 4.3125 | 4 | import sys
sys.path.insert(0, "../../")
from conceptual.linked_list import LinkedList
"""
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 two numbers
and returns the sum as a linked list.
Repeat if the digits are stored in forward order.
"""
def sumListsBackward(l1, l2):
""" This function takes 2 lists comprising of a number
7 -> 1 -> 6 617
5 -> 9 -> 2 295
and adds them to 2 -> 1 -> 9 912
Time Complexity O(n),
Space Complexity O(n) can be changed to O(1) if output is saved in one of the linkedlist
"""
carry = 0
output = LinkedList()
while l1 is not None or l2 is not None:
l1digit = 0 if l1 is None else l1.data
l2digit = 0 if l2 is None else l2.data
remainder = (l1digit + l2digit + carry) % 10
carry = (l1digit + l2digit + carry) // 10
output.push(remainder)
l1 = l1.next if l1 is not None else None
l2 = l2.next if l2 is not None else None
if l1 is None and l2 is None and carry > 0:
output.push(carry)
return output
def sumListsForward(l1, l2):
""" This function takes 2 lists comprising of a number
7 -> 1 -> 6 716
5 -> 9 -> 2 592
and adds to 1 -> 3 -> 0 -> 8 1308
Time Complexity O(n),
Space Complexity O(n)
"""
l3 = LinkedList()
def _sumListsForward(l1, l2):
if l1 is None and l2 is None:
return 0
carry = _sumListsForward(l1.next, l2.next)
sumOfDigits = (l1.data + l2.data + carry) % 10
l3.push_front(sumOfDigits)
return (l1.data + l2.data + carry) // 10
l1size = l1.size()
l2size = l2.size()
if l1size < l2size:
for i in range(l2size - l1size):
l1.push_front(0)
if l1size > l2size:
for i in range(l1size - l2size):
l2.push_front(0)
carry = _sumListsForward(l1.head, l2.head)
if carry > 0:
l3.push_front(carry)
return l3
if __name__ == "__main__":
l1 = LinkedList()
l2 = LinkedList()
l1.push(7)
l1.push(1)
l1.push(6)
print("INPUT: ", l1.show())
l2.push(5)
l2.push(9)
l2.push(2)
print("INPUT: ", l2.show())
output = sumListsBackward(l1.head, l2.head)
print("OUTPUT: ", output.show())
l1 = LinkedList()
l2 = LinkedList()
l1.push(9)
l1.push(7)
l1.push(9)
print("INPUT: ", l1.show())
l2.push(2)
l2.push(1)
print("INPUT: ", l2.show())
output = sumListsForward(l1, l2)
print("OUTPUT: ", output.show())
| true |
9db68315acd436a621caa8bf8ccf8f2dd1ddfaeb | anuragpatil94/Python-Practice | /cracking-the-coding-interview/LinkedList/2.6_Palindrome.py | 1,656 | 4.375 | 4 | import sys
sys.path.insert(0, "../../")
from conceptual.linked_list import LinkedList
"""
Important
2.6: Palindrome
Implement a function to check if the linked list is the palindrome
Solution:
- Get the Middle Element in Recursion
- using the (length - 2) in the recussion which will make sure
when length is 0 the current_node will reach the middle for an even size Linkedlist and
when length is 1 the current_node will reach the middle for an odd size Linkedlist
- Class Result - This is used to return 2 values and to update the values easily in the recursion.
"""
class Result:
def __init__(self, node, isPalindrome):
self.node = node
self.isPalindrome = isPalindrome
def __str__(self):
return "node:" + self.node.data + ", isPalindrome:" + str(self.isPalindrome)
def checkPalindrome(l, size):
current = l.head
result = _isPalindrome(current, size)
return result.isPalindrome
def _isPalindrome(current, length):
if length == 0:
return Result(current, True)
elif length == 1:
return Result(current.next, True)
result = _isPalindrome(current.next, length - 2)
if not result.isPalindrome or result.node == None:
return result
result.isPalindrome = result.node.data == current.data # Returns False if not equal
result.node = result.node.next
return result
if __name__ == "__main__":
l = LinkedList()
l.push("A")
l.push("B")
l.push("C")
l.push("B")
l.push("A")
l.show()
print(checkPalindrome(l, 5))
| true |
f31269622691bb450c41d584b36b206670658d56 | anuragpatil94/Python-Practice | /OnlineAssessmentQuestions/N16_FindPairWithGivenSum.py | 1,166 | 4.15625 | 4 | """
Given a list of positive integers nums and an int target, return indices of the two numbers such that they add up to a target - 30.
Conditions:
You will pick exactly 2 numbers.
You cannot pick the same element twice.
If you have muliple pairs, select the pair with the largest number.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
"""
PseudoCode:
Initialize a empty dictionary
for each number in the list
if target-num is in the dictionary
return the index of target-mun and index of num
else
add num to dictionary as key and index of num as value
"""
class Solution:
def twoSum(self, nums, target: int):
""" The Time Complexity of this algorithm is O(n) and the Space Complexity is O(n) """
# This stores the new number which was traversed in the loop with its index as value
x = {}
if not len(nums):
return None
for idx, num in enumerate(nums):
if (target - num) in x:
return [x[target - num], idx]
else:
x[num] = idx
return None
| true |
4123ec6a578d0e18c1a1a983334dd43c89dab311 | anuragpatil94/Python-Practice | /interview-questions/find_nth_smallest_in_the_set.py | 2,569 | 4.125 | 4 | """
Find the Nth Order Statistic for a given array of numbers
Steps :
Find the Smallest Number -
this is straightforward O(n),
Find 2nd Smallest Number -
Brute Force - Find Minimum - swap with 1st element - then again loop the remainder to find 2nd shortest - O(n**2)
Best Possible - Have two index - 1st will store the minimum, 2nd will store the 2nd min and them comparing them with rest of the list and comparing with each other. O(n)
Find Nth Smallest -
Take any element and place it in its correct position.
Comapare this position with N if N is smaller recurse 1st half else 2nd half.
Time Complexity : O(n)
Time Analysis:
This uses partition logic of quicksort algorithm.. which is done in O(n) time. In our case everytime the lookup for array becomes half the previous size considering Average Case.
Hence, the series of going through the array is like n + n/2 + n/4 + n/8 + n/16 .... which become (n).
Space Complexity: O(1)
"""
def findShortestInList(arr):
min = arr[0]
for num in arr[1:]:
if num < min:
num, min = min, num
return min
def findSecondShortestInList(arr):
min1 = arr[0]
min2 = arr[1]
for index in enumerate(arr[2:], start=2):
if arr[index] < min2:
arr[index], min2 = min2, arr[index]
elif arr[index] < min1:
arr[index], min1 = min1, arr[index]
if min2 < min1:
min1, min2 = min2, min1
return min2
def findNthShortestInList(arr, n):
position = partition(arr)
if n < position:
return findNthShortestInList(arr[:position], n)
elif n > position:
return findNthShortestInList(arr[position:], (n - position))
else:
return arr[position]
def partition(arr):
l = len(arr)
if l > 1:
pivot = arr[l - 1]
position = 0
for number in range(0, l - 1):
if arr[number] <= pivot:
arr[position], arr[number] = arr[number], arr[position]
position += 1
arr[position], arr[l - 1] = arr[l - 1], arr[position]
return position
if __name__ == "__main__":
arr = [4, 7, 2, 9, 1, 10, 45, 21, 15, 31, 13, 41, 14, 68, 18]
print(arr)
min = findShortestInList(arr) # O(n)
print(min)
arr = [4, 7, 2, 9, 1, 10, 45, 21, 15, 31, 13, 41, 14, 68, 18]
min = findSecondShortestInList(arr) # O(n)
print(min)
arr = [4, 7, 2, 9, 1, 10, 45, 21, 15, 31, 13, 41, 14, 68, 18]
n = 10
min = findNthShortestInList(arr, n - 1) # O(n)
print(min)
| true |
34678fcd907333314101b255a796553ea1c33ff9 | nileshsharma-cloud/PythonProjects | /pythonExamples/loopExamples.py | 345 | 4.34375 | 4 | names = ['Nilesh', 'Ashesh', 'Ashwani']
month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
for i in names:
invite = "Hi " + i + "! Please come to my party."
print(invite)
for i in month:
month_names = "Hi!!! This month is : "+i
print(month_names) | false |
83f85fdf1c3bc565f34406e38bb459000e27d864 | Luke-Callaghan23/Synonyms | /find_synonyms/scripts/clean_word.py | 554 | 4.15625 | 4 | from functools import reduce
def clean_word (word):
word = word.strip().lower() # step 1: remove excess spaces and turn to lower case
word = reduce ( # step 2: split the word on all spaces and only keep the longest one
lambda acc, word: ( # (sometimes the api will return words like 'blahblah (of)'
acc # and we'll want to strip the '(of)' )
if len(acc) > len(word)
else word
),
word.split(),
''
)
print(word)
return word | true |
2521f29cf2a56ef7ceab46a579f918ad465a50ec | xieqing181/Pythonwork-Chapter9 | /Admin.py | 1,818 | 4.28125 | 4 | class User():
'''save the user's first name, last name, and middle name,
also some other info, like height, weight, and username.'''
def __init__(self, first, last, height,
weight, username, middle=''):
self.first = first
self.last = last
self.height = height
self.weight = weight
self.username = username
self.middle = middle
def describe_user(self):
print("Here are some basic info about this user:\n")
print("First name: " + self.first.title())
print("Middle name: " + self.middle.title())
print("Last name: " + self.last.title())
print("Hight: " + str(self.height) + " cm")
print("Weight: " + str(self.weight) + " kg")
def greet_user(self):
print("Hello, " + self.first.title() + self.last.title() + " !")
class Admin(User):
'''create an new son-class named Admin,
def a function to show privileges of Admin'''
def __init__(self, first, last, height,
weight, username, middle='', *privileges):
super().__init__(first, last, height,
weight, username, middle)
self.privileges = privileges
def show_privileges(self):
print("Welcome Admin! You can access to: ")
for privilege in self.privileges:
print(" - " + privilege.upper())
user1 = User('qing', 'xie', 181, 70, 'mine99')
user2 = User('jason', 'king', 178, 80, 'hero', 'william')
user3 = User('lily', 'Mosion', 165, 65, 'lilxx\'s ok', 'elisabinsh')
admin1 = Admin('adam', 'joson', 180, 90, 'nickich', 'morris',
'read', 'write', 'edit')
user1.describe_user()
user1.greet_user()
print("********************************")
user2.describe_user()
user2.greet_user()
print("********************************")
user3.describe_user()
user3.greet_user()
print("********************************")
admin1.describe_user()
admin1.greet_user()
admin1.show_privileges()
print("********************************")
| true |
df436d40ab69118a77486626781563eb5d2fa844 | PythPeri2017/PyProgFall2017 | /pitonozavr/l11/racing.py | 1,341 | 4.3125 | 4 | # Описываем участников - скорость, нитро, бак, расход топлива, пройденный путь,
# имя.
# На выбор: обычная скорость, нитро - расход топлива 3x - каждый ход
# Побеждает тот, кто приехал первый, либо тот, у кого позже закончилось
# топливо.
def eezzzee(car):
car["distance"] += car["speed"]
car["fuel"] -= car["expen"]
def neeetrooo(car):
car["distance"] += car["nitro"]
car["fuel"] -= car["expen"] * 3
def stats(car):
print("\nТекущее состояние:",
"Топливо: " + str(car["fuel"]),
"Расстояние: " + str(car["distance"]) + "/" + str(track),
sep = "\n"
)
def step(car):
choose = input("Твой ход, " + car["name"] +
". Что будем делать?\n" +
"1 - Просто едем\n" +
"2 - топиим!!\n"
)
if choose == "1":
eezzzee(car)
elif choose == "2":
neeetrooo(car)
else:
print("Ты ошибся!")
stats(car)
input()
track = 50
car1 = {
"name": "Бэтмобиль",
"speed": 6,
"fuel": 35,
"expen": 3,
"nitro": 11,
"distance": 0
}
car2 = {
"name": "Черная молния",
"speed": 8,
"fuel": 30,
"expen": 4,
"nitro": 13,
"distance": 0
}
while True:
step(car1)
step(car2) | false |
d4c47fd2f50219fab61b8e311875e3988de33575 | toralero/PyRes | /5/errorhandling.py | 337 | 4.25 | 4 | while True:
try:
age = int(input("What is your age?: "))
except ValueError:
print("Age has to be an integer.")
print("Please answer the question again.")
print()
continue
else:
break
if age < 18:
print("You are still not an adult.")
else:
print("You are an adult!")
| true |
bf64c7fd11d3fe7626b2498e708bad6d9a30741a | toralero/PyRes | /3/listinlist.py | 881 | 4.5 | 4 | # A class of students
class_a = ["Edward", "Sally", "Oscar", "Ana"]
class_b = ["Steve", "Julius", "Jenny", "Stacey"]
class_c = ["Aubrey", "Kyle", "Bob", "Velma"]
# A year with multiple classes
year_3 = [class_a, class_b, class_c]
# A year directly
year_3 = [["Edward", "Sally", "Oscar", "Ana"],
["Steve", "Julius", "Jenny", "Stacey"],
["Aubrey", "Kyle", "Bob", "Velma"]]
# Accessing the Classes
print("A Class with year_3[0]:", year_3[0])
print("B Class with year_3[1]:", year_3[1])
print("C Class with year_3[2]:", year_3[2])
print("-------")
# Accessing Jenny
print("Jenny is in class B, which is year_3[1]")
print("Jenny is the third element of class B")
print("year_3[1][2] =", year_3[1][2])
# Accessing Aubrey
print("Aubrey is in class C, which is year_3[2]")
print("Aubrey is the first element of class C")
print("year_3[2][0] =", year_3[2][0])
| false |
b261320bc145ee14419755e8cc3c316e779a7248 | alhanoufN97/Python | /W5L30.py | 371 | 4.21875 | 4 | print("Range #1 : ")
for x in range(9) :
print(x)
print("Range #2 : ")
for x in range(3,9) :
print(x)
print("Range #3 : ")
for x in range(3,20 , 15) :
print(x)
print("Range #4 : ")
for x in range(3) :
print(x)
else :
print("Final loop ")
Digital = ["A","B","C" , "D"]
Num = [1,2,3,4,5]
for x in Digital :
for y in Num :
print(x,y)
| false |
80599480442c344e02401dc5991c1cb2862e7460 | Despaquitoe/Guisa_story | /2.py | 302 | 4.25 | 4 | # Write a program that will ask the user what their age is and then
# determine if they are old enough to vote or not and respond appropriately
ask=input("How old are you?")
elif ask >= int(18):
print=("What a little youngster")
if (18-100):
print=("Would you like to vote?")
int()
| true |
c2449b9d45fecd27e6872e9a05e1ea7381998c8e | PriraRoja/python_training | /day1/matrix.py | 365 | 4.1875 | 4 | row = int(input("Enter the no of rows:"))
col = int(input("Enter the no of columns:"))
mat = []
print("Enter the numbers:")
for i in range(row):
a =[]
for j in range(col):
a.append(int(input()))
m.append(a)
for i in range(row):
for j in range(col):
print(mat[i][j], end = " ")
print() | false |
6936bac435aad77d243c975a2295281ab90e65f4 | rosemary-c/codingDojo | /python/printListType.py | 1,169 | 4.28125 | 4 | '''
Assignment: Type List
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type.
If the item is a string, concatenate it onto a new string.
If it is a number, add it to a running sum.
At the end of your program print the string, the number and an analysis of what the array contains.
If it contains only one type, print that type, otherwise, print 'mixed'.
Here are a couple of test cases. Think of some of your own, too. What kind of unexpected input could you get?
'''
def printList(input):
sum = 0
stringConcat = ""
listType = ""
for elem in input:
if int == type(elem):
sum += elem
listType = "int"
elif str == type(elem):
stringConcat += elem
listType = "string"
if (len(stringConcat) != 0) & (sum != 0):
listType = "mixed"
print sum
print stringConcat
print listType
print "\n"
printList([1, 10, "cat", "dog", 100])
printList([1,2,3,4,5,6])
printList(["a", "b", "c", "dd"])
| true |
a934712e523a820f64e266beb891d660feeb367b | sunnychemist/pylearn | /python_tutor/07_lists/rank.py | 1,119 | 4.34375 | 4 | def rank_position(list_u, x):
"""
Source https://pythontutor.ru/lessons/lists/problems/lineup/
Condition
Petya moved to another school. In a physical education lesson,
he needed to determine his place in the ranks. Help him do this.
The program receives a non-increasing sequence of natural numbers,
which means the growth of each person in the system.
After that, enter the number X - Petit's growth.
All numbers in the input are natural and do not exceed 200.
Print the number under which Petya should stand in line.
If there are people in the ranks with the same height,
the same as Petya, then he must get up after them.
"""
list_u.sort()
rank = []
i = 0
while list_u:
if len(list_u) == i:
break
if list_u[i] < x < list_u[i + 1] or list_u[i] == x:
rank.append(list_u[i])
rank.append(x)
position = len(rank)
else:
rank.append(list_u[i])
i += 1
print(rank, position)
rank_position([145, 150, 140, 142, 151, 139], 141)
| true |
0b6698b58ff23e2f5cc88d36ad2e7f26cd67b847 | IvanDanyliv/python | /lab7_4.py | 220 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def encryption(expression: str) -> str:
lst = list(map(lambda x: chr(ord(x) + 1), expression))
return ''.join(lst)
print(encryption(input("Input your string: ")))
| false |
dfdca5d2079d4ef7bf0b00f2638511769a5c0cda | qiubite31/Leetcode | /Tree/leetcode-872.py | 1,507 | 4.28125 | 4 | """
872. Leaf-Similar Trees
Difficulty: Easy
Related Topic: Tree, Recursive
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Note:
Both of the given trees will have between 1 and 100 nodes.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
def traversal(leaf, root):
if root is None:
return None
if root.left is None and root.right is None:
leaf.append(root.val)
traversal(leaf, root.left)
traversal(leaf, root.right)
return leaf
return traversal([], root1) == traversal([], root2)
root = TreeNode(5)
root.left = TreeNode(2)
root.right = TreeNode(13)
root2 = TreeNode(5)
root2.left = TreeNode(1)
# root2.right = TreeNode(2)
root2.left.left = TreeNode(2)
root2.left.right = TreeNode(13)
solution = Solution()
output = solution.leafSimilar(root, root2)
print(output)
| true |
cbcc8e3955cecdbf3d5bdacb6a8b4cbae8b6ba6b | qiubite31/Leetcode | /Hash/leetcode-500.py | 1,268 | 4.125 | 4 | """
500. Keyboard Row
Difficulty: Easy
Related Topic: Hash Table
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
American keyboard
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
"""
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
KEYBOARD_MAP = dict(zip(list("qwertyuiopasdfghjklzxcvbnm"), list("11111111112222222223333333")))
same_row_words = []
for word in words:
line_loc = KEYBOARD_MAP[word[0].lower()]
row_flag = True
for char in word:
if not KEYBOARD_MAP[char.lower()] == line_loc:
row_flag = False
break
if row_flag:
same_row_words.append(word)
return same_row_words
words = ["Hello", "Alaska", "Dad", "Peace"]
solution = Solution()
output = solution.findWords(words)
print(output)
| true |
d4e3e9bbe62976988977347d81510912dd0b767f | aratik711/100-python3-programs | /92.py | 602 | 4.1875 | 4 | """
Manage a game player's High Score list.
Your task is to build a high-score component of the classic Frogger game, one of the highest selling and addictive games of all time, and a classic of the arcade era. Your task is to write methods that return the highest score from the list, the last added score and the three highest scores.
"""
def highest(scores):
return max(scores)
def last_added(scores):
return scores[-1]
def top_three(scores):
return sorted(scores, reverse=True)[:3]
scores = [45,62,12,78,4]
print(highest(scores))
print(last_added(scores))
print(top_three(scores)) | true |
76c486ecc32a8632f9d39a8fc6c375dd933ae707 | aratik711/100-python3-programs | /48.py | 316 | 4.34375 | 4 | """
Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.
"""
class Circle(object):
def __init__(self, radius = 0):
self.radius = radius
def area(self):
return self.radius**2*3.14
circle = Circle(5)
print(circle.area()) | true |
24477e86ca72c6bbd3285942d61766633f0fc845 | aratik711/100-python3-programs | /94.py | 1,065 | 4.3125 | 4 | """
Your body is made up of cells that contain DNA. Those cells regularly wear out and need replacing, which they achieve by dividing into daughter cells. In fact, the average human body experiences about 10 quadrillion cell divisions in a lifetime!
When cells divide, their DNA replicates too. Sometimes during this process mistakes happen and single pieces of DNA get encoded with the incorrect information. If we compare two strands of DNA and count the differences between them we can see how many mistakes occurred. This is known as the "Hamming Distance".
We read DNA using the letters C,A,G and T. Two strands might look like this:
GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^ ^ ^ ^^
They have 7 differences, and therefore the Hamming Distance is 7.
The Hamming Distance is useful for lots of things in science, not just biology, so it's a nice phrase to be familiar with :)
"""
def hammingDistance(dna1, dna2):
return sum(i!=j for i,j in zip(dna1,dna2))
dna1 = "GAGCCTACTAACGGGAT"
dna2 = "CATCGTAATGACGGCCT"
print (hammingDistance(dna1, dna2))
| true |
752c24c84d3e8b266dcbb5fcd71ff0fb184f83db | keishi25/work-codes | /class/classmethod.py | 1,199 | 4.21875 | 4 | """
classmethod使用方法
メリット:クラスから直接メソッドを呼べる(クラスをインスタンス化する必要なし)
使われるケース:メソッドの処理とそれに基づいて変更されたインスタンス変数にアクセスできる
"""
# classmethodを使用しないケース
class Item1:
def __init__(self, id, name):
self.id = id
self.name = name
def retrieve_item(id):
data = {"name":"taka"}
return Item1(id, data["name"])
# classmetodを使用するケース
class Item2:
def __init__(self, id, name):
self.id = id
self.name = name
@classmethod
def retrieve_item(cls, id):
data = {"name": "taka"}
return cls(id, data["name"]) # コンストラクタに引数が渡される
if __name__ == '__main__':
# classmethodを使用しないケース
# moduleのインストールは、Item1とretrieve_itemの二つ
out = retrieve_item(2)
print(out.id)
print(out.name)
# classmetodを使用するケース
# moduleのインストールは、Item2のクラスだけで良い
out = Item2.retrieve_item(2)
print(out.id)
print(out.name)
| false |
660bac6a3ee2b739922073a0ea59f5fdf0086371 | romulogm/EstudosPython | /cursoUSP/ordenacao.py | 327 | 4.15625 | 4 | def main():
num1 = float(input("Insira um número: "))
num2 = float(input("Insira um número: "))
num3 = float(input("Insira um número: "))
if (num1) < (num2) and (num2) < (num3) or num1 < 0 and num1 > num2 > num3:
print ("crescente")
else:
print ("não está em ordem crescente")
main()
| false |
87346f0af31de16e7e808a7379cbc73bdd42c5d6 | JunDang/MIT-Python | /CreditCard1.py | 994 | 4.125 | 4 | '''
Monthly interest rate= (Annual interest rate) / 12.0
Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
'''
def CreditCard(balance, annualInterestRate, monthlyPaymentRate):
MonthlyInterestRate = annualInterestRate / 12.0
totalPaid = 0
for i in range(1, 13):
MinimumMonthlyPayment = monthlyPaymentRate * balance
monthlyUnpaidBalance = balance - MinimumMonthlyPayment
balance = monthlyUnpaidBalance + MonthlyInterestRate * monthlyUnpaidBalance
totalPaid = totalPaid + MinimumMonthlyPayment
print "Month: " + str(i)
print "Minimum monthly payment: " + str("%.2f" % MinimumMonthlyPayment)
print "Remaining balance: " + str("%.2f" % balance)
print "Total paid: " + str("%.2f" % totalPaid)
print "Remaining balance: " + str("%.2f" % balance)
CreditCard(4213, 0.2, 0.04)
| true |
9d813ebf826f742a7c2027836a2cb0d64a7118b9 | markwang922/markwang922 | /Python/Test/copylist.py | 295 | 4.15625 | 4 | # 题目:将一个列表的数据复制到另一个列表中。
# -*- coding: utf-8 -*-
def copy_list(arg):
list_in = []
for i in arg:
list_in.append(i)
return list_in
if __name__ == '__main__':
list1 = [1, 2, 4, 5, 3]
list2 = copy_list(list1)
print(list2) | false |
5c1dccfbf85eb8a5f44bee2c55affd997ccec8ba | dileepachuthan/Python-Exercise | /Exercise_9.py | 1,140 | 4.21875 | 4 | Pretend that you have just opened a new savings account that earns 4 percent interest per year. The interest that you earn is paid at the end of the year, and is added
to the balance of the savings account. Write a program that begins by reading the amount of money deposited into the account from the user. Then your program should
compute and display the amount in the savings account after 1, 2, and 3 years. Display each amount so that it is rounded to 2 decimal places
r = 4
y = int(input("enter year:"))
if y>3:
print("Error!")
for i in range(y):
if y == 1:
n = int(input("Enter Amount:"))
p = n*y*r/100
n = n+p
print("Principal is:",p)
print("Savings in 1 year is:{:.2f}".format(n))
pass
y = int(input("enter year:"))
if y == 2:
p = float(n*y*r/100)
print("Principal is:",p)
n = n+p
print("Savings in 2 years is:{:.2f}".format(n))
pass
y = int(input("enter year:"))
if y == 3:
p = float(n*y*r/100)
print("Principal is:",p)
n = n+p
print("Savings in 3 years is:{:.2f}".format(n))
| true |
f6276c8a2b723d2c37dbf1a3e21592a4b4d8492a | Divyansh-03/PythoN_WorK | /Denomination.py | 521 | 4.125 | 4 | ''' A cashier has currency notes of denominations 10, 50 and
100. If the amount to be withdrawn is input through the
keyboard in hundreds, find the total number of currency notes
of each denomination the cashier will have to give to the
withdrawer. '''
amount = int(input(" Enter the Total Amount in Hundreds "))
notes_in_10 = amount/10
notes_in_50 = amount/50
notes_in_100 = amount/100
print(" Notes of 10Rs. " + str(notes_in_10) + "\n Notes of 50Rs. " + str(notes_in_50) + "\n Notes of 100Rs. " + str(notes_in_100) ) | true |
3173330493eb58230febd9caeee826a2cd2dff52 | Divyansh-03/PythoN_WorK | /distance.py | 456 | 4.40625 | 4 | ''' The distance between two cities (in km.) is input through the
keyboard. Write a program to convert and print this distance
in meters, feet, inches and centimeters. '''
dist_km = float(input("Enter distance in kilometres" ))
print(" The distance in meters is " + str(dist_km*1000.0) + " The distance in feet is "+ str(dist_km*3280.84) + " The distance in inches is " + str(dist_km*39370.1) + " The distance in centimeters is " + str(dist_km*100000.0))
| true |
d0f94f29be1cc7a4f9d2708d6fbcf4870c768522 | Divyansh-03/PythoN_WorK | /Largest3.py | 1,089 | 4.375 | 4 | ''' Input any three number and display which one is largest according to
given situation and result;
n1 n2 n3 Output
5 5 5 All Three Are Equal
5 5 2 First and Second Number are Largest
5 2 5 First and Third Number are Largest
2 5 5 Second and Third Number are Largest
5 1 2 First Number is Largest
5 11 2 Second Number is Largest
1 3 5 Third Number is Largest '''
n1 = int(input(" Enter 1st number "))
n2 = int(input(" Enter 2nd number "))
n3 = int(input(" Enter 3rd number "))
if n1==n2 and n2==n3 :
print(" All Three are equal ")
else :
if n1==n2 and n1!=n3:
if n1>n3 :
print(" First and Second are Largest ")
else :
print(" Third is Largest ")
if n1==n3 and n3!=n2:
if n1>n2 :
print(" First and Third are Largest ")
else :
print(" Second is Largest ")
if n2==n3 and n1!=n2:
if n1>n2 :
print(" First is Largest ")
else :
print(" Second and Third are Largest ")
if n1!=n2 and n2!=n3 and n1!=n3:
if n1>n2 and n1>n3:
print(" First Largest ")
else :
if n1<n2 and n2>n3:
print(" Second Largest ")
else :
print(" Third Largest ")
| false |
f6060dbd91f4a1e6871a97fb2db1f46be5bb56a0 | Divyansh-03/PythoN_WorK | /4company.py | 935 | 4.21875 | 4 | ''' In a company, worker efficiency is determined on the basis of
the time required for a worker to complete a particular job. If
the time taken by the worker is between 2 – 3 hours, then the
worker is said to be highly efficient. If the time required by
the worker is between 3 – 4 hours, then the worker is ordered
to improve speed. If the time taken is between 4 – 5 hours, the
worker is given training to improve his speed, and if the time
taken by the worker is more than 5 hours, then the worker has
to leave the company. If the time taken by the worker is input
through the keyboard, find the efficiency of the worker. '''
time = int(input(" Input time in hours "))
if time>=2 and time<3:
print(" Worker is Highly Efficient ")
elif time>=3 and time<4:
print(" Worker is Ordered to Improve Speed ")
elif time>=4 and time<5:
print(" Worker is Trained to Improve Speed ")
else:
print(" Worker has to leave the company ") | true |
a22c2139f716074a184fac5f560fd2e98914cf72 | Divyansh-03/PythoN_WorK | /youngest.py | 920 | 4.15625 | 4 | ''' If the ages of Ram, Shyam and Ajay are input through the
keyboard, write a program to determine the youngest of the
three. '''
n1 = int(input(" Enter Ram's age "))
n2 = int(input(" Enter Shyam's age "))
n3 = int(input(" Enter Ajay's age "))
if n1==n2 and n2==n3 :
print(" All Three are of equal ages. ")
else :
if n1==n2 and n1!=n3:
if n1>n3 :
print(" Ajay is Youngest. ")
else :
print(" Ram and Shyam of equal ages and youngest. ")
if n1==n3 and n3!=n2:
if n1>n2 :
print(" Shyam is Youngest ")
else :
print(" Ram and Ajay are of equal ages and youngest. ")
if n2==n3 and n1!=n2:
if n1>n2 :
print(" Shyam and Ajay are of equal ages and youngest. ")
else :
print(" Ram is Youngest. ")
if n1!=n2 and n2!=n3 and n1!=n3:
if n1<n2 and n1<n3:
print(" Ram is Youngest. ")
else:
if n2<n3 and n2<n1:
print(" Shyam is Youngest. ")
else:
print(" Ajay is Youngest. ") | false |
2ca40ae8cb5255db3205a56d75f9da920f2d500a | brandonnorsworthy/ProjectEuler | /python/p004.py | 619 | 4.125 | 4 | #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
foundnumber = 0
for x in reversed(range(900,1000)):
for y in reversed(range(900,1000)):
number = x * y
#print(str(number)[0:3], ' r', str(number)[6:2:-1], ' x', x, ' y', y)
str1 = str(number)[0:3]
str2 = str(number)[6:2:-1]
if(str1 == str2):
foundnumber = number
break
if foundnumber != 0:
break
print(foundnumber) | true |
7fab1cd207ab3b2afc933d6e226c5c7ab9e78f01 | Vibhushit07/Python | /Case Studies/cs7.py | 611 | 4.40625 | 4 | '''
You are given a string that was encoded by a Caesar cipher with an unknown distance value.
The text can contain any of the printable ASCII characters.
Suggest an algorithm for cracking this code.
- Input Plain Text & its Cipher Text
- Output distance value d.
'''
def findDistance(cipherText, plainText):
if(ord(cipherText[0]) - ord(plainText[0]) > 0):
return (ord(cipherText[0]) - ord(plainText[0]))
else:
return 127 - (ord(plainText[0]) - ord(cipherText[0]))
print("Distance is: ", findDistance(input("Enter encrypted data: "), input("Enter plain text: "))) | true |
fd9f2e759e086f928e09ae35c1e089bdf8104c50 | Vibhushit07/Python | /Case Studies/cs5.py | 753 | 4.375 | 4 | '''
Write the encrypted text of each of the following words using a Caesar cipher with a distance value of 3:
a. python
b. hacker
c. wow
And then decrypt it also.
Write different scripts for encryption & decryption.
'''
def encrypt(string):
enc = ""
for i in string:
if ord(i) < 120:
enc += chr(ord(i) + 3)
else:
enc += chr(97 + (ord(i) - 120))
return enc
def decrypt(string):
dec = ""
for i in string:
if ord(i) > 99:
dec += chr(ord(i) - 3)
else:
dec += chr(120 + (ord(i) - 97))
return dec
enc = encrypt(input("Enter a string to encrypt: "))
print("Encypted data is: ", enc)
print("decypted data is: ", decrypt(enc)) | true |
3cfb8695374c6784e4d386f865f513d545814903 | David-Guri/python | /to-do-list.py | 1,254 | 4.125 | 4 | print(' ')
print('Hi, David!')
print('Welcome back to your to-do list')
thislist = ['Learn the basics of python', 'Learn the basics of vim', 'Play with PS4', 'Take a sh*t']
print('Number of items in your list: ' + str(len(thislist)))
print('Currently in your list are these items: ')
print(thislist)
newItem = input("Enter new item:")
print("Adding to the list: " + str(newItem))
if newItem:
thislist.append(str(newItem))
print(thislist)
else:
print('Sorry, I did not quite get that. Please try again!')
newItem = input("Enter new item:")
print("Adding to the list: " + str(newItem))
if newItem:
thislist.append(str(newItem))
print(thislist)
removeItem = input('Would you like to remove any items?')
if removeItem == 'yes' or 'Yes':
remove = input('Ok, which one?' )
if str(remove) in thislist:
thislist.remove(remove)
print(thislist)
else:
print('Sorry, I did not quite get that. Please try again!')
remove = input('Ok, which one?')
if str(remove) in thislist:
thislist.remove(remove)
print(thislist)
if removeItem == 'no' or 'No':
print('Ok.') | true |
eb93a34f3046548ebdff20a0817e6658b9bf52f3 | agiratech/yelp-review-text-analysis | /scripts/data_pre_processing.py | 790 | 4.15625 | 4 | import nltk,re
# strip the suffix # stemming
def stem(word):
regexp = r'^(.*?)(ing|ly|ed|ious|ies|ive|s|es|ment)?$'
stem, suffix = re.findall(regexp, word)[0]
return stem
raw = "There's a lot going on in this pipeline. To understand it properly, it helps to be clear about the type of each variable that it mentions. We find out the type of any Python object x using type(x), e.g. type(1) is <int> since 1 is an integer."
punctuation = re.compile(r'''[-.?!,":;()<>|0-9]''')
stop_words=['a','an' ,'the','of', 'is', 'this', 'in', 'there', 'on','it', 'to',"there's"]
# punctuation and numbers to be removed
# convert lower
# removing stop words
# tokenized
words = [stem(w).lower() for w in nltk.word_tokenize(punctuation.sub("", raw)) if w.lower() not in stop_words]
print words
| false |
38e4c254c0030c1771664c1e55c9dec2bc1d7fda | konstantinskorin/python_tasks | /Scripts/task_1.py | 556 | 4.125 | 4 | #!/usr/bin/env python
def my_dict(key,value):
while len(key)>len(value):
value.append('None') #добавляем значение 'None', если список key больше
return dict(zip(key, value)) #zip создает объект-итератор, из которого извлекается кортеж, состоящий из двух элементов - первый из списка key, второй из списка value
print(my_dict(['one', 'two', '3', 'Вася'],[1, 2, 3, 4, 5, 6, 7])) #зададим списки
| false |
95b555a7283f61d41194d216f2d807dabcc055dc | SumanSudhir/Automatic-Speech-Recognition-CS753 | /Assignment1/search.py | 1,067 | 4.3125 | 4 | '''
The function of this code is to search for given word when it is searched in FST
'''
import argparse
ap = argparse.ArgumentParser()
#ap.add_argument("--l_fst", type=str)
ap.add_argument("--words", type=str)
args = ap.parse_args()
input_txt = open("input.txt", 'r')
word_fst = open('word.fst', 'w')
word_fst.write(str(0) + " " + str(1) + " " +
args.words + " " + args.words + '\n')
word_fst.write(str(1) + '\n')
# l_dot_fst = open(args.l_fst, "r")
# lines = l_dot_fst.readlines()
# # print(lines[2][2])
# # print(l_dot_fst[0])
# # print(l_dot_fst[0])
#
# for i, words in enumerate(lines):
# # print(words.split()[3])
# if int(words.split()[0]) == 0 and words.split()[2] == args.words:
# phones = words.split()[3]
# print(phones)
#
# while(len(lines[i + 1].split()) > 1):
# # print("True")
# phones = phones + " " + (lines[i + 1].split())[3]
# i = i + 1
# #phones.append(lines[i + 1][3])
# # print("Hey")
# print(phones)
# l_dot_fst = open(args.l_fst, "r")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.