blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
637260eab712b7cca3c5f0f9e058fcd3639ffa96 | bqr407/PyIQ | /bubble.py | 1,671 | 4.15625 | 4 | class Bubble():
"""Class for bubble objects"""
def __init__(self, id, x, y, x2, y2, value):
"""each bubble object has these values associated with it"""
self.x = x
self.y = y
self.x2 = x2
self.y2 = y2
self.id = id
self.value = value
def getX(self):
"""returns x1 of tkinter shape"""
return self.x
def getY(self):
"""returns y1 of tkinter shape"""
return self.y
def getX2(self):
"""returns x2 pos of tkinter shape"""
return self.x2
def getY2(self):
"""returns y2 of tkinter shape"""
return self.y2
def getID(self):
"""returns unique object identifier"""
return self.id
def getValue(self):
"""returns value of the bubble"""
return self.value
class Choice():
"""Class for choice objects"""
def __init__(self, id, x, y, x2, y2, value):
"""each choice object has these values associated with it"""
self.x = x
self.y = y
self.x2 = x2
self.y2 = y2
self.id = id
self.value = value
def getX(self):
"""returns x1 of tkinter shape"""
return self.x
def getY(self):
"""returns y1 of tkinter shape"""
return self.y
def getX2(self):
"""returns x2 pos of tkinter shape"""
return self.x2
def getY2(self):
"""returns y2 of tkinter shape"""
return self.y2
def getID(self):
"""returns unique object identifier"""
return self.id
def getValue(self):
"""returns answer the object represents"""
return self.value | true |
a72b8412d9b2ca109436ac39d7dc3dcc021a8d75 | jsvn91/example_python | /eg/getting_max_from_str_eg.py | 350 | 4.15625 | 4 | # Q.24. In one line, show us how you’ll get the max alphabetical character from a string.
#
# For this, we’ll simply use the max function.
#
print (max('flyiNg'))
# ‘y’
#
# The following are the ASCII values for all the letters of this string-
#
# f- 102
#
# l- 108
#
# because y is greater amongst all y- 121
#
# i- 105
#
# N- 78
#
# g- 103
| true |
5935356da274001c362f979a7405c61f71cdef0b | Zhaokun1997/2020T1 | /comp9321/labs/week2/activity_2.py | 1,596 | 4.4375 | 4 | import sqlite3
import pandas as pd
from pandas.io import sql
def read_csv(csv_file):
"""
:param csv_file: the path of csv file
:return: a dataframe out of the csv file
"""
return pd.read_csv(csv_file)
def write_in_sqlite(data_frame, database_file, table_name):
"""
:param data_frame: the dataframe which must be written into the database
:param database_file: where the database is stored
:param table_name: the name of the table
"""
cnx = sqlite3.connect(database_file) # make a connection
sql.to_sql(data_frame, name=table_name, con=cnx, index=True)
def read_from_sqlite(database_file, table_name):
"""
:param database_file: where the database is stored
:param table_name: the name of the table
:return: a dataframe
"""
cnx = sqlite3.connect(database_file)
return sql.read_sql('select * from ' + table_name, cnx)
if __name__ == '__main__':
table_name = "Demographic_Statistics"
database_file = 'Demographic_Statistics.db' # name of sqlite db file that will be created
csv_file = 'Demographic_Statistics_By_Zip_Code.csv'
# read data from csv file
print("Reading csv file...")
loaded_df = read_csv(csv_file)
print("Obtain data from csv file successfully...")
# write data (read from csv file) to the sqlite database
print("Creating database...")
write_in_sqlite(loaded_df, database_file, table_name)
print("Write data to database successfully...")
# make a query
print("Querying the database")
queried_df = read_from_sqlite(database_file, table_name)
| true |
dc903ba5999763753228f8d9c2942718ddd3fe69 | magicmitra/obsidian | /discrete.py | 1,190 | 4.46875 | 4 | #----------------------------------------------------------------------------------
# This is a function that will calculate the interest rate in a discrete manner.
# Wirh this, interest is compounded k times a year and the bank will only add
# interest to the pricipal k times a year.
# The balance will then be returned.
# Author: Erv
#-----------------------------------------------------------------------------------
from decimal import *
constant_one = 1
# Formula : B(t) = P(1 + (r/k)) ** kt
# B = balance
# P = principal
# r = interest rate
# k = times compounded
# t = time in years
def discrete_calculate():
# prompt the user for values
principal = float(input("Enter the principal amount: $"))
time = int(input("Enter the time in years: "))
rate = float(input("Enter the interest rate in percentage form (Ex. 5.2): "))
compound = int (input("How many times a year is the interest compounded? "))
# calculate the balance
rate = rate * 0.01
exponent = compound * time
fraction = rate / compound
meta_balance = (fraction + constant_one) ** exponent
balance = principal * meta_balance
balance = round(balance, 2)
return "balance will be $" + str(balance)
| true |
097a63c09d55dc17208b953b948229ccc960c751 | Onyiee/DeitelExercisesInPython | /circle_area.py | 486 | 4.4375 | 4 | # 6.20 (Circle Area) Write an application that prompts the user for the radius of a circle and uses
# a method called circleArea to calculate the area of the circle.
def circle_area(r):
pi = 3.142
area_of_circle = pi * r * r
return area_of_circle
if __name__ == '__main__':
try:
r = int(input("Enter the radius of the circle: "))
area = circle_area(r)
print(area)
except ValueError:
print(" You need to enter a value for radius")
| true |
bccd0d8074473316cc7eb69671929cf14ea5c1ac | Onyiee/DeitelExercisesInPython | /Modified_guess_number.py | 1,472 | 4.1875 | 4 | # 6.31 (Guess the Number Modification) Modify the program of Exercise 6.30 to count the number of guesses
# the player makes. If the number is 10 or fewer, display Either you know the secret
# or you got lucky! If the player guesses the number in 10 tries, display Aha! You know the secret!
# If the player makes more than 10 guesses, display You should be able to do better! Why should it
# take no more than 10 guesses? Well, with each “good guess,” the player should be able to eliminate
# half of the numbers, then half of the remaining numbers, and so on.
from random import randint
count = 1
def ten_or_less_message(count):
if count == 10:
return "Aha! You know the secret!"
random_message = randint(1, 2)
if random_message == 1:
return "You got lucky!"
if random_message == 2:
return "You know the secret"
def greater_than_ten_message():
return "You should be able to do better!"
def modified_guess_game(guessed_number):
global count
random_number = randint(1, 10)
guessed_number = int(guessed_number)
if guessed_number == random_number and count <= 10:
print(ten_or_less_message(count))
if guessed_number == random_number and count > 10:
print(greater_than_ten_message())
count += 1
if guessed_number != random_number:
modified_guess_game(input("Guess a number between 1 and 10: "))
print(modified_guess_game(input("Guess a number between 1 and 10: ")))
| true |
3b26b40c9619c6b0eee0a36096688aeb57819f10 | Subharanjan-Sahoo/Practice-Questions | /Problem_34.py | 810 | 4.15625 | 4 | '''
Single File Programming Question
Your little brother has a math assignment to find whether the given number is a power of 2. If it is a power of 2 then he has to find the sum of the digits. If it is not a power of 2, then he has to find the next number which is a power of 2. He asks for your help to validate his work. But you are already busy playing video games. Develop a program so that your brother can validate his work by himself.
Example 1
Input
64
Output
Yes
10
Example 2
Input
133
Output
NO
'''
def math(input1):
if (int(input1) & (int(input1) - 1)) == 0 :#% 2 == 0:
sumyes = 0
print('Yes')
for i in range(len(input1)):
sumyes = int(input1[i]) + sumyes
print(sumyes)
else:
print('NO')
input1 = input()
math(input1) | true |
0bbb5802a3cfb9cd06a9a458bc77403689dad0ca | Subharanjan-Sahoo/Practice-Questions | /Problem_33.py | 1,040 | 4.375 | 4 | '''
Write a program to calculate and return the sum of distances between the adjacent numbers in an array of positive integers
Note:
You are expected to write code in the find TotalDistance function only which will receive the first parameter as the number of items in the array and second parameter as the array itself. You are not required to take input from the console
Example
Finding the total distance between adjacent items of a list of 5 numbers
Input input1: 5
input2: 10 11 7 12 14
Output
12
Explanation
The first parameter (5) is the size of the array. Next is an array of integers. The total of distances is 12 as per the calculation below
11-7-4
7-12-5
12-14-2 Total distance 1+4+5+2= 12
'''
def findTotalDistance(input1):
input2 = list(map(int,input().strip().split(" ")))[:input1]
sum = 0
for i in range(input1):
for j in range(input1):
if i+1 == j:
sum = (abs(input2[i] - input2[j])) + sum
return sum
input1 = int(input())
print(findTotalDistance(input1)) | true |
97c1bac183bf1c744eb4d1f05b6e0253b1455f10 | Subharanjan-Sahoo/Practice-Questions | /Problem_13.py | 733 | 4.21875 | 4 | '''
Write a function to find all the words in a string which are palindrome
Note: A string is said to be a palindrome if the reverse of the string is the same as string. For example, "abba" is a palindrome, but "abbe" is not a palindrome.
Input Specification:
input1: string
input2: Length of the String
Output Specification:
Retum the number of palindromes in the given string
Example 1:
inputt: this is level 71
input2: 16
Output 1
'''
def palondrom(input1):
input2 =list(input("input the string: ").strip().split(" "))[:input1]
count = 0
for i in input2:
if i == i[::-1]:
count = count + 1
print(count)
input1 =int(input("Enter the number of Word: "))
palondrom(input1) | true |
d30504a329fd5bcb59a284b5e28b89b6d21107e3 | lada8sztole/Bulochka-s-makom | /1_5_1.py | 479 | 4.1875 | 4 | # Task 1
#
# Make a program that has some sentence (a string) on input and returns a dict containing
# all unique words as keys and the number of occurrences as values.
# a = 'Apple was sweet as apple'
# b = a.split()
a = input('enter the string ')
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print(word_count(a))
| true |
cdc0c71ee2fd47586fca5c145f2c38905919cff5 | lada8sztole/Bulochka-s-makom | /1_6_3.py | 613 | 4.25 | 4 | # Task 3
#
# Words combination
#
# Create a program that reads an input string and then creates and prints 5 random strings from characters of the input string.
#
# For example, the program obtained the word ‘hello’, so it should print 5 random strings(words)
# that combine characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ -> ‘hlelo’, ‘olelh’, ‘loleh’ …
#
# Tips: Use random module to get random char from string)
import random
from itertools import permutations
a = input('sentence ')
b = list(permutations(a))
i = 0
while i<5:
print(''.join(b[random.randint(0, len(b))]))
i+=1
| true |
5438b1928dc780927363d3d7622ca0d00247a5c2 | malay190/Assignment_Solutions | /assignment9/ass9_5.py | 599 | 4.28125 | 4 | # Q.5- Create a class Expenditure and initialize it with expenditure,savings.Make the following methods.
# 1. Display expenditure and savings
# 2. Calculate total salary
# 3. Display salary
class expenditure:
def __init__(self,expenditure,savings):
self.expenditure=expenditure
self.savings=savings
def total_salary(self):
print("your expenditure is ",self.expenditure)
print("your saving is",self.savings)
salary=self.expenditure+self.savings
print("your salary is",salary)
a=expenditure(int(input("enter your expenditure:")),int(input("enter your savings:")))
a.total_salary() | true |
72a8086b765c8036b7f30853e440550a020d7602 | bradger68/daily_coding_problems | /dailycodingprob66.py | 1,182 | 4.375 | 4 | """Assume you have access to a function toss_biased()
which returns 0 or 1 with a probability that's not 50-50
(but also not 0-100 or 100-0). You do not know the bias
of the coin.
Write a function to simulate an unbiased coin toss.
"""
import random
unknown_ratio_heads = random.randint(1,100)
unknown_ratio_tails = 100-unknown_ratio_heads
def coin_toss(tosses):
heads_count = 0
tails_count = 0
weighted_probabilities = unknown_ratio_heads * ['Heads'] + unknown_ratio_tails * ['Tails']
for x in range(tosses):
toss = random.choice(weighted_probabilities)
if toss == 'Heads':
heads_count += 1
else:
tails_count += 1
ratio_tails = (tails_count / tosses) * 100
ratio_heads = (heads_count / tosses) * 100
print(str(heads_count) + " of the " + str(tosses) + " tosses were heads. That is " + str(ratio_heads) + " percent.")
print(str(tails_count) + " of the " + str(tosses) + " tosses were tails. That is " + str(ratio_tails) + " percent.")
print("The unknown probability of getting heads was " + str(unknown_ratio_heads) +". How close were you?")
coin_toss(10000)
| true |
68c281e253778c4c3640a5c67d2e7948ca8e150a | farahhhag/Python-Projects | /Grade & Attendance Calculator (+Data Validation).py | 2,363 | 4.21875 | 4 | data_valid = False
while data_valid == False:
grade1 = input("Enter the first grade: ")
try:
grade1 = float(grade1)
except:
print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.")
continue
if grade1 <0 or grade1 > 10:
print("Grade should be in between 0 to 10")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
grade2 = input("Enter the second grade: ")
try:
grade2 = float(grade2)
except:
print("Invalid input. Only numbers are accepted. Decimals should be separated with a dot.")
continue
if grade2 <0 or grade2 > 10:
print("Grade should be in between 0 to 10")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
total_class = input("Enter the number of total class: ")
try:
total_class = int(total_class)
except:
print("Invalid input. Only numbers are accepted.")
continue
if total_class <= 0:
print("The number of total class can't be less than 0")
continue
else:
data_valid = True
data_valid = False
while data_valid == False:
absences = input("Enter the number of total absences: ")
try:
absences = int(absences)
except:
print("Invalid input. Only numbers are accepted.")
continue
if absences <=0 or absences > total_class:
print("The number of absences can't be less than 0 or greater than the number of total classes")
continue
else:
data_valid = True
avg_grade = (grade1 + grade2) / 2
attendance = (total_class - absences) / total_class
print("Average Grade:", round(avg_grade, 2))
print("Attendance Rate:", str(round((attendance * 100),2))+"%")
if (avg_grade >= 6.0 and attendance >= 0.8):
print("The student has been approved")
elif(avg_grade < 6.0 and attendance < 0.8):
print("The student has failed because the attendance rate is lower than 80% and the average grade is lower than 6.0")
elif(attendance >= 0.8):
print("The student has failed because the average grade is lower than 6.0")
else:
print("The student has failed because the attendance rate is lower than 80%")
| true |
c68084826badc09dd3f037098bfcfbccb712ee15 | kayazdan/exercises | /chapter-5.2/ex-5-15.py | 2,923 | 4.40625 | 4 | # Programming Exercise 5-15
#
# Program to find the average of five scores and output the scores and average with letter grade equivalents.
# This program prompts a user for five numerical scores,
# calculates their average, and assigns letter grades to each,
# and outputs the list and average as a table on the screen.
# define the main function
# define local variables for average and five scores
# Get five scores from the user
# find the average by passing the scores to a function that returns the average
# display grade and average information in tabular form
# as score, numeric grade, letter grade, separated by tabs
# display a line of underscores under this header
# print data for all five scores, using the score,
# with the result of a function to determine letter grade
# display a line of underscores under this table of data
# display the average and the letter grade for the average
# Define a function to return the average of 5 grades.
# This function accepts five values as parameters,
# computes the average,
# and returns the average.
# define a local float variable to hold the average
# calculate the average
# return the average
# Define a function to return a numeric grade from a number.
# This function accepts a grade as a parameter,
# Uses logical tests to assign it a letter grade,
# and returns the letter grade.
# if score is 90 or more, return A
# 80 or more, return B
# 70 or more, return C
# 60 or more, return D
# anything else, return F
# Call the main function to start the program
def main():
average = 0
score1 = 0
score2 = 0
score3 = 0
score4 = 0
score5 = 0
score1 = int(input("Score one: "))
score2 = int(input("Score two: "))
score3 = int(input("Score three: "))
score4 = int(input("Score four: "))
score5 = int(input("Score five: "))
find_average(score1, score2, score3, score4, score5)
average = find_average(score1, score2, score3, score4, score5)
get_letter_grade(average)
letter_grade = get_letter_grade(average)
print(" ")
print("Average Grade: ", '\t', "Letter Grade: ")
print("__________________________________________")
print(average, '\t', " ", letter_grade)
def find_average(score1, score2, score3, score4, score5):
average = 0.0
all_score = score1 + score2 + score3 + score4 + score5
average = all_score/5
return average
def get_letter_grade(average):
if average >= 90:
return "A"
elif average >= 80:
return "B"
elif average >= 70:
return "C"
elif average >= 60:
return "D"
else:
return "F"
main()
| true |
ed61c43c7ab9b7ea26b890a00a08d2ed52ba3e47 | kayazdan/exercises | /chapter-3/exercise-3-1.py | 1,209 | 4.65625 | 5 | # Programming Exercise 3-1
#
# Program to display the name of a week day from its number.
# This program prompts a user for the number (1 to 7)
# and uses it to choose the name of a weekday
# to display on the screen.
# Variables to hold the day of the week and the name of the day.
# Be sure to initialize the day of the week to an int and the name as a string.
# Get the number for the day of the week.
# be sure to format the input as an int
nmb_day = input("What number of the day is it?: ")
int_nmb_day = int(nmb_day)
# Determine the value to assign to the day of the week.
# use a set of if ... elif ... etc. statements to test the day of the week value.
if int_nmb_day == 1:
print("Monday")
elif int_nmb_day == 2:
print("Tuesday")
elif int_nmb_day == 3:
print("Wednesday")
elif int_nmb_day == 4:
print("Thursday")
elif int_nmb_day == 5:
print("Friday")
elif int_nmb_day == 6:
print("Saturday")
elif int_nmb_day == 7:
print("Sunday")
else:
print("Out of range")
# use the final else to display an error message if the number is out of range.
# display the name of the day on the screen.
| true |
77f27e01be7161901f28d68801d67c3d1e1e8c83 | Nikola011s/portfolio | /work_with_menus.py | 2,539 | 4.6875 | 5 |
#User enters n, and then n elements of the list
#After entering elements of the list, show him options
#1) Print the entire list
#2) Add a new one to the list
#3) Average odd from the whole list
#4) The product of all elements that is divisible by 3 or by 4
#5) The largest element in the list
#6) The sum of those that is higher than the average of the whole list
# User choose an option and based on that option you print
n = int(input("Enter list lenth: "))
list_elements = []
for i in range(n):
number = int(input("Enter number:"))
list_elements.append(number)
print(list_elements)
while True:
print("""
1) Print the entire list
2) Add a new one to the list
3) Average odd from the whole list
4) The product of all elements that is divisible by 3 or by 4
5) The largest element in the list
6) The sum of those that is higher than the average of the whole list
0) Exit program
""")
option = int(input("Choose an option:"))
if option == 0:
print("End of the line")
exit(1)
elif option == 1:
print(list_elements)
elif option == 2:
number = int(input("Enter new element to the list: "))
list_elements.append(number)
elif option == 3:
sum = 0
counter = 0
lenth_list = len(list_elements)
for i in range(lenth_list):
if list_elements[i] % 2 != 0:
sum = sum + list_elements[i]
counter = counter + 1
if counter != 0:
average = sum / counter
print(" Average odd from the whole list is {average}")
else:
print("No odd elements")
elif option == 4:
product = 1
for i in range(n):
if list_elements[i] % 3 == 0 or list_elements[i] % 4 == 0:
product = product * list_elements[i]
print("Product is {product}")
elif option == 5:
maximum = list_elemens[0]
for number in list_elements:
if number > maximum:
maximum = number
print(maximum)
elif option == 6:
sum_higher = 0
sum = 0
for number in list_elements:
sum += number
average = sum / len(list_elements)
for number in list_elements:
if number > average:
sum_higher += number
print(sum_higher)
| true |
ba564bd38231baac9bec825f4eaac669c00ff6a5 | desingh9/PythonForBeginnersIntoCoding | /Day6_Only_Answers/Answer_Q2_If_Else.py | 353 | 4.21875 | 4 | #1.) Write a program to check whether a entered character is lowercase ( a to z ) or uppercase ( A to Z ).
chr=(input("Enter Charactor:"))
#A=chr(65,90)
#for i in range(65,90)
if (ord(chr) >=65) and (ord(chr)<=90):
print("its a CAPITAL Letter")
elif (ord(chr>=97) and ord(chr<=122)):
print ("its a Small charector")
else:
print("errrrr404") | true |
dea948a20c0c3e4ad252eb28988f2ae935e79046 | desingh9/PythonForBeginnersIntoCoding | /Q4Mix_A1.py | 776 | 4.28125 | 4 | #1) Write a program to find All the missing numbers in a given integer array ?
arr = [1, 2,5,,9,3,11,15]
occurranceOfDigit=[]
# finding max no so that , will create list will index till max no .
max=arr[0]
for no in arr:
if no>max:
max=no
# adding all zeros [0] at all indexes till the maximum no in array
for no in range(0,max+1):
occurranceOfDigit.append(0)
# original array
print(arr)
# marking index in occurrance array to 1 for all no in original array. marking indexes that are present in original array
for no in arr:
occurranceOfDigit[no]=1
print("Missing elements are: ")
i=1
# accesing all indexes where values are zero. i.e no. are not present in array
while i<=max:
if occurranceOfDigit[i]==0:
print(i,end=" ")
i+=1
| true |
be06a70e1eef93540bb5837ae43220ae29d7d7fa | veetarag/Data-Structures-and-Algorithms-in-Python | /Interview Questions/Rotate Image.py | 592 | 4.125 | 4 | def rotate(matrix):
l = len(matrix)
for row in matrix:
print(row)
print()
# Transpose the Matrix
for i in range(l):
for j in range(i, l):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
print(row)
print()
# Row Reverse
for i in range(l):
for j in range(l//2):
matrix[i][l-j-1], matrix[i][j] = matrix[i][j], matrix[i][l-j-1]
for row in matrix:
print(row)
return matrix
# Rotate the image 90 degree clockwise
rotate([
[1,2,3],
[4,5,6],
[7,8,9]
]) | true |
219d0100864e2e8b1777cb935a9b5e61ca52ef8a | osalpekar/RSA-Encrypter | /rsa.py | 620 | 4.15625 | 4 | '''
Main function instantiates the Receiver class
Calls encrypt and decrypt on user-inputted message
'''
from receiver import Receiver
def main():
message = raw_input("Enter a message you would like to encrypt/decrypt: ")
receiver = Receiver()
encrypted_message = receiver.encrypt(message)
decrypted_message = receiver.decrypt(encrypted_message)
print "Your original message was: " + message
print "Your encrypted message is: " + ''.join([str(num) for num in encrypted_message])
print "Your decrpyted message is: " + decrypted_message
return
if __name__ == "__main__":
main()
| true |
db6b22e0d6c051b508dbdff4cab4babcbd867c6e | ua-ants/webacad_python | /lesson01_old/hw/script3.py | 485 | 4.15625 | 4 | while True:
print('To quit program enter "q"')
val1 = input('Enter a first number: ')
if val1 == 'q':
break
val2 = input('Enter a second number: ')
if val2 == 'q':
break
try:
val1 = int(val1)
val2 = int(val2)
except ValueError:
print('one of entered value is not integer')
continue
if val1 > val2:
print(val1-val2)
elif val1 < val2:
print(val1+val2)
else:
print(val1)
| true |
96b4061196c3dc36646c9f3b88a004890db47edf | KostaSav/Tic-Tac-Toe | /console.py | 1,231 | 4.1875 | 4 | ########## Imports ##########
import config
# Initialize the Game Board and print it in console
board = [
[" ", "|", " ", "|", " "],
["-", "+", "-", "+", "-"],
[" ", "|", " ", "|", " "],
["-", "+", "-", "+", "-"],
[" ", "|", " ", "|", " "],
]
## Print the Game Board in console
def print_board():
for line in board:
for char in line:
print(char, end="")
print()
## Reset the board to empty
def reset_board():
for line in board:
for i in range(len(line)):
if line[i] == "X" or line[i] == "O":
line[i] = " "
## Draw the played piece on the board
def place_piece(pos, first_player_turn, piece):
if first_player_turn:
config.player1_positions.add(pos)
else:
config.player2_positions.add(pos)
if pos == 1:
board[0][0] = piece
elif pos == 2:
board[0][2] = piece
elif pos == 3:
board[0][4] = piece
elif pos == 4:
board[2][0] = piece
elif pos == 5:
board[2][2] = piece
elif pos == 6:
board[2][4] = piece
elif pos == 7:
board[4][0] = piece
elif pos == 8:
board[4][2] = piece
elif pos == 9:
board[4][4] = piece | true |
c03e3f76b690c87b8939f726faeac5c0d6107b93 | Anwar91-TechKnow/PythonPratice-Set2 | /Swipe two numbers.py | 1,648 | 4.4375 | 4 | # ANWAR SHAIKH
# Python program set2/001
# Title: Swipe two Numbers
'''This is python progaramm where i am doing swapping of two number using two approches.
1. with hardcorded values
2. Values taken from user
also in this i have added how to use temporary variable as well as without delcaring
temporary varibale.
============================================================
'''
# Please commentout the rest approches and use only one approch at the time of execution.
import time
#1. with hardcorded values
num1=55
num2=30
print("Value of num1 before swapping : ",num1)
print("Value of num2 before swapping : ",num2)
time.sleep(2)
#now here created temporary varibale to store value of numbers.
a = num1 #it will store value in variable called a
num1=num2 #here num2 will replace with num1 value
num2=a #here num2 value swapped with num1 which
#swapping is done
print("Value of num1 After swapping : ",num1)
print("Value of num2 after swapping : ",num2)
time.sleep(3)
#second example:
#2. Values taken from user
#we can take input from user also
num_one=input("Enter first number : ")
num_two=input("Enter Second number : ")
time.sleep(3)
b = num_one
num_one=num_two
num_two=b
print("Value of first number After swapping : ",num_one)
print("Value of second number swapping : ",num_two)
time.sleep(3)
#without delcaring temporary variable.
num1=20
num2=5
print("Value of num1 before swapping : ",num1)
print("Value of num2 before swapping : ",num2)
time.sleep(3)
num1,num2=num2,num1
#swapping is done
print("Value of num1 After swapping : ",num1)
print("Value of num2 after swapping : ",num2)
time.sleep(3) | true |
981c2e7984813e752f26a37f85ca2bec74470b40 | mon0theist/Automate-The-Boring-Stuff | /Chapter 04/commaCode2.py | 1,183 | 4.375 | 4 | # Ch 4 Practice Project - Comma Code
# second attempt
#
# Say you have a list value like this:
# spam = ['apples', 'bananas', 'tofu', 'cats']
#
# Write a function that takes a list value as an argument and returns a string
# with all the items separated by a comma and a space, with and inserted before
# the last item. For example, passing the previous spam list to the function
# would return 'apples, bananas, tofu, and cats'. But your function should be
# able to work with any list value passed to it.
#
# Couldn't figure this out on my own, had to look at the solution from my last attempt,
# which I'm also pretty sure I didn't figure out on my own, pretty sure I
# copy+pasted from somewhere
#
# I can read it and understand why it works, but writing it from scratch is a whole
# different thing :'(
def commaList(listValue):
counter = 0
newString = ''
while counter < len(listValue)-1:
newString += str(listValue[counter]) + ', '
counter += 1
print(newString + 'and ' + str(listValue[counter])) # print for testing
return newString + 'and ' + str(listValue[counter])
spamList = ['apples', 'bananas', 'tofu', 'cats']
commaList(spamList)
| true |
3c2f7e0a16640fdb7e72795f10824fcce5370199 | mon0theist/Automate-The-Boring-Stuff | /Chapter 07/strongPassword.py | 1,249 | 4.375 | 4 | #! /usr/bin/python3
# ATBS Chapter 7 Practice Project
# Strong Password Detection
# Write a function that uses regular expressions to make sure the password
# string it is passed is strong.
# A strong password has:
# at least 8 chars - .{8,}
# both uppercase and lowercase chars - [a-zA-Z]
# test that BOTH exist, not just simply re.IGNORECASE
# at least one digit - \d+
# You may need to test the string against multiple regex patterns to validate its strength.
# NOTES
# Order shouldn't matter, & operator?
# Test: if regex search/findall != None
# seperate Regex for reach requirement?
import re
def pwStrength(pw):
if eightChars.search(pw) and oneUpper.search(pw) and oneLower.search(pw) and oneDigit.search(pw) != None:
print('Your password meets the requirements.')
else:
print('Your password does not meet the requirements.')
eightChars = re.compile(r'.{8,}') # tests for 8 or more chars
oneUpper = re.compile(r'[A-Z]+') # test for 1+ upper
oneLower = re.compile(r'[a-z]+') # test for 1+ lower
oneDigit = re.compile(r'\d+') # test for 1+ digit
# Wanted to combine all into single Regex if possible but can't figure it out
password = input('Please enter the password you want to test: ')
pwStrength(password)
| true |
cf1e3aa630ec34233b352168bd4b0818565883cb | sofianguy/skills-dictionaries | /test-find-common-items.py | 1,040 | 4.5 | 4 | def find_common_items(list1, list2):
"""Produce the set of common items in two lists.
Given two lists, return a list of the common items shared between
the lists.
IMPORTANT: you may not not 'if ___ in ___' or the method 'index'.
For example:
>>> sorted(find_common_items([1, 2, 3, 4], [1, 2]))
[1, 2]
If an item appears more than once in both lists, return it each
time:
>>> sorted(find_common_items([1, 2, 3, 4], [1, 1, 2, 2]))
[1, 1, 2, 2]
(And the order of which has the multiples shouldn't matter, either):
>>> sorted(find_common_items([1, 1, 2, 2], [1, 2, 3, 4]))
[1, 1, 2, 2]
"""
common_items_list = []
for item1 in list1:
for item2 in list2:
if item1 == item2:
common_items_list.append(item1) #add item1 to new list
return common_items_list
print find_common_items([1, 2, 3, 4], [1, 2])
print find_common_items([1, 2, 3, 4], [1, 1, 2, 2])
print find_common_items([1, 1, 2, 2], [1, 2, 3, 4]) | true |
fbb4ce33a955eec2036211a7421950f027330a0b | l3ouu4n9/LeetCode | /algorithms/7. Reverse Integer.py | 860 | 4.125 | 4 | '''
Given a 32-bit signed integer, reverse digits of an integer.
E.g.
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
import sys
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = str(x)
if(s[0] == '-'):
s = '-' + s[1::][::-1]
else:
s = s[::-1]
while(len(s) > 1 and s[0] == '0'):
s = s[1::]
if(int(s) >= 2 ** 31 or int(s) < (-2) ** 31):
return 0
else:
return int(s)
| true |
4f85b8be417d4253520781c0f99e31af282d60b7 | sjtrimble/pythonCardGame | /cardgame.py | 2,811 | 4.21875 | 4 | # basic card game for Coding Dojo Python OOP module
# San Jose, CA
# 2016-12-06
import random # to be used below in the Deck class function
# Creating Card Class
class Card(object):
def __init__(self, value, suit):
self.value = value
self.suit = suit
def show(self):
print self.value + " " + self.suit
# Creating Deck Class
class Deck(object):
def __init__(self):
self.cards = []
self.get_cards() # running the get_card method defined below to initiate with a full set of cards as your deck
def get_cards(self):
suits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']
values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
for suit in suits: # iterating through the suits
for value in values: # iterating through each value
newcard = Card(value, suit) # creating a newcard variable with the class Card and passing the iterations from the for loop
self.cards.append(newcard) # adding the newly created card of Card class and adding it to the cards variable within the deck class object/instance
def show(self):
for card in self.cards:
card.show() # calling the Card class' show method (see above in Card class section) - this is okay because the item it's iterating through it of the Card class
def shuffle(self):
random.shuffle(self.cards) # using random.shuffle method - import random above needs to be set before using
def deal(self):
return self.cards.pop() # returning the removed last value (a card of class Card) of the cards variable
# Creating Player Class
class Player(object):
def __init__(self, name):
self.hand = []
self.name = name
def draw_cards(self, number, deck): # also need to pass through the deck here so that the player can have cards deal to them from that deck of class Deck
if number < len(deck.cards):# to ensure that the amount of cards dealt do not exceed how many cards remain in a deck
for i in range (number): # iterating through the cards in the deck
self.hand.append(deck.deal()) # appending it to the player's hand variable set above
print "Sorry, the deck is out of cards"
def show(self):
for card in self.hand:
card.show() # calling the Card class' show method (see above in Card class section) - this is okay because the item it's iterating through it of the Card class
# Sample Order of Process
mydeck = Deck() # create a new deck with Deck class
mydeck.shuffle() # shuffle the deck
player1 = Player('Bob') # create a new player
player1.draw_cards(5, mydeck) # draw 5 card from the mydeck deck created
player1.show() # show the player's hand of cards that has been drawn | true |
6e2fd2cc56821e6aeb9ac0beb5173a9d57c03f67 | ericd9799/PythonPractice | /year100.py | 421 | 4.125 | 4 | #! /usr/bin/python3
import datetime
now = datetime.datetime.now()
year = now.year
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
yearsToHundred = 100 - age
turnHundred = int(year) + yearsToHundred
message = name + " will turn 100 in the year "+ str(turnHundred)
print(message)
repeat = int(input("Please enter integer to repeat message: "))
print(repeat * (message + "\n"))
| true |
1b6d711b5078871fca2de4fcf0a12fc0989f96e4 | ericd9799/PythonPractice | /modCheck.py | 497 | 4.125 | 4 | #! /usr/bin/python3
modCheck = int(input("Please enter an integer: "))
if (modCheck % 4) == 0:
print(str(modCheck) + " is a multiple of 4")
elif (modCheck % 2) == 0:
print(str(modCheck) + " is even")
elif (modCheck % 2) != 0:
print(str(modCheck) + " is odd")
num, check = input("Enter 2 numbers:").split()
num = int(num)
check = int(check)
if num % check == 0:
print(str(check) + " divides evenly into " + str(num))
else:
print(str(check) + " does not divide evenly into " + str(num))
| true |
4e8737d284c7cf01dea8dd82917e1fc787216219 | EraSilv/day2 | /day5_6_7/day7.py | 879 | 4.125 | 4 | # password = (input('Enter ur password:'))
# if len(password) >= 8 and 8 > 0:
# print('Correct! ')
# print('Next----->:')
# else:
# print('Password must be more than 8!:')
# print('Try again!')
# print('Create a new account ')
# login = input('login:')
# email = input('Your e-mail:')
# print('Choose correct password.')
# password = (input('Enter ur password:'))
# if len(password) >= 8 and 8 > 0:
# print('Correct! ')
# print('Next----->:')
# else:
# print('Password must be more than 8!:')
# print('Try again!')
# print('-----------------ENTER-------------------')
# log = input('login or e-mail: ')
# pas = input('password: ')
# if login==log and password==pas:
# print(' Entrance is successfully competed! ')
# else:
# print('password or login is incorrect! ')
# print('Try after a few minutes! ')
| true |
3253b6843f4edd1047c567edc5a1d1973ead4b00 | watson1227/Python-Beginner-Tutorials-YouTube- | /Funtions In Python.py | 567 | 4.21875 | 4 | # Functions In Python
# Like in mathematics, where a function takes an argument and produces a result, it
# does so in Python as well
# The general form of a Python function is:
# def function_name(arguments):
# {lines telling the function what to do to produce the result}
# return result
# lets consider producing a function that returns x^2 + y^2
def squared(x, y):
result = x**2 + y**2
return result
print(squared(10, 2))
# A new function
def born (country):
return print("I am from " + country)
born("greensboro") | true |
de12c3cb06a024c01510f0cf70e76721a80d506e | ytlty/coding_problems | /fibonacci_modified.py | 1,049 | 4.125 | 4 | '''
A series is defined in the following manner:
Given the nth and (n+1)th terms, the (n+2)th can be computed by the following relation
Tn+2 = (Tn+1)2 + Tn
So, if the first two terms of the series are 0 and 1:
the third term = 12 + 0 = 1
fourth term = 12 + 1 = 2
fifth term = 22 + 1 = 5
... And so on.
Given three integers A, B and N, such that the first two terms of the series (1st and 2nd terms) are A and B respectively, compute the Nth term of the series.
Input Format
You are given three space separated integers A, B and N on one line.
Input Constraints
0 <= A,B <= 2
3 <= N <= 20
Output Format
One integer.
This integer is the Nth term of the given series when the first two terms are A and B respectively.
Note
Some output may even exceed the range of 64 bit integer.
'''
import sys
from math import pow
a,b,n = tuple(map(int, input().split()))
#print(a,b,n)
nums = []
nums.append(a)
nums.append(b)
n_2 = a
n_1 = b
res = 0
for x in range(2, n):
res = n_1*n_1 + n_2
n_2 = n_1
n_1 = res
print(res)
| true |
f69783e7a620ca692a6b6213f16ef06b491b35e5 | lily-liu-17/ICS3U-Assignment-7-Python-Concatenates | /concatenates.py | 883 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Lily Liu
# Created on: Oct 2021
# This program concatenates
def concatenate(first_things, second_things):
# this function concatenate two lists
concatenated_list = []
# process
for element in first_things:
concatenated_list.append(element)
for element in second_things:
concatenated_list.append(element)
return concatenated_list
def main():
concatenated_list = []
# input
user_first_things = input("Enter the things to put in first list (no spaces): ")
user_second_things = input("Enter the things to put in second list (no spaces): ")
# output
print("")
concatenated_list = concatenate(user_first_things, user_second_things)
print("The concatenated list is {0} ".format(concatenated_list))
print("")
print("Done.")
if __name__ == "__main__":
main()
| true |
2015152c0424d7b45235cefa678ea2cb90523132 | ChiselD/guess-my-number | /app.py | 401 | 4.125 | 4 | import random
secret_number = random.randint(1,101)
guess = int(input("Guess what number I'm thinking of (between 1 and 100): "))
while guess != secret_number:
if guess > secret_number:
guess = int(input("Too high! Guess again: "))
if guess < secret_number:
guess = int(input("Too low! Guess again: "))
if guess == secret_number:
print(f"You guessed it! I was thinking of {secret_number}.") | true |
ae9e8ccfee70ada5d6f60a9e8a16f3c2204078ca | OmarSamehMahmoud/Python_Projects | /Pyramids/pyramids.py | 381 | 4.15625 | 4 | height = input("Please enter pyramid Hieght: ")
height = int(height)
row = 0
while row < height:
NumOfSpace = height - row - 1
NumOfStars = ((row + 1) * 2) - 1
string = ""
#Step 1: Get the spaces
i = 0
while i < NumOfSpace:
string = string + " "
i += 1
#step 2: Get the stars
i = 0
while i < NumOfStars:
string = string + "*"
i +=1
print(string)
row += 1 | true |
b746c7e3d271187b42765b9bf9e748e79ba29eca | fortunesd/PYTHON-TUTORIAL | /loops.py | 792 | 4.40625 | 4 | # A for loop is used for iterating over a sequence (that is either a list, a tuple, a set, or a string).
students = ['fortunes', 'abdul', 'obinaka', 'amos', 'ibrahim', 'zaniab']
# simple for loop
for student in students:
print(f'i am: {student}')
#break
for student in students:
if student == 'odinaka':
break
print(f'the student is: {student}')
#continue
for student in students:
if student == 'odinaka':
continue
print(f'the people included: {students}')
#range
for person in range(len(student)):
print(f'number: {person}')
# custom range
for n in range(0, 12):
print(f'number: {n}')
# while loops excute a set of statements as long as a condition is true.
count = 0
while count < 10:
print(f'count: {count}')
count += 1
| true |
6d3f673aad4128477625d3823e3cf8688fc89f2f | CollinNatterstad/RandomPasswordGenerator | /PasswordGenerator.py | 814 | 4.15625 | 4 | def main():
#importing necessary libraries.
import random, string
#getting user criteria for password length
password_length = int(input("How many characters would you like your password to have? "))
#creating an empty list to store the password inside.
password = []
#establishing what characters are allowed to be chosen.
password_characters = string.ascii_lowercase + string.ascii_uppercase + string.digits
#for loop to iterate over the password_length choosing a character at random from the pool of choices in password_characters.
for x in range (password_length):
password.append(random.choice(password_characters))
#printing the password to the terminal.
print("".join(password))
if __name__ == "__main__":
main() | true |
2b33a5ed96a8a8c320432581d71f2c46b2a3998a | laufzeitfehlernet/Learning_Python | /math/collatz.py | 305 | 4.21875 | 4 | ### To calculate the Collatz conjecture
start = int(input("Enter a integer to start the madness: "))
loop = 1
print(start)
while start > 1:
if (start % 2) == 0:
start = int(start / 2)
else:
start = start * 3 + 1
loop+=1
print(start)
print("It was in total", loop, "loops it it ends!")
| true |
dfa330f673a2b85151b1a06ca63c3c78214c722e | joq0033/ass_3_python | /with_design_pattern/abstract_factory.py | 2,239 | 4.25 | 4 | from abc import ABC, abstractmethod
from PickleMaker import *
from shelve import *
class AbstractSerializerFactory(ABC):
"""
The Abstract Factory interface declares a set of methods that return
different abstract products. These products are called a family and are
related by a high-level theme or concept. Products of one family are usually
able to collaborate among themselves. A family of products may have several
variants, but the products of one variant are incompatible with products of
another.
"""
@abstractmethod
def create_serializer(self):
pass
class ConcretePickleFactory(AbstractSerializerFactory):
"""
Concrete Factories produce a family of products that belong to a single
variant. The factory guarantees that resulting products are compatible. Note
that signatures of the Concrete Factory's methods return an abstract
product, while inside the method a concrete product is instantiated.
"""
def create_serializer(self):
return MyPickle('DocTestPickle.py', 'test')
class ConcreteShelfFactory(AbstractSerializerFactory):
"""
Concrete Factories produce a family of products that belong to a single
variant. The factory guarantees that resulting products are compatible. Note
that signatures of the Concrete Factory's methods return an abstract
product, while inside the method a concrete product is instantiated.
"""
def create_serializer(self):
return Shelf('source_file')
def test_serializers(factory):
"""
The client code works with factories and products only through abstract
types: AbstractFactory and AbstractProduct. This lets you pass any factory
or product subclass to the client code without breaking it.
"""
serialize = factory.create_serializer()
serialize.make_data()
serialize.unmake_data()
if __name__ == "__main__":
"""
The client code can work with any concrete factory class.
"""
print("Client: Testing client code with the first factory type: MyPickle")
test_serializers(ConcretePickleFactory())
| true |
1af1818dfe2bfb1bab321c87786ab356f7cff2d4 | rahulrsr/pythonStringManipulation | /reverse_sentence.py | 241 | 4.25 | 4 | def reverse_sentence(statement):
stm=statement.split()
rev_stm=stm[::-1]
rev_stm=' '.join(rev_stm)
return rev_stm
if __name__ == '__main__':
m=input("Enter the sentence to be reversed: ")
print(reverse_sentence(m))
| true |
590419d3a0fa5cbf2b1d907359a22a0aa7fe92b5 | kopelek/pycalc | /pycalc/stack.py | 837 | 4.1875 | 4 | #!/usr/bin/python3
class Stack(object):
"""
Implementation of the stack structure.
"""
def __init__(self):
self._items = []
def clean(self):
"""
Removes all items.
"""
self._items = []
def push(self, item):
"""
Adds given item at the top of the stack.
"""
self._items.append(item)
def pop(self):
"""
Returns with removing from the stack the first item from the top of the stack.
"""
return self._items.pop()
def peek(self):
"""
Returns the first item from the top of the stack.
"""
return self._items[len(self._items) - 1]
def is_empty(self):
"""
Returns True if stack is empty, False otherwise.
"""
return self._items == []
| true |
289d459d9e0dda101f443edaa9bf65d2985b4949 | YaraBader/python-applecation | /Ryans+Notes+Coding+Exercise+16+Calculate+a+Factorial.py | 604 | 4.1875 | 4 | '''
Create a Factorial
To solve this problem:
1. Create a function that will find the factorial for a value using a recursive function.
Factorials are calculated as such 3! = 3 * 2 * 1
2. Expected Output
Factorial of 4 = 24
Factorial at its recursive form is: X! = X * (X-1)!
'''
# define the factorial function
def factorial(n):
# Sets to 1 if asked for 1
# This is the exit condition
if n==1:
return 1
else:
# factorial in recursive form for >= 2
result = n * factorial(n-1)
return result
# prints factorial of 4
print ("Factorial of 4 =", factorial(4)) | true |
84e848c7b3f7cd20142ce6326a8a5131b1ecacad | YaraBader/python-applecation | /Ryans+Notes+Coding+Exercise+8+Print+a+Christmas+Tree.py | 1,956 | 4.34375 | 4 | '''
To solve this problem:
Don't use the input function in this code
1. Assign a value of 5 to the variable tree_height
2. Print a tree like you saw in the video with 4 rows and a stump on the bottom
TIP 1
You should use a while loop and 3 for loops.
TIP 2
I know that this is the number of spaces and hashes for the tree
4 - 1
3 - 3
2 - 5
1 - 7
0 - 9
Spaces before stump = Spaces before top
TIP 3
You will need to do the following in your program :
1. Decrement spaces by one each time through the loop
2. Increment the hashes by 2 each time through the loop
3. Save spaces to the stump by calculating tree height - 1
4. Decrement from tree height until it equals 0
5. Print spaces and then hashes for each row
6. Print stump spaces and then 1 hash
Here is the sample program
How tall is the tree : 5
#
###
#####
#######
#########
#
'''
# Sets 5 for tree_height (as an integer)
height = int(5)
# spaces starts as height - 1
spaces = stumpspaces = height -1
# hashes start as 1
hashes = 1
# This loop goes until the height limit is reached
# height will be decreased by 1 each iteration of the loop
while height >= 1:
# Prints a space for the number of spaces before the hashes
# This starts at height-1, just like the stump, and decreases 1 per iteration
# end="" does not print a new line
for i in range(spaces):
print(" ", end="")
# Prints the hashes
# which starts at 1 and increases by 2 per iteration
for j in range(hashes):
print('#', end="")
# prints a new line after each iteration of the spaces and hashes
print()
# spaces decreases 1 per iteration
spaces -= 1
# hashes increase 2 per iteration
hashes += 2
# This is what makes it go down to the next level
height -= 1
# Prints the spaces before the hash stump
# which is height-1
for i in range(stumpspaces):
print(' ', end="")
# Prints the hash stump
print("#")
| true |
20d2c16838f90918e89bfcf67d7c1f9210d6d39a | vaishu8747/Practise-Ass1 | /1.py | 231 | 4.34375 | 4 | def longestWordLength(string):
length=0
for word in string.split():
if(len(word)>length):
length=len(word)
return length
string="I am an intern at geeksforgeeks"
print(longestWordLength(string))
| true |
894abe59b869794b4a35903f04a750b1f9ee5788 | brianbrake/Python | /ComputePay.py | 834 | 4.3125 | 4 | # Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay
# Award time-and-a-half for the hourly rate for all hours worked above 40 hours
# Put the logic to do the computation of time-and-a-half in a function called computepay()
# Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75)
def computepay (hrs,rate):
try:
hrs=float(raw_input("Enter Hours: "))
rate=float(raw_input("Enter Rate: "))
if hrs <= 40:
gross = hrs * rate
else:
overtime = float (hrs-40)
gross = (rate*40)+(overtime*1.5*rate)
return gross
except:
print "Please type numerical data only. Restart & try again: "
quit()
print computepay('hrs', 'rate')
| true |
6168ffa995d236e3882954d9057582a5c130763a | ghinks/epl-py-data-wrangler | /src/parsers/reader/reader.py | 2,129 | 4.15625 | 4 | import re
import datetime
class Reader:
fileName = ""
def __init__(self, fileName):
self.fileName = fileName
def convertTeamName(self, name):
"""convert string to upper case and strip spaces
Take the given team name remove whitespace and
convert to uppercase
"""
try:
upper = name.upper()
converted = re.sub(r"\s+", "", upper)
return converted
except Exception as e:
print(f"an exception when trying to convert ${name} to upper case has taken place ${e}")
raise
def convertStrDate(self, strDate):
"""given dd/mm/yyyy or yyyy-mm-dd create a python Date
Take the string format of 'dd/mm/yyyy' or 'yyyyy-mm-dd'
and convert that into a form that may be used to create
a python date
"""
if not isinstance(strDate, str):
return strDate
try:
compiled = re.compile(r"(\d\d)\/(\d\d)\/(\d{2,4})")
match = compiled.match(strDate)
if match:
day = match.groups()[0]
month = match.groups()[1]
year = match.groups()[2]
# there are two types of year format that can be given
# the first is a 2 digit year. If this year is > 80
# then it was before year 2000
# if it is < 80 it is after year 2000
if len(year) == 2 and 80 < (int(year)) < 100:
year = (int(year)) + 1900
elif len(year) == 2 and (int(year)) < 80:
year = 2000 + int(year)
return datetime.date(int(year), int(month), int(day))
compiled = re.compile(r"(\d\d\d\d)\-(\d\d)\-(\d\d)(.*)")
match = compiled.match(strDate)
year = match.groups()[0]
month = match.groups()[1]
day = match.groups()[2]
return datetime.date(int(year), int(month), int(day))
except (ValueError, AttributeError, TypeError):
print("error handling date ", strDate)
raise
| true |
3e0567d81aa20bf04a43d2959ae3fff8b71501ec | biam05/FPRO_MIEIC | /exercicios/RE05 Functions/sumNumbers.py | 955 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 24 11:47:09 2018
@author: biam05
"""
#
# DESCRIPTION of exercise 2:
#
# Write a Python function sum_numbers(n) that returns the sum of all positive
# integers up to and including n.
#
# For example: sum_numbers(10) returns the value 55 (1+2+3+. . . +10)
#
# Do NOT alter the function prototype given
#
# PASTE your code inside the function block below, paying atention to the right indentation
#
# Don't forget that your program should use the return keyword in the last instruction
# to return the appropriate value
#
def sum_numbers(n):
"""
returns the sum of all positive integers up to and including n
"""
#### MY CODE STARTS HERE ######################################
if n >= 0:
result = n
for i in range(n):
result += i
else:
result = 0
return result
#### MY CODE ENDS HERE ######################################## | true |
c0994074084e337bba081ca44c37d2d4d8553f8f | xtom0369/python-learning | /task/Learn Python The Hard Way/task33/ex33_py3.py | 368 | 4.15625 | 4 | space_number = int(input("Input a space number : "))
max_number = int(input("Input a max number : "))
i = 0
numbers = []
while i < max_number:
print(f"At the top i is {i}")
numbers.append(i)
i = i + space_number
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
| true |
27d0745e6199185dc5b1fb8d9739b2d0226fd606 | letaniaferreira/guessinggame | /game.py | 1,554 | 4.1875 | 4 | """A number-guessing game."""
# greet player
# get player name
# choose random number between 1 and 100
# repeat forever:
# get guess
# if guess is incorrect:
# give hint
# increase number of guesses
# else:
# congratulate player
import random
name = raw_input("Welcome, what is your name? ")
greeting = "Hello, %s, do you want to play a guessing game? " %(name)
print greeting
best_score = ""
def number_game():
random_number = random.randint(1,100)
user_guess = 0
count = 0
while user_guess != random_number:
user_guess = raw_input("Guess a number from 1 to 100: ")
try:
user_guess = int(user_guess)
#break
except ValueError:
print("Oops! That was an invalid number. Rounding number.")
user_guess = int(float(user_guess))
print user_guess
if user_guess > random_number:
print "Your guess is too high!"
count += 1
elif user_guess < random_number:
print "Your guess is too low!"
count += 1
elif user_guess < 1 or user_guess > 100:
print "Please enter a number between 1 and 100."
count += 1
else:
print "Well done, %s, You found the number in %s trials!" %(name,count)
return count
number_game()
# keep track of best score
greeting = raw_input("Would you like to play another round: ")
if greeting == 'yes':
number_game()
# if count < best_score:
else:
print "goodbye"
| true |
1532020913bb3d12e049d871a9d544fb0d5f4abc | KD4/TIL | /Algorithm/merge_two_sorted_lists.py | 1,227 | 4.1875 | 4 | # Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
# splice 꼬아 잇다
# 주어준 링크드리스트 두 개를 하나의 리스트로 만들어라. 두 리스트의 노드들을 꼬아서 만들어야한다.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
cur = None
result = None
while l1 is not None or l2 is not None:
if l2 is None or (l1 is not None and l1.val < l2.val):
if result is None:
result = l1
cur = l1
l1 = l1.next
else:
cur.next = l1
cur = l1
l1 = l1.next
else:
if result is None:
result = l2
cur = l2
l2 = l2.next
else:
cur.next = l2
cur = l2
l2 = l2.next
return result
| true |
b6364e51af1472c1eec2b3bef4e9aa5d68f4e2e4 | CHuber00/Simulation | /Sprint-1-Python_and_Descriptive_Statistics/Deliverables/MoreCalculations.py | 2,014 | 4.25 | 4 | """
Christian Huber
CMS 380, Fall 2020 / Sprint 1 / MoreCalculations
This script reads a text file's values and calculates and prints
the mean, median, variance, and standard deviation.
"""
from math import sqrt
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
def mean(x):
"""
Calculate and return the mean of input list x
"""
return sum(x) / len(x)
def median(x):
"""
Calculate and return the median of input list x
"""
values.sort()
# Calculate mean for middle indexes for even set
# Averaging middle two indexes
if(len(x)%2==0):
return ((x[int(len(x)/2)]+x[int(len(x)/2)-1])/2)
# Referencing the middle index of uneven set
else:
return(x[(int(len(x)/2))])
def variance(x):
"""
Calculate and return the variance of input list x
"""
m = mean(x)
# Create an array with the value of each (element - mean)^2
v = [((i-m)**2) for i in x]
return mean(v)
def sDeviation(x):
"""
Calculate and return the standard Deviation of
input list x
"""
return sqrt(variance(x))
values = []
# Read all data from the file into value list
with open("data.txt") as f:
data = f.readlines()
for line in data:
# Remove trailing whitespace
line = line.strip()
values.append(float(line))
dataMean = mean(values)
dataMedian = median(values)
dataVariance = variance(values)
dataSDeviation = sDeviation(values)
# Use matlibplot to output boxplot and histogram to pdf
plt.figure()
plt.boxplot(values)
plt.title("Data.txt Values visualization in Boxplot")
plt.xlabel("Data")
plt.ylabel("Values")
plt.savefig("MoreCalculationsBoxplot.pdf", bbox_inches = "tight")
plt.figure()
plt.hist(values,20)
plt.title("Data.txt Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.savefig("moreCalculationsHistogram.pdf", bbox_inches = "tight")
| true |
0779044e55eb618e79e6cc91c7d8d59e614713dc | yamiau/Courses | /[Udemy] Web Scraping with Python - BeautifulSoup, Requests, Selenium/00 Data Structures Refresher/List Comprehension 2.py | 777 | 4.21875 | 4 | '''Nested lists'''
carts = [['toothpaste', 'soap', 'toilet paper'], ['meat', 'fruit', 'cereal'], ['pencil', 'notebook', 'eraser']]
#or
person1 = ['toothpaste', 'soap', 'toilet paper']
person2 = ['meat', 'fruit', 'cereal']
person3 = ['pencil', 'notebook', 'eraser']
carts = [person1, person2, person3]
print(carts)
for value in carts:
print(value)
#print(my_list[row][column])
'''2D list'''
my_matrix = []
#range(start inclusive, stop exclusive, step)
for row in range(0, 25, 5):
row_list = []
for column in range(row, row+5):
row_list.append(column)
my_matrix.append(row_list)
print(my_matrix)
for row in my_matrix:
print(row)
'''Using list comprehension'''
new_matrix = [[column for column in range(row, row+5)] for row in range(0,25,5)]
print(new_matrix) | true |
16ab5543da15a3db9c80b7526c55e3745eadf2af | lithiumspiral/python | /calculator.py | 1,196 | 4.25 | 4 | import math
print('This calculator requires you to enter a function and a number')
print('The functions are as follows:')
print('S - sine')
print('C - cosine')
print('T - tangent')
print('R - square root')
print('N - natural log')
print('X 0- eXit the program')
f, v = input("Please enter a function and a value ").split(" ")
v = float(v)
while f != 'X' and f != 'x':
if f == 'S' or f == 's' :
calculation = math.sin(v)
print('The sine of your number is ', calculation)
elif f == 'C' or f == 'c' :
calculation = math.cos(v)
print('The cosine of your number is ', calculation)
elif f == 'T' or f == 't' :
calculation = math.tan(v)
print('The tangent of your number is ', calculation)
elif f == 'R' or f == 'r' :
calculation = math.sqrt(v)
print('The square root of your number is ', calculation)
elif f == 'N' or f == 'n' :
calculation = math.log10(v)
elif f == 'X' or f == 'x' :
print('Thanks for using the calculator')
if f != 'X' and f != 'x':
f, v = input("Please enter a function and a value ").split(" ")
v = float(v)
print('Thanks for using the calculator')
| true |
d508ae43c03ea8337d2d5dcfeb3ccfc75555df4d | Emma-2016/introduction-to-computer-science-and-programming | /lecture15.py | 1,958 | 4.34375 | 4 | # Class - template to create instance of object.
# Instance has some internal attributes.
class cartesianPoint:
pass
cp1 = cartesianPoint()
cp2 = cartesianPoint()
cp1.x = 1.0
cp2.x = 1.0
cp1.y = 2.0
cp2.y = 3.0
def samePoint(p1, p2):
return (p1.x == p2.x) and (p1.y == p2.y)
def printPoint(p):
print '(' + str(p.x) + ', ' + str(p.y) + ')'
# shallow equality -- 'is': given two things, do they point to exactly the same reference? (object)
# deep equality -- we can define. (value)
class cPoint():
#def __init__(self, x, y): create an instance, use 'self' to refer to that instance
#when call a class, it create an instance with all those internal attributes. __init__ create a pointer to that instance.
#You need access to that, so it calls it, passing in self as the pointer to the instance.
#That says, it has access to that piece of memory and now inside of that piece of memory, I can do thing like:
#define self.x to be the value passed in for x. That is create a variable name x and a value associated with it.
#self will always point to a particular instance
def __init__(self, x, y):
self.x = x
self.y = y
self.radius = math.sqrt(self.x * self.x + self.y * self.y)
self. angle = math.atan2(self.y, self.x)
def cartesian(self):
return (self.x, self.y)
def polar(self):
return (self.radius, self.angle)
def __str__(self): #print repretation
return '(' + str(self.x) + ', ' + str(self.y) + ')'
def __cmp__(self, other):
return cmp(self.x, other.x) and cmp(self.y, other.y)
#data hidding - one can only access instance values through defined methods. Python does not do this.
# operator overloading
class Segment():
def __init__(self, start, end):
self.start = start
self.end = end
def length(self):
return ((self.start.x - self.end.x) ** 2 + (self.start.y - self.end.y) ** 2) ** 0.5
#in fact, one should access the value through a defined method.
| true |
00ce7ddd2e3fe18691908492ddd2de4ebde05559 | ckceddie/OOP | /OOP_Bike.py | 878 | 4.25 | 4 | # OOP Bike
# define the Bike class
class bike(object):
def __init__ (self , price , max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print "bike's price is " + str(self.price)
print "maximum speed : " + str(self.max_speed)
print "the total miles : "+str(self.miles)
return self
def ride(self):
print "Riding : "
self.miles += 10
print "the miles is "+str(self.miles)
return self
def reverse(self):
print "Reversing : "
self.miles -= 5
print "the miles is "+str(self.miles)
return self
# create instances and run methods
bike1 = bike(99.99, 12)
bike1.displayInfo()
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
bike2=bike(1000,20)
bike2.displayInfo()
| true |
6604cf3f68749b72d0eeb22a76e03075d2b87a02 | jkbstepien/ASD-2021 | /graphs/cycle_graph_adj_list.py | 1,087 | 4.125 | 4 | def cycle_util(graph, v, visited, parent):
"""
Utility function for cycle.
:param graph: representation of a graph as adjacency list.
:param v: current vertex.
:param visited: list of visited vertexes.
:param parent: list of vertexes' parents.
:return: boolean value for cycle function.
"""
visited[v] = True
for u in graph[v]:
if not visited[u]:
parent[u] = v
cycle_util(graph, u, visited, parent)
elif visited[u] and parent[u] != v:
return True
return False
def cycle(graph, s=0):
"""
Function determines whether graph has a cycle.
:param graph: graph as adjacency list.
:param s: starting vertex.
:return: boolean value.
"""
n = len(graph)
visited = [False] * n
parent = [False] * n
return cycle_util(graph, s, visited, parent)
if __name__ == "__main__":
G = [[1, 3], [2, 0], [3, 1], [4, 0], [3]]
G2 = [[1, 3], [2, 0], [1], [4, 0], [3]]
G3 = [[1, 2], [2, 0], [0, 1]]
print(cycle(G))
print(cycle(G2))
print(cycle(G3))
| true |
5512e04c4832ad7b74e6a0ae7d3151643747dd8c | anmolparida/selenium_python | /CorePython/DataTypes/Dictionary/DictionaryMethods.py | 1,181 | 4.28125 | 4 | d = {'A': 1, 'B' : 2}
print(d)
print(d.items())
print(d.keys())
print(d.values())
print(d.get('A'))
print(d['A'])
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
print(my_dict)
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
print(my_dict)
"""
Removing elements from Dictionary
"""
print('\nRemoving elements from Dictionary')
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
squares[4] = 16
print(squares)
# removes last item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# print(squares) # Throws Error
"""
setdefault
"""
person = {'name': 'Phill', 'age': 22}
age = person.setdefault('age')
print('person = ',person)
print('Age = ',age) | true |
946d183421857c5896636eac5dcaa797091cb87a | aboyington/cs50x2021 | /week6/pset6/mario/more/mario.py | 480 | 4.15625 | 4 | from cs50 import get_int
def get_height(min=1, max=8):
"""Prompt user for height value."""
while True:
height = get_int("Height: ")
if height >= min and height <= max:
return height
def print_pyramid(n):
"""Print n height of half-pyramid to console."""
for i in range(1, n+1):
print(" "*(n-i) + "#"*i + " "*2 + "#"*i)
def main():
height = get_height()
print_pyramid(height)
if __name__ == "__main__":
main()
| true |
2b233d93ef2101f8833bbff948682add348fde63 | djanibekov/algorithms_py | /inversion_counting.py | 2,025 | 4.21875 | 4 | inversion_count = 0
def inversion_counter_conquer(first, second):
"""[This function counts #inversions while merging two lists/arrays ]
Args:
first ([list]): [left unsorted half]
second ([list]): [right unsorted half]
Returns:
[tuple]: [(first: merged list of left and right halves, second: #inversions)]
"""
i = 0
j = 0
length_of_first = len(first)
length_of_second = len(second)
inversion_count = 0
merged = []
#? looking for number of particular inversion
while (i < length_of_first) and (j < length_of_second):
if (first[i] > second[j]):
inversion_count += length_of_first - i
merged.append(second[j])
j = j + 1
else:
merged.append(first[i])
i = i + 1
#! extra check whether element is left
while i < len(first):
merged.append(first[i])
i = i + 1
while j < len(second):
merged.append(second[j])
j = j + 1
return merged, inversion_count
def list_divider_divide(array):
"""[This function divides the input list/array in to two parts recursively
by divide and conquer method till the base case.]
Args:
array ([list]): [given input]
Returns:
[int]: [final answer of the question "How many inversions did list hold?"]
[list]: [the sorted array/list of two derived lists "left" and "right"]
"""
length = len(array)
if(length == 1):
return array, 0
mid = length // 2
left = list_divider_divide(array[:mid])
right = list_divider_divide(array[mid:])
#? inversion_count holds the sum of all particular #inversion
merged, particular_inversions = inversion_counter_conquer(left[0], right[0])
inversion_count = particular_inversions + left[1] + right[1]
return merged, inversion_count
f_name = open("IntegerArray.txt")
integers = []
for integer in f_name:
integers.append(int(integer))
print(list_divider_divide(integers)[1])
| true |
63ca4f68c05708f2482045d06775fa5d7d22ea55 | loudan-arc/schafertuts | /conds.py | 1,574 | 4.1875 | 4 | #unlike with other programming languages that require parentheses ()
#python does not need it for if-else statements, but it works with it
fake = False
empty = None
stmt = 0
f = 69
k = 420
hz = [60, 75, 90, 120, 144, 240, 360]
if k > f:
print(f"no parentheses if condition: {k} > {f}")
if (k > f):
print(f"with parentheses if condition: {k} > {f}")
if not k==hz[5]:
print(f"variable {k=}, not {hz[5]}")
#not can be used in place of != inequality
#or just evaluating if a statement is false and accept it if false
#for fstrings in pythong, using {var_name=}
#will print the variable name with the actual value of it directly'
#you must include the = sign
#otherwise it will just print value, period
#-------------------
#CONDITIONALS
if fake == False:
print(f"Fake == {fake}, empty == {empty}")
#evalutes to print the fact that it is false
if not empty:
print("empty will also evaluate to False")
#while empty is strictly set to None, which means using "if empty == None"
#will be skipped by the program
#if you use "if not empty"
#it will like on the above example, try to evaluate to false
#and None will evaluate to False in this specific way, so it will print
#the statement, it will not skip
if stmt == 0:
print("0 is also false")
else:
print("True bruh")
#What evals to False:
# * any variable = False
# * any variable = None
# * any variable = 0
# * any variable = '', (), [] which is an empty list or tuple
# * any variable = {} empty dict
#-------------------
#LOOPING
| true |
4afceabb3673acbe934061dd9888d06e0457a152 | dark5eid83/algos | /Easy/palindrome_check.py | 330 | 4.25 | 4 | # Write a function that takes in a non-empty string that returns a boolean representing
# whether or not the string is a palindrome.
# Sample input: "abcdcba"
# Sample output: True
def isPalindrome(string, i=0):
j = len(string) - 1 - i
return True if i >= j else string[i] == string[j] and isPalindrome(string, i + 1) | true |
7ce3fe03de726250fbad7573e0f6a12afa5fcc4a | AshishKadam2666/Daisy | /swap.py | 219 | 4.125 | 4 | # Taking user inputs:
x = 20
y = 10
# creating a temporary variable to swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
| true |
bb155d4d67a7611506849ea6160074b6fec2d01f | kalpitthakkar/daily-coding | /problems/Jane_Street/P5_consCarCdr.py | 1,420 | 4.125 | 4 | def cons(a, b):
def pair(f):
return f(a, b)
return pair
class Problem5(object):
def __init__(self,
name):
self.name = name
# The whole idea of this problem is functional programming.
# Use the function cons(a, b) to understand the functional
# interface required to write functions car(f) and cdr(f).
# car/cdr takes a function as input => as cons(a,b) returns a
# function. The returned function takes a function as input,
# which has two arguments like cons => this inner function
# like cons can be made by us according to whether it is called
# from car or cdr.
def solver_car(self, f):
def first(x, y):
return x
return f(first)
def solver_cdr(self, f):
def last(x, y):
return y
return f(last)
def __repr__(self):
return "Problem #5 [Medium]: " + self.name + "\nThis problem was asked by Jane Street"
if __name__ == '__main__':
p = Problem5('Return first element of pair using car and second using cdr')
print(p)
x = cons(2, cons(cons(3, 4), 5))
car = getattr(p, 'solver_car')
cdr = getattr(p, 'solver_cdr')
print("Input: x = cons(2, cons(cons(3, 4), 5))")
print("Solution from solver for car function: car(x) = {}".format(car(x)))
print("Solution from solver for cdr function: cdr(cdr(x)) = {}".format(cdr(cdr(x))))
| true |
84f2c41dd849d194eb1bbdbb5abc97ae9f05bfcd | trishajjohnson/python-ds-practice | /fs_1_is_odd_string/is_odd_string.py | 974 | 4.21875 | 4 | def is_odd_string(word):
"""Is the sum of the character-positions odd?
Word is a simple word of uppercase/lowercase letters without punctuation.
For each character, find it's "character position" ("a"=1, "b"=2, etc).
Return True/False, depending on whether sum of those numbers is odd.
For example, these sum to 1, which is odd:
>>> is_odd_string('a')
True
>>> is_odd_string('A')
True
These sum to 4, which is not odd:
>>> is_odd_string('aaaa')
False
>>> is_odd_string('AAaa')
False
Longer example:
>>> is_odd_string('amazing')
True
"""
abcs = list('abcdefghijklmnopqrstuvwxyz')
count = 0
word = word.lower()
for letter in word:
idx = abcs.index(letter) + 1
count += idx
if count % 2 == 1:
return True
else:
return False
# Hint: you may find the ord() function useful here | true |
1991e34b3272b9374e485fb49abe10f2adfb7b3b | smirnoffmg/codeforces | /519B.py | 303 | 4.15625 | 4 | # -*- coding: utf-8 -*-
n = int(raw_input())
first_row = map(int, raw_input().split(' '))
second_row = map(int, raw_input().split(' '))
third_row = map(int, raw_input().split(' '))
print [item for item in first_row if item not in second_row]
print [item for item in second_row if item not in third_row] | true |
42e25fed3a11b28f2bd4eb5070ce2ff7034eeda1 | sanapplegates/Python_qxf2_exercises | /bmi.py | 288 | 4.28125 | 4 |
#calculate the bmi of user
#user height in kg
print("Enter the user's weight(kg):")
weight = int(input())
#user height in metres
print("Enter the user's height(metre) :")
height = int(input())
#Body Mass Index of user
bmi = weight/(height*height)
print("bmi of user:",bmi)
| true |
b88a715b7625b1b27f47e9cb6098e00e8e616f7e | lexruee/project-euler | /problem_9.py | 326 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc
"""
def main():
#TODO
pass
if __name__ == '__main__':main() | true |
91e717e2422ba6a54dcfef0de4292846b9fd1832 | Laavanya-Agarwal/Python-C2 | /Making functions/countWords.py | 271 | 4.3125 | 4 | def countWords():
fileName = input('Enter the File Name')
file = open(fileName, 'r')
noOfWords = 0
for line in file:
words = line.split()
noOfWords = noOfWords + len(words)
print('The number of words is ' + str(noOfWords))
countWords() | true |
3c54aa7bc9815de81888d9b40085067fa1cf218a | keryl/2017-03-24 | /even_number.py | 467 | 4.25 | 4 | def even_num(l):
# first, we will ensure l is of type "list"
if type(l) != list:
return "argument passed is not a list of numbers"
# secondly, check l is a list of numbers only
for n in l:
if not (type(n) == int or type(n) == float):
return "some elements in your list are not numbers"
# else find even numbers in it
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
| true |
8bd5806dd9b01c9eb90592e7239e8662ae9f1af5 | danny237/Python-Assignment3 | /insertion_sort.py | 541 | 4.1875 | 4 | """Insertion Sort"""
def insertion_sort(list1):
"""function for insertion sort"""
for i in range(1, len(list1)):
key = list1[i]
j = i-1
while j >=0 and key < list1[j] :
list1[j+1] = list1[j]
j -= 1
list1[j+1] = key
return list1
# user input
print('Enter list of number seperated by comma.')
print('Example: 1,2,3')
list_arr = [int(i) for i in input().strip().split(',')]
sorted_arr = insertion_sort(list_arr)
print(f'Sorted list: {sorted_arr}') | true |
adfba4e45bc9ec9707eeda09767bfde152600426 | reachtoakhtar/data-structure | /tree/problems/binary_tree/diameter.py | 776 | 4.125 | 4 | __author__ = "akhtar"
def height(root, ans):
if root is None:
return 0
left_height = height(root.left, ans)
right_height = height(root.right, ans)
# update the answer, because diameter of a tree is nothing but maximum
# value of (left_height + right_height + 1) for each node
ans[0] = max(ans[0], 1 + left_height + right_height)
return 1 + max(left_height, right_height)
def find_diameter(root):
"""
Find the diameter of a binary tree with given root.
:param BTreeNode root: The root of the tree.
:return: the diameter of the tree.
:rtype: int
"""
if root is None:
return 0
# This will store the final answer
ans = [-99999999999]
height(root, ans)
return ans[0]
| true |
7915e90dd431cedcd1820486783a299df813b0b9 | SoumyaMalgonde/AlgoBook | /python/sorting/selection_sort.py | 654 | 4.21875 | 4 | #coding: utf-8
def minimum(array, index):
length = len(array)
minimum_index = index
for j in range(index, length):
if array[minimum_index] > array[j]:
minimum_index = j
return minimum_index
def selection_sort(array):
length = len(array)
for i in range(length - 1):
minimum_index = minimum(array, i)
if array[i] > array[minimum_index]:
array[i], array[minimum_index] = array[minimum_index], array[i]
if __name__ == "__main__":
entry = input("Enter numbers separated by space: => ")
array = [int(x) for x in entry.split()]
selection_sort(array)
print(array)
| true |
3b68f1f217fd64cc0428e93fbfe17745c664cb2e | SoumyaMalgonde/AlgoBook | /python/maths/jaccard.py | 374 | 4.1875 | 4 |
a = set()
b = set()
m = int(input("Enter number elements in set 1: "))
n = int(input("Enter number elements in set 2: "))
print("Enter elements of set 1: ")
for i in range(m):
a.add(input())
print("Enter elements of set 2: ")
for i in range(n):
b.add(input())
similarity = len(a.intersection(b))/len(a.union(b))
print("Similarity index: {} ".format(similarity)) | true |
df7feb3e68df6d0434ed16f02ce3fcf0fd1dbf99 | SoumyaMalgonde/AlgoBook | /python/maths/Volume of 3D shapes.py | 2,970 | 4.1875 | 4 | import math
print("*****Volume of the Cube*****\n")
side=float(input("Enter the edge of the cube "))
volume = side**3
print("Volume of the cube of side = ",side," is " ,volume,)
print("\n*****Volume of Cuboid*****\n")
length=float(input("Enter the length of the cuboid "))
breadth=float(input("Enter the breadth of the cuboid "))
height=float(input("Enter the height of the cuboid "))
volume=length * breadth * height
print("Volume of the cuboid of length = ",length,", breadth = ",breadth,", height = ",height," is " ,volume)
print("\n*****Volume of cone*****\n")
radius = float(input("Enter the radius of the cone "))
height = float(input("Enter the height of the cone "))
volume = round((((math.pi)*(radius**2)*height)/3),2)
print("Volume of cone of radius = ",radius,", height = ", height, " is ", volume)
print("\n*****Volume of right circular cone*****\n")
radius = float(input("Enter the radius of the right circular cone "))
height = float(input("Enter the height of the right circular cone "))
volume = round((((math.pi)*(radius**2)*height)/3),2)
print("Volume of right circular cone of radius = ",radius,", height = ", height, " is ", volume)
print("\n*****Volume of a prism*****\n")
base_length = float(input("Enter the length of the base "))
base_breadth = float(input("Enter the breadth of the base "))
height = float(input("Enter the height of the prism"))
base_area = base_length * base_breadth
volume = base_area * height
print("Volume of prism of base area =",base_area,", height = ",height, " is ",volume)
print("\n*****Volume of different types of pyramid*****\n")
apothem = float(input("Enter the apothem length of the pyramid "))
base = float(input("Enter the base length of the pyramid "))
height = float(input("Enter the height of the pyramid "))
volume_square = ((base**2)*height)/3
volume_triangle = (apothem * base * height)/6
volume_pentagon = (5 * apothem * base * height)/6
volume_hexagon = apothem * base * height
print("\nVolume of a square pyramid of base = ",base,", height = ",height, " is ", volume_square)
print("Volume of a triangular pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_triangle)
print("Volume of a pentagonal pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_pentagon)
print("Volume of a hexagonal pyramid of apothem = ", apothem, ", base = ",base,", height = ",height, " is ", volume_hexagon)
print("\n*****Volume of Sphere*****\n")
radius = float(input("Enter the radius of the sphere "))
volume = round((4 * (math.pi) * (radius**3))/3)
print("Volume of the sphere of radius = ",radius," is ",volume)
print("\n*****Volume of circular cylinder*****\n")
radius = float(input("Enter the radius of the circular cylinder "))
height = float(input("Enter the height of the circular cylinder "))
volume = round((math.pi) * (radius**2) * height)
print("Volume of the circular cylinder of radius = ",radius,", height = ",height," is ",volume) | true |
bb114c561547aa3adbcf855e3e3985e08c748a01 | SoumyaMalgonde/AlgoBook | /python/sorting/Recursive_quick_sort.py | 834 | 4.1875 | 4 | def quick_sort(arr, l, r): # arr[l:r]
if r - l <= 1: # base case
return ()
# partition w.r.t pivot - arr[l]
# dividing array into three parts one pivot
# one yellow part which contains elements less than pivot
# and last green part which contains elements greater than pivot
yellow = l + 1
for green in range(l+1, r):
if arr[green] <= arr[l]:
arr[yellow], arr[green] = arr[green], arr[yellow]
yellow += 1
# move pivot into place
arr[l], arr[yellow - 1] = arr[yellow - 1], arr[l]
quick_sort(arr, l, yellow-1) # recursive calls
quick_sort(arr, yellow, r)
return arr
print("Enter elements you want to sort: ")
array = list(map(int, input().split()))
sorted_array = quick_sort(array, 0, len(array))
print("Sorted array is: ", *sorted_array) | true |
edb2d3e1a9f09ce94933b8b223af17dda52143a3 | SunshinePalahang/Assignment-5 | /prog2.py | 327 | 4.15625 | 4 | def min_of_3():
a = int(input("First number: "))
b = int(input("Second number: "))
c = int(input("Third number: "))
if a < b and a < c:
min = a
elif b < a and b < c:
min = b
else:
min = c
return min
minimum = min_of_3()
print(f"The lowest of the 3 numbers is {minimum}") | true |
34a2bfbe98dfb42c1f3d2a8f444da8e49ca04639 | PaxMax1/School-Work | /fbi.py | 1,610 | 4.25 | 4 | # a322_electricity_trends.py
# This program uses the pandas module to load a 3-dimensional data sheet into a pandas DataFrame object
# Then it will use the matplotlib module to plot comparative line graphs
import matplotlib.pyplot as plt
import pandas as pd
# choose countries of interest
my_countries = ['United States', 'Zimbabwe','Cuba', 'Caribbean small states', "Cameroon", "Burundi"]
# Load in the data with read_csv()
df = pd.read_csv("elec_access_data.csv", header=0) # header=0 means there is a header in row 0
# get a list unique countries
unique_countries = df['Entity'].unique()
# Plot the data on a line graph
for c in unique_countries:
if c in my_countries:
# match country to one of our we want to look at and get a list of years
years = df[df['Entity'] == c]['Year']
# match country to one of our we want to look at and get a list of electriciy values
sum_elec = df[df['Entity'] == c]['Access']
plt.plot(years, sum_elec, label=c,)
plt.ylabel('Percentage of Country Population')
plt.xlabel('Year')
plt.title('Percent of Population with Access to Electricity')
plt.legend()
plt.show()
# CQ1- A countrys access to electricity can affect its access to computing innovations because computers require electricity and power to opperate.
# If you don't have electricity to run a computer, than you can't use your computer and have access to it's innovations.
# CQ2- Analyzing data like this can affect global change because we can see what countrys have issues in the world so that other countrys that are more advanced can help get them up on their feet.
| true |
c275468117aa43e59ac27afd391e463d0983a979 | gevishahari/mesmerised-world | /integersopr.py | 230 | 4.125 | 4 | x=int(input("enter the value of x"))
y=int(input("enter the value of y"))
if(x>y):
print("x is the largest number")
if(y>x):
print("y is the largest number")
if (x==y):
print("x is equal to y")
print("they are equal") | true |
d76dfe561f9111effed1b82da602bf6df98f2405 | AdmireKhulumo/Caroline | /stack.py | 2,278 | 4.15625 | 4 | # a manual implementation of a stack using a list
# specifically used for strings
from typing import List
class Stack:
# initialise list to hold items
def __init__(self):
# initialise stack variable
self.stack: List[str] = []
# define a property for the stack -- works as a getter
@property
def stack(self) -> List[str]:
return self._stack
# define a setter for the property
@stack.setter
def stack(self, new_stack: List[str]) -> None:
# ensure proper format
if isinstance(new_stack, List):
# assign private stack wit new value
self._stack = new_stack
else:
# improper input, deny and raise an error
raise ValueError("Must be a list of strings, i.e List[str]")
# push method adds to top of stack
def push(self, item: str) -> None:
if type(item) == str:
self.stack.append(item)
else:
raise ValueError("Must supply a string")
# pop method removes from top of stack
def pop(self) -> str:
# get top item
item: str = self.stack[-1]
# delete top item
del self.stack[-1]
# return top item
return item
# peek method retrieves the item at the top of the stack without removing it
def peek(self) -> str:
return self.stack[-1]
# size returns the number of elements in the stack
def size(self) -> int:
return len(self.stack)
# check if the stack is empty
def is_empty(self) -> bool:
return len(self.stack) == 0
# reverse method
def reverse(self) -> None:
# create a new stack
new_stack: Stack = Stack()
# iterate through current stack and push to new stack
while not self.is_empty():
new_stack.push(self.stack.pop())
# assign new_stack to old_stack
self.stack = new_stack.stack
# dunder methods -- kinda unnecessary here to be honest
# len works the same as size() above
def __len__(self) -> int:
return len(self.stack)
# repr returns a string representation of the stack
def __repr__(self) -> str:
string: str = ''
for item in self.stack:
str += item
return string
| true |
71021e7cf21f47c13df7be87afe4e169eb945ab5 | jessicazhuofanzh/Jessica-Zhuofan--Zhang | /assignment1.py | 1,535 | 4.21875 | 4 | #assignment 1
myComputer = {
"brand": "Apple",
"color": "Grey",
"size": 15.4,
"language": "English"
}
print(myComputer)
myBag = {
"color": "Black",
"brand": "MM6",
"bagWidth": 22,
"bagHeight": 42
}
print(myBag)
myApartment = {
"location": "New York City",
"type": "studio",
"floor": 10,
"color": "white and wood"
}
print(myApartment)
myBreakfast = {
"cost": "5 dollars",
"drink": "pink drink",
"food": "egg and bacon",
"calorie": 500
}
print(myBreakfast)["food"]
#assignment 2
{
"name": "amy",
"location": "garden",
"genus": "flower",
"species": "rose",
"count": 5,
"spined": False
}
#assignment 3
print ("Welcome to New York City")
print ("Answer the questions below to create your story in NYC")
print ("-------------------------")
adjective1 = raw_input("Enter an adjective: ")
color1 = raw_input("What is your favorite color?: ")
country1 = raw_input("Which country you come from?: ")
number1 = raw_input("Enter any number between 1-100: ")
place1 = raw_input("Enter your favorite area in NYC: ")
person1 = raw_input("Enter your favorite movie star: ")
person2 = raw_input("Enter your favorite singer: ")
story = " I arrived New York City on a" + adjective1 + "day," \
"carrying a" + color1 + "suitcase which I bought in" + country1 + "." \
"It will take" + number1 + "minutes to my apartment, " \
"which located in" + place1 + "." \
"I fount out that" + person1 + "and" + person2 + "is my neighbor. " \
print(story)
| true |
15774b26dae087e6ec683e676046c29d2009b904 | devimonica/Python-exercises---Mosh-Hamedani-YT- | /4.py | 490 | 4.5 | 4 | # Write a function called showNumbers that takes a parameter called limit. It should
# print all the numbers between 0 and limit with a label to identify the even and odd numbers. For example,
# if the limit is 3, it should print:
# 0 EVEN
# 1 ODD
# 2 EVEN
# 3 ODD
# Solution:
def showNumbers(limit):
for number in range(0, limit+1):
if number % 2 == 0:
print(f'{number} EVEN')
else:
print(f'{number} ODD')
showNumbers(5)
| true |
d5d3b540482b581ad95e5a4d4ab4e8dbcc1280fd | gninoshev/SQLite_Databases_With_Python | /delete_records.py | 411 | 4.1875 | 4 | import sqlite3
# Connect to database
conn = sqlite3.connect("customer.db")
# Create a cursor
c = conn.cursor()
# Order By Database - Order BY
c.execute("SELECT rowid,* FROM customers ORDER BY rowid ")
# Order Descending
c.execute("SELECT rowid,* FROM customers ORDER BY rowid DESC")
items = c.fetchall()
for item in items:
print(item)
# Close out connection
conn.close()
| true |
5a0637856f9dddcb3d6667340def81e831361c7d | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 20 and 21 February 2021/03. Computer Room.py | 755 | 4.25 | 4 | month = input()
hours = int(input())
people_in_group = int(input())
time_of_the_day = input()
per_hour = 0
if month == "march" or month == "april" or month == "may":
if time_of_the_day == "day":
per_hour = 10.50
elif time_of_the_day == "night":
per_hour = 8.40
elif month == "june" or month == 'july' or month == "august":
if time_of_the_day == "day":
per_hour = 12.60
elif time_of_the_day == "night":
per_hour = 10.20
if people_in_group >= 4:
per_hour *= 0.9
if hours >= 5:
per_hour *= 0.5
price_per_person = per_hour
total_price = (price_per_person * people_in_group) * hours
print(f"Price per person for one hour: {price_per_person:.2f}")
print(f"Total cost of the visit: {total_price:.2f}") | true |
bb2ff59d2062a5b6ab007782f05653c2fd7fb1c1 | Ramya74/ERP-projects | /Employee.py | 1,296 | 4.25 | 4 | employees = [] #empty List
while True:
print("1. Add employee")
print("2. Delete employee")
print("3. Search employee")
print("4. Display all employee")
print("5. Change a employee name in the list")
print("6. exit")
ch = int(input("Enter your choice: "))
if ch is None:
print("no data present in Employees")
elif ch == 1:
#Add employee
name = input("Enter name: ")
employees.append(name)
#in one line
#employees.append(input("Enter name: "))
elif ch == 2:
#Delete employee
print(employees)
print("Choose name from this: ")
name = input("Enter name to delete: ")
employees.remove(name)
elif ch == 3:
#Search employee
name = input("Enter name you want to search: ")
if name in employees:
print(name + " is in the list")
else:
print(name + " not in the list")
elif ch == 4:
#Display employee
#print("---['r','t']---like output")
#print(employees)
for i in range(0,len(employees)):
print(i+1,".",employees[i])
i+=1
elif ch== 5:
#Change a employee name in the list
name = input("Enter the name: ")
index = employees.index(name)
new_name = input("Enter new name: ")
employees[index] = new_name
#employees[employees.index(name)] = input("Enter new name: ")
elif ch == 6:
#Exit
break;
else:
print("Invalid Choice")
| true |
5491efb3841bc753f8de6fff6b0f5233c132a805 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day22/Remove_Duplicates_in_Dictionary.py | 364 | 4.21875 | 4 | def Remove_Duplicates(Test_string):
Test_list = []
for elements in Test_string.split(" "):
if ((Test_string.count(elements) > 1 or Test_string.count(elements) == 1) and elements not in Test_list):
Test_list.append(elements)
return Test_list
Test_string = input("Enter a String: ")
print(*(Remove_Duplicates(Test_string))) | true |
f2f47ab9d8e116d43c619e88b3db0807b4d658f9 | saubhagyav/100_Days_Code_Challenge | /DAYS/Day10/String_Palindrome.py | 203 | 4.1875 | 4 | def Palindrome(Test_String):
if Test_String == Test_String[::-1]:
return True
else:
return False
Test_String = input("Enter a String: ")
print(Palindrome(Test_String))
| true |
bb1a8090d3fc97546339037bbc0e9b06ff43b438 | 3point14guy/Interactive-Python | /strings/count_e.py | 1,153 | 4.34375 | 4 | # Assign to a variable in your program a triple-quoted string that contains your favorite paragraph of text - perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.
#
# Write a function that counts the number of alphabetic characters (a through z, or A through Z) in your text and then keeps track of how many are the letter ‘e’. Your function should print an analysis of the text like this:
#
# Your text contains 243 alphabetic characters, of which 109 (44.8%) are 'e'.
import string # has sets of characters to use with 'in' and 'not in'
letters = string.ascii_lowercase + string.ascii_uppercase
strng = """The stump thunk the skunk stunk and the skunk thunk the stump stunk."""
def count(p):
#count characters, "e", and calc % "e"
counter = 0
e = 0
for char in p:
if char in letters:
counter = counter + 1
if char == "e" or char == "E":
e = e + 1
perc = e / counter * 100
return counter, e, perc
#returns a set
ans = count(strng)
print("Your text contains {} alphabetic characters, of which {} ({:.2}%) are 'e'.".format(ans[0], ans[1], ans[2]))
| true |
11992691b92d6d74aa41fe6797f70f810ea3bfb9 | 3point14guy/Interactive-Python | /tkinter/hello_world_tkinter.py | 1,249 | 4.15625 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import simpledialog
window = tk.Tk()
# my_label = ttk.Label(window, text="Hello World!")
# my_label.grid(row=1, column=1)
# messagebox.showinfo("Information", "Information Message")
# messagebox.showerror("Error", "My error message")
# messagebox.showwarning("WARNING!", "Warning message")
# answer = messagebox.askokcancel("QUESTION", "DO YOU WANT TO OPEN A FILE?")
# answer = messagebox.askretrycancel("Question", "Do you want to try again?")
# answer = messagebox.askyesno("Question", "Do you like Python?")
# answer = messagebox.askyesnocancel("Hey You!", "Continue playing?")
answer = simpledialog.askstring("input", "WHat is your first name?", parent=window)
if answer is not None:
print("Hello ", answer)
else:
print("hello annonymous user")
answer = simpledialog.askinteger("input", "What is your age", parent=window, minvalue=0, maxvalue=100)
if answer is not None:
my_label = ttk.Label(window, text="Wow, I am {} too!".format(answer))
my_label.grid(row=10, column=20)
else:
my_label = ttk.Label(window, text="Most people who feel old won't enter their age either.")
my_label.grid(row=10, column=20)
window.mainloop()
| true |
da34092f0d87be4f33072a3e2df047652fb29cf3 | sudj/24-Exam3-201920 | /src/problem2.py | 2,658 | 4.125 | 4 | """
Exam 3, problem 2.
Authors: Vibha Alangar, Aaron Wilkin, David Mutchler, Dave Fisher,
Matt Boutell, Amanda Stouder, their colleagues and
Daniel Su. January 2019.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the TEST functions in this module. """
run_test_shape()
def run_test_shape():
""" Tests the shape function. """
print()
print('--------------------------------------------------')
print('Testing the SHAPE function:')
print('There is no automatic testing for this one; just compare it'
'to the expected output given in the comments:')
print('--------------------------------------------------')
print()
print('Test 1 of shape: n=5')
shape(5)
print()
print('Test 2 of shape: n=3')
shape(3)
print()
print('Test 3 of shape: n=9')
shape(9)
def shape(n):
####################################################################
# IMPORTANT: In your final solution for this problem,
# you must NOT use string multiplication.
####################################################################
"""
Prints a shape with numbers on the left side of the shape,
other numbers on the right side of the shape,
and stars in the middle, per the pattern in the examples below.
You do NOT need to deal with any test cases where n > 9.
It looks like this example for n=5:
11111*
2222*1
333*12
44*123
5*1234
And this one for n=3:
111*
22*1
3*12
And this one for n=9:
111111111*
22222222*1
3333333*12
444444*123
55555*1234
6666*12345
777*123456
88*1234567
9*12345678
:type n: int
"""
# ------------------------------------------------------------------
# DONE: 2. Implement and test this function.
# Some tests are already written for you (above).
####################################################################
# IMPORTANT: In your final solution for this problem,
# you must NOT use string multiplication.
####################################################################
for k in range(n):
for j in range(n - k):
print(k + 1, end='')
if k == 0:
print('*')
else:
print('*', end='')
for l in range(k):
if l == (k - 1):
print(l + 1)
else:
print(l + 1, end='')
# ----------------------------------------------------------------------
# Calls main to start the ball rolling.
# ----------------------------------------------------------------------
main()
| true |
b2e763e72dd93b471294f997d2c18ab041ad665c | Evanc123/interview_prep | /gainlo/3sum.py | 1,274 | 4.375 | 4 | '''
Determine if any 3 integers in an array sum to 0.
For example, for array [4, 3, -1, 2, -2, 10], the function
should return true since 3 + (-1) + (-2) = 0. To make things simple,
each number can be used at most once.
'''
'''
1. Naive Solution is to test every 3 numbers to test if it is zero
2. is it possible to cache sum every two numberse, then see if the rest make zero?
Insight: we need enough "power" in the negative numbers to reduce the positive numbers.
Count up the negative numbers summed to see the maximum negative number.
Possibly create some sort of binary search tree, where all the sums are the roots? No
that wouldn't work.
'''
def sum_2(arr, target):
dict = {}
for i in range(len(arr)):
complement = target - arr[i]
if complement in dict:
return True
dict[arr[i]] = i
return False
def sum_3(arr):
arr.sort()
for i in range(len(arr)):
if sum_2(arr[:i] + arr[i+1:], -arr[i]):
return True
return False
test = [4, 3, -1, 2, -2, 10]
assert sum_3(test) == True
test = [4, -4, 0]
assert sum_3(test) == True
test = [4, -3, -1]
assert sum_3(test) == True
test = [0, 0, 1]
assert sum_3(test) == False
test = [0, 2, -1, -5, 20, 10, -2]
assert sum_3(test) == True
| true |
5ebd4c91bd2fd1b34fbfdcff3198aef77ceb8612 | CrazyCoder4Carrot/lintcode | /python/Insert Node in a Binary Search Tree.py | 1,676 | 4.25 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
"""
Revursive version
"""
class Solution:
"""
@param root: The root of the binary search tree.
@param node: insert this node into the binary search tree.
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
if not root:
root = node
return root
if root.val > node.val:
if not root.left:
root.left = node
else:
self.insertNode(root.left, node)
return root
else:
if not root.right:
root.right = node
else:
self.insertNode(root.right, node)
return root
"""
Iteration version
"""
class Solution:
"""
@param root: The root of the binary search tree.
@param node: insert this node into the binary search tree.
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
if not root:
root = node
return root
cur = root
while cur:
if cur.val > node.val:
if cur.left:
cur = cur.left
else:
cur.left = node
break
else:
if cur.right:
cur = cur.right
else:
cur.right = node
break
return root
"""
Refined iteration version
"""
| true |
0046fd9fa359ebfaa81b7fb40ecf2c5f6d278273 | sfagnon/stephane_fagnon_test | /QuestionA/QaMethods.py | 1,120 | 4.21875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Verify if the two positions provided form a line
def isLineValid(line_X1,line_X2):
answer = True
if(line_X1 == line_X2):
answer = False
print("Points coordinates must be different from each other to form a line")
return answer
#Verify if the two positions provided form respectively the lower bound and the upper bound of #the line
def verifyLineCoordinates(line):
line_X1 = line[0]
line_X2 = line[1]
#Swap the line's bounds
if(line_X1 > line_X2):
temporary_point = line_X1
line_X1 = line_X2
line_X2 = temporary_point
print("Line Coordinates\' bounds have been swapped from X1 = "+str(line_X2)+" and X2 = "+str(line_X1)+ "\n Line is now: ("+str(line_X1)+","+str(line_X2)+")")
line = [line_X1,line_X2]
return line
#Check if a position bound belongs to a line interval (represented by its bounds)
def isValueInInterval(value,lower_bound,upper_bound):
answer = False
if((lower_bound<=value) and (upper_bound>=value)):
answer = True
return answer
| true |
1916ef020df5cb454e7887d2d4bb051d308887e3 | sammysun0711/data_structures_fundamental | /week1/tree_height/tree_height.py | 2,341 | 4.15625 | 4 | # python3
import sys
import threading
# final solution
""" Compute height of a given tree
Height of a (rooted) tree is the maximum depth of a node,
or the maximum distance from a leaf to the root.
"""
class TreeHeight:
def __init__(self, nodes):
self.num = len(nodes)
self.parent = nodes
self.depths = [0] * self.num
def path_len(self, node_id):
""" Returns path length from given node to root."""
parent = self.parent[node_id]
if parent == -1:
return 1
if self.depths[node_id]:
return self.depths[node_id]
self.depths[node_id] = 1 + self.path_len(self.parent[node_id])
return self.depths[node_id]
def compute_height(self):
""" Computes the tree height."""
return max([self.path_len(i) for i in range(self.num)])
'''
# original solution
def compute_height(n, parents):
# Replace this code with a faster implementation
max_height = 0
for vertex in range(n):
height = 0
current = vertex
while current != -1:
height += 1
current = parents[current]
max_height = max(max_height, height)
return max_height
'''
'''
# alternativ solution, explicit build tree and use recursiv compute_height,
# not use cache to store intermediate depth of node,not quick as original solution
def build_tree(root_node, nodes):
children = [
build_tree(child, nodes)
for child, node in enumerate(nodes)
if node == root_node
]
print(children)
return {'key': root_node, 'children':children}
def compute_height(tree):
return 1 + max((compute_height(child) for child in tree['children']), default=-1)
'''
def main():
'''
n = int(input())
parents = list(map(int, input().split()))
print(compute_height(n, parents))
'''
input()
nodes = list(map(int, input().split()))
tree = TreeHeight(nodes)
print(tree.compute_height())
# In Python, the default limit on recursion depth is rather low,
# so raise it here for this problem. Note that to take advantage
# of bigger stack, we have to launch the computation in a new thread.
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
threading.Thread(target=main).start() | true |
7cafa9fc6b348af6d2f11ad8771c5cca59b1bea7 | irina-baeva/algorithms-with-python | /data-structure/stack.py | 1,702 | 4.15625 | 4 | '''Imlementing stack based on linked list'''
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def insert_first(self, new_element):
"Insert new element as the head of the LinkedList"
new_element.next = self.head
self.head = new_element
def delete_first(self):
"Delete the first (head) element in the LinkedList as return it"
if self.head:
deleted_element = self.head
temp = deleted_element.next
self.head = temp
return deleted_element
else:
return None
class Stack(object):
def __init__(self,top=None):
self.ll = LinkedList(top)
def push(self, new_element):
"Push (add) a new element onto the top of the stack"
self.ll.insert_first(new_element)
def pop(self):
"Pop (remove) the first element off the top of the stack and return it"
return self.ll.delete_first()
# Test cases
# Set up some Elements
e1 = Element(5)
e2 = Element(20)
e3 = Element(30)
e4 = Element(40)
# Start setting up a Stack
stack = Stack(e1)
# Test stack functionality
stack.push(e2)
stack.push(e3)
print(stack.pop().value) #30
print (stack.pop().value) #20
print (stack.pop().value) # 5
print (stack.pop())
stack.push(e4)
print (stack.pop().value) | true |
01ece2001beaf028b52be310a8f1df24858f4e59 | amitesh1201/Python_30Days | /OldPrgms/Day3_prc05.py | 579 | 4.375 | 4 | # Basic String Processing : four important options: lower, upper, capitalize, and title.
# In order to use these methods, we just need to use the dot notation again, just like with format.
print("Hello, World!".lower()) # "hello, world!"
print("Hello, World!".upper()) # "HELLO, WORLD!"
print("Hello, World!".capitalize()) # "Hello, world!"
print("Hello, World!".title()) # "Hello, World!"
# Use the strip method remto remove white space from the ends of a string
print(" Hello, World! ".strip()) # "Hello, World!"
| true |
b9151241f8234f5c1f038c733a5d0ff46da376d3 | louishuynh/patterns | /observer/observer3.py | 2,260 | 4.15625 | 4 | """
Source: https://www.youtube.com/watch?v=87MNuBgeg34
We can have observable that can notify one group of subscribers for one kind of situation.
Notify a different group of subscribers for different kind of situation.
We can have the same subscribers in both groups.
We call these situations events (different kinds of situations) or channels.
This gives us the flexibility of how we notify subscribers.
"""
class Subscriber:
""" Sample observer. """
def __init__(self, name):
self.name = name
def update(self, message):
print('{} got message "{}"'.format(self.name, message))
class Publisher:
def __init__(self, events):
"""
We want to provide interface that allows subscribers to register for a specific event that the observable can announce.
So we modify a publisher to take several events and modify the subscriber attribute to
map event names to strings to dictionaries that then map subscribers to their callback function
"""
self.subscribers = {event: dict() for event in events}
def get_subscribers(self, event):
""" Helper method.
Look up for a given even the map of subscriber to the callback function.
"""
return self.subscribers[event]
def register(self, event, who, callback=None):
""" Change the way we insert the subscriber to our records of the callback."""
if callback is None:
# fallback to original method
callback = getattr(who, 'update')
self.get_subscribers(event)[who] = callback
def unregister(self, event, who):
del self.get_subscribers(event)[who]
def dispatch(self, event, message):
""" We keep the api interface fairly similar."""
for subscriber, callback in self.get_subscribers(event).items():
callback(message)
if __name__ == '__main__':
pub = Publisher(['lunch', 'dinner'])
bob = Subscriber('Bob')
alice = Subscriber('Alice')
john = Subscriber('John')
pub.register("lunch", bob)
pub.register("dinner", alice)
pub.register("lunch", john)
pub.register("dinner", john)
pub.dispatch("lunch", "It's lunchtime!")
pub.dispatch("dinner", "Dinner is served") | true |
e2ef440e9f140b93cb1adc8bf478baf2beae8fa3 | timmichanga13/python | /fundamentals/oop/demo/oop_notes.py | 1,389 | 4.25 | 4 | # Encapsulation is the idea that an instance of the class is responsible for its own data
# I have a bank account, teller verifies account info, makes withdrawal from acct
# I can't just reach over and take money from the drawer
# Inheritance allows us to pass attributes and methods from parents to children
# Vehicles are a class that can carry cargo and passengers
# we wouldn't create vehicles, but we would create classes that inherit from our vehicle class:
# wheeled vehicles with wheels, aquatic vehicle that floats, winged vehicle that flies, living vehicles like a horse
# all require fuel, but it's different for each subclass
# multiple inheritance - a class can inherit from multiple classes
# Polymorphism - many forms, classes that are similar can behave similarly
# can have x = 34, y = 'hello!', z = {'key_a': 2883, 'key_b': 'a word!'}
# can find the length of each; len(x), len(y), len(z)
# each gives us a length, but differs based on the type of info (number of items, number of letters)
# Abstraction: an extension of encapsulation, we can hide things that a class doesn't need to know about
# a class can use methods of another class without needing to know how they work
# we can drive a car, fill tank with gas, might not be able to change oil but can take it somewhere to get oil changed
# can't make a car out of raw materials, but still know how to drive it
| true |
95eaa4c8b527c0ac22bbd95dcfc30dad1fc836ad | notwhale/devops-school-3 | /Python/Homework/hw09/problem6.py | 973 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Решить несколько задач из projecteuler.net
Решения должны быть максимально лаконичными, и использовать list comprehensions.
problem6 - list comprehension : one line
problem9 - list comprehension : one line
problem40 - list comprehension
problem48 - list comprehension : one line
Sum square difference
Problem 6
The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
print(sum([_ for _ in range(1, 101)]) ** 2 - sum(map(lambda x: x**2, [_ for _ in range(1, 101)])))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.