blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d386ca487ac4ea2b315a6dc8d92b8f3ad6766867 | rishavghosh605/Competitive-Coding | /daily coding problem/Facebook/Find Itinerary from a given list of tickets.py | 1,956 | 4.21875 | 4 | """
This problem was asked by Facebook.
Given an unordered list of flights taken by someone, each represented as (origin, destination) pairs, and a starting airport, compute the person's itinerary. If no such itinerary exists, return null. If there are multiple possible itineraries, return the lexicographically smallest one. All flights must be used in the itinerary.
For example, given the list of flights [('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')] and starting airport 'YUL', you should return the list ['YUL', 'YYZ', 'SFO', 'HKO', 'ORD'].
Given the list of flights [('SFO', 'COM'), ('COM', 'YYZ')] and starting airport 'COM', you should return null.
Given the list of flights [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')] and starting airport 'A', you should return the list ['A', 'B', 'C', 'A', 'C'] even though ['A', 'C', 'A', 'B', 'C'] is also a valid itinerary. However, the first one is lexicographically smaller.
"""
def create_Hash_Map(flight_plan):
hmap={}
for origin,destination in flight_plan:
if origin not in hmap.keys():
hmap[origin]=[destination]
else:
hmap[origin]+=destination
hmap[origin]=sorted(hmap[origin])
print(hmap)
return hmap
def find_itinerary(flight_plan,origin):
hmap=create_Hash_Map(flight_plan)
itinerary=list()
itinerary.append(origin)
while(True):
if origin not in hmap.keys() or hmap[origin] == []:
break
destination = hmap[origin][0]
itinerary.append(destination)
hmap[origin]=hmap[origin][1:]
origin=destination
return itinerary if len(itinerary)-1 == len(flight_plan) else None
if __name__=="__main__":
flight_plan=[('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')]
origin=input("Enter the origin of the intinerary: ")
itinerary=find_itinerary(flight_plan,origin)
print(itinerary)
| true |
dff8383e51ec14e8f0b5965eecacbb8f2c40d42f | manojnayakkuna/leetcode_easy | /misc_algorithms/reverseLinkedList.py | 1,246 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 20 19:08:43 2020
@author: manoj
"""
class Node:
def __init__ (self,data):
self.data = data
self.next = None
class linkedList:
def __init__(self):
self.head = None
def printLinkedList(self):
temp = self.head
print ('Linked List Value: ', end='')
while (temp is not None):
print (temp.data, end=' ')
temp = temp.next
print ()
def reverseLinkedList(self):
prevNode = None
currNode = self.head
while currNode is not None:
nextNode = currNode.next
currNode.next = prevNode
prevNode = currNode
currNode = nextNode
#currNode.next = prevNode
self.head = prevNode
linkedList1 = linkedList()
linkedList1.head = Node(1)
nextNode2 = Node(2)
nextNode3 = Node(3)
nextNode4 = Node(4)
nextNode5 = Node(5)
linkedList1.head.next = nextNode2
nextNode2.next = nextNode3
nextNode3.next = nextNode4
nextNode4.next = nextNode5
print ('Display Newly Created Linked List')
linkedList1.printLinkedList()
print ('Display Reversed Linked List')
linkedList1.reverseLinkedList()
linkedList1.printLinkedList() | true |
60857fe08e60a9f65344763b943fa7c2b3336416 | manojnayakkuna/leetcode_easy | /problems/leetcode_206_reverseLinkedList.py | 887 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 14:50:01 2020
@author: manoj
"""
class LinkedList:
def __init__(self,val):
self.val = val
self.next = None
def reverseLinkedList(head):
if head is None:
return -1
prevNode = None
currNode = head
nextNode = None
while currNode is not None:
nextNode = currNode.next
currNode.next = prevNode
prevNode = currNode
currNode = nextNode
print ('*******AFT prevNode:',prevNode.val,'currNode:',currNode,'nextNode:',nextNode)
return prevNode
def printLinkedList(head):
while head is not None:
print (head.val,end=' ')
head=head.next
Node1 = LinkedList(1)
Node2 = LinkedList(2)
Node1.next = Node2
Node3 = LinkedList(3)
Node2.next = Node3
printLinkedList(Node1)
Node1 = reverseLinkedList(Node1)
print ()
printLinkedList(Node1) | false |
0d5baef8a0feb9b07ac3773a8a1e15b47355ef87 | manojnayakkuna/leetcode_easy | /problems/leetcode_1360_numberDaysBetweenTwoDates.py | 2,274 | 4.5 | 4 | # -*- coding: utf-8 -*-
"""
Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Example 1: Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1
Example 2: Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
"""
# 81%
def daysBetweenDates(date1, date2):
def isLeapYear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return True
return False
date1Y, date1M, date1D = map(int,date1.split('-'))
date2Y, date2M, date2D = map(int,date2.split('-'))
leapYear = [31,29,31,30,31,30,31,31,30,31,30,31]
nonLeapYear = [31,28,31,30,31,30,31,31,30,31,30,31]
T1, T2 = 0, 0
if date1Y > date2Y:
for i in range(date2Y, date1Y):
T1 += 366 if (isLeapYear(i)) else 365
T1 += sum(leapYear[:date1M-1])+date1D if (isLeapYear(date1Y)) else sum(nonLeapYear[:date1M-1])+date1D
T2 = sum(leapYear[:date2M-1])+date2D if (isLeapYear(date2Y)) else sum(nonLeapYear[:date2M-1])+date2D
else:
T1 = sum(leapYear[:date1M-1])+date1D if (isLeapYear(date1Y)) else sum(nonLeapYear[:date1M-1])+date1D
for i in range(date1Y, date2Y):
T2 += 366 if (isLeapYear(i)) else 365
T2 += sum(leapYear[:date2M-1])+date2D if (isLeapYear(date2Y)) else sum(nonLeapYear[:date2M-1])+date2D
return abs(T1-T2)
# 50%
def daysBetweenDates1(date1, date2):
def isleapyear(year):
flag=False
if year%4==0:
if year%100==0:
if year%400==0:
flag=True
else:
flag=True
return flag
def totaldays(year,month,day):
md=[31,28,31,30,31,30,31,31,30,31,30,31]
total=0
for i in range(1971,year):
total+=366 if isleapyear(i) else 365
return total+sum(md[:month-1])+day
y1,m1,d1=map(int,date1.split("-"))
y2,m2,d2=map(int,date2.split("-"))
t1=totaldays(y1,m1,d1)
t2=totaldays(y2,m2,d2)
if isleapyear(y1) and m1>2:
t1+=1
if isleapyear(y2) and m2>2:
t2+=1
return abs(t1-t2)
| true |
632e73e544dcfa1f77dda3d11c631ca9ba15ab71 | manojnayakkuna/leetcode_easy | /problems/leetcode_476_numberComplement.py | 1,347 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1: Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2: Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
"""
# Time - 77%
def findComplement(num):
new_string = ''
for char in str(bin(num)).split('b')[1]:
new_string += '0' if char == '1' else '1'
return int(new_string, 2)
# Time - 75% (Without using defaukt functions)
def findComplement1(num):
new_string = ''
for char in decimalToBinary(num):
new_string += '0' if char == '1' else '1'
return binaryToDecimal(int(new_string))
def decimalToBinary(decimalVal):
binaryVal = ''
while decimalVal:
lastBit = decimalVal % 2
decimalVal = decimalVal // 2
binaryVal = str(lastBit) + binaryVal
return binaryVal
def binaryToDecimal(binaryVal):
decimalVal = 0
base = 1
while binaryVal:
lastBit = binaryVal % 10
binaryVal = binaryVal // 10
decimalVal += lastBit * base
base = base*2
return decimalVal | true |
6c448546d03455c4add583d562566dbbfe737534 | TangentialDevelopment/PythonProjects | /CSE 231/lab projects/Pre-Req Files/clock.py | 984 | 4.375 | 4 | #class time
#__hour, __mins, __secs
class time(object):
def __init__ (self, hour = 0, mins = 0, secs = 0):
"""It sets the three instance variables to real variables to be used"""
self.__hour = hour
self.__mins = mins
self.__secs = secs
def __repr__ (self):
"""allows the variable created to show real data"""
template = "Class Time: {:02d}:{:02d}:{:02d}".format(self.__hour, self.__mins, self.__secs)
return template
def __str__ (self):
"""if the class is called in a print function allows it to be readable"""
template = "{:02d}:{:02d}:{:02d}".format(self.__hour, self.__mins, self.__secs)
return template
def from_str (self, str_time):
"""allows a time variable to be formed when given a string"""
hour, mins, secs = [int(n) for n in str_time.split(":")]
self.__hour = hour
self.__mins = mins
self.__secs = secs
| true |
ce725d86ed5637835d5f073decdd31e8a4a9ff31 | TangentialDevelopment/PythonProjects | /CSE 231/lab projects/Lab14 Classes Cont/lab14.parta.py | 610 | 4.1875 | 4 |
##
## Demonstrate some of the operations of the Fraction class
##
import fraction
def display( arg1, arg2 ):
print( "Display:", locals() )
print()
print( "arg1:", arg1 )
print( "arg2:", arg2 )
print()
print( "arg1 + arg2:", arg1 + arg2 )
print()
print( "arg1 - arg2:", arg1 - arg2 )
print()
print( "arg1 == arg2:", arg1 == arg2 )
print()
print( "arg1 < arg2:", arg1 < arg2 )
print()
print( "arg1 > arg2:", arg1 > arg2 )
print()
def main():
A = fraction.Fraction( 3, 4)
B = fraction.Fraction( 1, 4 )
display( A , 5 )
main()
| false |
92118dc655f200701b2bab1a546328bcef3c16cd | jake-s2021/standard_deviation.py | /standard_deviation.py | 886 | 4.1875 | 4 | import math
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
while 1:
n = input("n =")
x = [] #holds all values in the set
xth = 0 #temporary variable for accepting the set values
xtot = 0 #variable to hold the sum of all values in the set squared
xnaught = 0 #average
if isfloat(n):
n = float(n)
while isfloat(xth) or xth is "": #enter a letter to exit the loop and start calculation
xth = input("X's: ")
if isfloat(xth):
x.append(float(xth))
xnaught = sum(x)/n
for i in x:
xtot = xtot+(i**2)
s = math.sqrt((1/(n-1))*(xtot-(n*(xnaught**2)))) #formula for standard deviation
print(s)
print("\n")
else:
print("not a number")
| true |
8e65f600940af8a164485ab4955075ea75509382 | miaolin/evolution | /leetCode/alg_003.py | 1,198 | 4.15625 | 4 | """
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
class Solution:
def lengthOfLongestSubstring(self, s):
"""
type s: str
return: int
beats 10% of py3 submissions
"""
if len(s) == 0:
return 0
max_len = 0
for n in range(len(s)):
m = n + 1
cur_str = s[n:m]
while m < len(s):
if s[m] in cur_str:
break
else:
m += 1
cur_str = s[n:m]
print([n, m])
max_len = max(max_len, m - n)
return max_len
if __name__ == "__main__":
test = Solution()
s1 = "abcabcbb"
print(test.lengthOfLongestSubstring(s1))
s2 = "bbbb"
print(test.lengthOfLongestSubstring(s2))
s3 = "pwwkew"
print(test.lengthOfLongestSubstring(s3))
| true |
d14c7ef52f982150b33ac9b2bec90a7b014e5cad | lwariar/practice | /part1.py | 1,578 | 4.28125 | 4 | #Write a function that takes in a list and prints each item in the list.
def print_each_item(myList):
for item in myList:
print(item)
#Write a function that takes in a list of words. For each word, the function should print a tuple of (first_letter_of_word, word).
def print_tuple(myList):
for word in myList:
print((word[0], word))
#Write a function that takes in a list of numbers. It should print every other number, starting with the number at index 0.
def print_every_other(myList):
print(myList[::2])
#Write a function that takes in a list and an item. It should return True if the list contains the item. Otherwise, return False.
def find_item(myList, item):
for each_item in myList:
if each_item == item:
return True
return False
#Write a function that takes in a string and returns the length of that string. You cannot use the len function.
def find_length(str):
length = 0
for char in str:
length += 1
return length
#Write a function that takes in a sentence as a string. The function should print the length of each word in the sentence.
#Your sentence will not contain any punctuation.
def print_len_word(str):
for word in str.split():
print(word, len(word))
#Write a function that takes in a list of numbers and returns the largest number in the list. You cannot use the max function.
def largest_number(myList):
largest = myList[0]
for num in myList:
if num > largest:
largest = num
return largest | true |
9f107c6079ecb102e6c2996ecb88ca1f73b67267 | nehamarne2700/python | /untitled/basic/area.py | 590 | 4.21875 | 4 | #area of circle
radius=int(input('enter radius'))
area=3.14*radius**2;
msg=f'area of circle with radius {radius} is {area}'
print(msg)
#area of retangle
length=int(input('enter length'))
width=int(input('enter width'))
area=length*width
msg=f'area of rectangle with length {length} and width {width} is {area}'
print('area of rectangle with length {!s} and width {!s} is {!s}'.format(length,width,area))
#area of triangle
base=int(input('enter base'))
height=int(input('enter height'))
area=base*height//2
msg=f'area of triangle with length {base} and width {height} is {area}'
print(msg) | true |
50d29b0bc9d6feaf743d1b5834f5a14f69a65a3a | CarlosAlbertoTI/Tests-in-Python | /exercicios/exercicio11.py | 1,096 | 4.125 | 4 | salario = float( input('Digite o seu salario: R$'))
if salario <= 0:
print('Salario invalido')
else:
if 0 < salario <= 280.00:
print('Salario inicial: R$ %.2f' %salario)
print('O percentual de aumento aplicado: 20%')
print('Valor do aumento: R$ %.2f' %( (20/100)*salario ))
print('Novo Salario: R$ %.2f' %( salario + ((20/100)*salario) ))
elif 280.00 < salario <=700.00:
print('Salario inicial: R$ %.2f' %salario)
print('O percentual de aumento aplicado: 15%')
print('Valor do aumento: R$ %.2f' %( (15/100)*salario) )
print('Novo Salario: R$ %.2f' %( salario + ((15/100)*salario) ))
elif 700.00 < salario <= 1500.00:
print('Salario inicial: R$ %.2f' %salario)
print('O percentual de aumento aplicado: 10%')
print('Valor do aumento: R$ %.2f' %( (10/100)*salario) )
print('Novo Salario: R$ %.2f' %( salario + ((10/100)*salario) ))
else:
print('Salario inicial: R$ %.2f' %salario)
print('O percentual de aumento aplicado: 5%')
print('Valor do aumento: R$ %.2f' %( (5/100)*salario) )
print('Novo Salario: R$ %.2f' %( salario + ((5/100)*salario) ))
| false |
835c07b683ef3beede4ce1a895d973638a030c04 | YOGESH-TECH/python-basic-problems | /greatest among three.py | 561 | 4.1875 | 4 | n1=int(input())
n2=int(input())
n3=int(input())
if n1==n2==n3:
print("all three are equal")
elif n1<n2<n3:
print("third is greater")
elif n1>n2>n3:
print("first is greater")
elif n2>n1>n3:
print("second is greater")
elif n1==n2>n3:
print("first and second are largest")
elif n1==n3>n2:
print("first and third are greatest")
elif n2==n3>n1:
print("second and third are greatest")
elif n2==n3<n1:
print("first is largest")
elif n1==n3<n2:
print("second is largest")
elif n1==n2<n3:
print("third is largest")
else:
print("error") | false |
36e4ccaadceb42a63c894bc4757f7abcebcb60a1 | SukeshBairy/Pro-Python-Accelarator | /Program_Dictionary.py | 207 | 4.125 | 4 | mydict=dict()
mydict= {"hello" : "world", "speckbit" : "self-learning", "life" : "meaning"}
n=input("Enter the value:")
for i,j in enumerate(mydict):
if mydict[j]==n:
print("The key is:",j)
| false |
707a6d8638d2ab8be2637f0d96524e0034e67dc2 | Shivashna/financialCalculator | /finance_calculators.py | 2,824 | 4.4375 | 4 | import math
# The purpose of this program is to calculate the amount that the user will earn on their investment or to calculate the amount that the user will have to pay on a home loan.
menu = (input("Choose either 'investment' or 'bond' from the menu below to proceed : \n\ninvestment\t-to calculate the amount of interest you'll earn on an investment \nbond\t\t-to calculate the amount you'll have to pay on a home loan\n\nEnter 'investment' or 'bond' to continue : ")).lower()
P = 0
interest_str = ''
interest = 0
num_years = 0
interest_type = ''
total_amount = 0
present_value = 0
i = 0
num_months = 0
monthly_amount = 0
# If the user chooses 'investment' the program will ask for the relevant information to calculate the interest on the investment
if (menu == "investment"):
P = float(input("Enter the amount that you would like to invest : R"))
interest_str = input("Enter the interest rate you would like to invest at : ")
interest = (float(interest_str.strip("%")))/100
num_years = float(input("Enter the number of years you would like to invest for : "))
interest_type = (input("\nState whether you like to invest using simple or compound interest : \n\nSimple Interest\t\t- is continually calculated on the initial amount that you invest \nCompound Interest\t- is calculated on the accumalated amount which includes the accumalated interest \n\nSimply enter 'simple' or 'compound' to proceed : ")).lower()
# The user must choose whether they want 'simple interest' or 'compound interest' on their investment
if (interest_type == "simple"):
total_amount = P * (1 + interest * num_years)
total_amount = round(total_amount,2)
print("\nThe total amount you will get at the end of {} years is R{}".format(num_years,total_amount))
elif (interest_type == "compound"):
total_amount = P * math.pow((1 + interest),num_years)
total_amount = round(total_amount,2)
print("\nThe total amount you will get at the end of {} years is R{}".format(num_years,total_amount))
# If the user chooses 'bond' the program will ask the user to enter the relevent information in order to work out their monthly payment for the bond
elif (menu == "bond") :
present_value = float(input("\nEnter the present value of the house : R"))
interest_str = input("Enter the interest rate : ")
interest = (float(interest_str.strip("%")))/100
i = interest/12
num_months = float(input("Enter the number of months over which you plan to repay the bond : "))
monthly_amount = (i * present_value)/ (1 - (math.pow((1 + i),(-num_months))))
monthly_amount = round(monthly_amount,2)
print("\nYour monthly payment is an amount of R{} for {} months.".format(monthly_amount,num_months))
| true |
6f6f66b134c3992d2394843d18092be7bd501407 | sharknoise/python-project-lvl1 | /brain_games/games/even.py | 832 | 4.125 | 4 | # -*- coding:utf-8 -*-
"""Game logic for the 'brain-even.py' game script."""
from random import randint
from typing import Tuple
RULE = ('Answer "yes" if a number is even, otherwise answer "no".')
def is_even(number: int) -> bool:
"""Define if the number is even.
# noqa: DAR101
# noqa: DAR201
"""
return number % 2 == 0
def create_round(max_number=100) -> Tuple[str, str]:
"""Show a random number, ask the user if the number is even.
Args:
max_number: maximum random number
Returns:
the number, the correct answer to the question
as strings, because the game engine only accepts strings
"""
random_number = randint(1, max_number)
true_answer = 'yes' if is_even(random_number) else 'no'
question = str(random_number)
return question, true_answer
| true |
224310c5fe0ba5e080a2a774d22732d4944cfd2c | akash080491/Games | /scrabble.py | 934 | 4.125 | 4 | def scrabble_score(word):
score={"a":1,"c":3,"b":3,"e":1,"d":2,"g":2,
"f":4,"i":1,"h":4,"k":5,"j":8,"m":3,
"l":1,"o":1,"n":1,"q":10,"p":3,"s":1,
"r":1,"u":1,"t":1,"w":4,"v":4,"y":4,
"x":8,"z":10}
sum=0
a=0
for i in word:
sum=sum+(score[i])
return(sum)
point1=0
chance=5
counter =1
print("*********************Welcome to Scrabble*********************")
print("Rules\n\t 1) You have 5 chances. \n\t 2) To Win - You need to score 50.")
while(chance>0):
word=input("Please enter the "+ str(counter) + "st word - ")
point=scrabble_score(word)
print("Your Score is", point)
point1=point1+point
print("Game Point is = ", point1)
if(point1>=50):
print("You Won")
break
counter=counter+1
chance=chance-1
else:
print("You Loose")
print("\n\t\t\t\t\t\tThanks for Playing") | false |
cedc7492136eefd25ffe962c6eb000c887048db1 | DamienVassart/codewars | /PY/8kyu/bmi.py | 449 | 4.125 | 4 | # Write function bmi that calculates body mass index (bmi = weight / height ** 2).
# if bmi <= 18.5 return "Underweight"
# if bmi <= 25.0 return "Normal"
# if bmi <= 30.0 return "Overweight"
# if bmi > 30 return "Obese"
def bmi(weight, height):
p = weight / (height ** 2)
if p <= 18.5:
return "Underweight"
elif p <= 25:
return "Normal"
elif p <= 30:
return "Overweight"
else:
return "Obese" | false |
8f2f8e3de266ba13a8f4db97df68b4375c3b8cfb | Imnishith/DataStructure | /recursion/substring.py | 646 | 4.21875 | 4 | #
# Listout all substring pattern for a given string
# Logic : For each given character in given recursion tree there are two possibilities,
# 1) You add character
# 2) You don't add
# For ex.
# ''
# '' 'A' (index = 1)
# '' 'B' 'A' 'AB' (index = 2)
# As seen in above recursion tree, we need to print all leaf nodes
#
def generate_subsequnce(list,cur,len):
count = 0
count1 = 0
for item in list:
count1+=1
if(count1 == len):
print(cur+'')
return;
generate_subsequnce(list,cur,len+1);
generate_subsequnce(list,cur+list[len],len+1)
list = ['A','B']
cur = ''
len = 0
generate_subsequnce(list,cur,len);
| true |
6c727622d27e1b95a6e661191891cc2d5a8df5e8 | mohit2494/gfg | /data structures/strings/subsequence/3.py | 1,469 | 4.1875 | 4 | '''
Given a string, count number of subsequences of the form
a^ib^jc^k, i.e., it consists of i ’a’ characters, followed by
j ’b’ characters, followed by k ’c’ characters where i >= 1, j >=1 and k >= 1.
Note: Two subsequences are considered different if the set of array indexes
picked for the 2 subsequences are different.
Expected Time Complexity : O(n)
Input : abbc
Output : 3
Subsequences are abc, abc and abbc
Input : abcabc
Output : 7
Subsequences are abc, abc, abbc, aabc,abcc, abc and abc
Going from left to right, keep track of the number of sequences until the current position,
which are of these three forms:
a^i
a^i b^j
a^i b^j c^k
Suppose that these are stored in three variables a,b,c respectively. Whenever you see the character ‘a’,
it can extend the strings of type 1, and also, be the starting position for a string of type 1,
so a+=(a+1), whenever you see a ‘b’, it can extend previous strings of type 1 and 2, so b+=(a+b),
for ‘c’, it will extend all strings of type 2 and 3, so c+=(b+c).
'''
def all_subs(s):
a, b , c = 0, 0, 0
size = len(s)
for i in range(size):
if s[i] == 'a':
a += a+1
elif s[i] == 'b':
b += (a+b)
else:
c += (b+c)
return c
'''------------------------------------'''
s = "abcabc"
print(all_subs(s))
'''
solution : https://discuss.codechef.com/t/help-needed-for-solving-string-and-sub-sequences-problem/14057
''' | true |
009f0f4d871e1b432ddb71210f3d1d90baec2faf | mohit2494/gfg | /languages/python/Input_Output(done)/7. How to print without newline in python.py | 545 | 4.25 | 4 | '''
Generally people switching from C/C++ to Python wonder how to print two or more variables or
statements without going into a new line in python. Since the python print() function by default
ends with newline. Python has a predefined format if you use print(a_variable) then it will go to
next line automatically.
'''
# Print without newline in Python 3.x
# The default end of the print() statement in python3
# is \n
print("geeks", end=" ")
print("geeksforgeeks")
# geeks geeksforgeeks
for i in range(4):
print(i, end = ' ')
# 1 2 3 4 | true |
08b408fdfe1190194f00de031466f0140076047b | harrisg7/WWU | /Python/Programming_I/ChangeMaker.py | 1,890 | 4.40625 | 4 | #Gavin Harris, Lab 3b
# How to run: python ChangeMaker.py
#ask user for input on how much change for program
change = int(input("How much change are you trying to give (in cents)? "))
quarters = 0
dimes = 0
nickels = 0
pennies = 0
#it will loop as long as the change is above 0 cents
while change > 0 :
#if the change is at or above 25 cents we will use quarters and subtract 25 cents from total and add one quarters to quarter variable
if change >= 25:
change = change - 25
quarters = quarters + 1
#if the change is at or above 10 but less than 25 we will use dimes, subtract 10 from total and add one dime to dimes variable
elif change >= 10:
change = change - 10
dimes = dimes + 1
#if the change is at or above 5 but less than 10 we will use nickels, subtract 5 from total and add one nickel to nickels variable
elif change >= 5:
change = change - 5
nickels = nickels + 1
#if the change is at or above 1 but less than 5 we will use pennies, subtract 1 from total and add one penny to pennies variable
elif change >= 1:
change = change -1
pennies = pennies + 1
#print unknown input if not valid input
else :
Print("Unknown input")
#this is the start of the print statement to tell the user what coins to use, we put end=" " to make it all go on one line of code
print("You should give the customer:", end= " ")
#I use if statements to figure out which coins will be over zero and if they are over zero it will do the print statement saying how many and has end="" to put them all on the same line of code. If at 0 it will be ignored
if quarters > 0:
print( quarters, "quarters", end=" ")
else: ""
if dimes > 0:
print(dimes, "dimes", end= " ")
else: ""
if nickels > 0:
print (nickels, "nickels", end= " ")
else : ""
if pennies > 0:
print( pennies, "pennies", end = " ")
else : "" | true |
dda7f89e5b4ac9f8e2a62e04109a751670502f00 | maisiehester/220 | /labs/lab2/lab2.py | 1,003 | 4.1875 | 4 | """
Maisie Hester
lab2.py
Problem: Arithmetic Functions
"""
import math
def sum_of_three():
upper_bound = eval(input( " Enter upper bound: "))
acc = 0
for i in range( 0, upper_bound, 3):
acc = i + acc
print(acc)
def multiplication_table():
for H in range(1,11):
for L in range(1,11):
print(H * L, end=" ")
print()
def triangle_area():
A = eval(input( " Enter side a: "))
B = eval(input( " Enter side b: "))
C = eval(input( " Enter side c: "))
S = ( A + B + C ) / 2
a = math.sqrt(S*(S-A)*(S-B)*(S-C))
print(a)
def sumSquare():
lower_bound = eval(input( " Enter lower bound: "))
upper_bound = eval(input( " Enter upper bound: "))
acc = 0
for x in range(lower_bound, upper_bound + 1):
acc = acc + (x**2)
print(acc)
def power():
base = eval(input("Enter base: "))
exponent = eval(input("Enter exponent: "))
acc = 1
for i in range(exponent):
acc = acc * base
print(acc)
| false |
781f1f454c22c6213d77cef2717595a99bec346d | heysushil/python-practice-set-three-with-3.8 | /7.list.py | 2,049 | 4.1875 | 4 | '''
All Collection Types: (Array)
1. list (changeable, dublicate) []
2. tuple (non-changable, dublicate) ()
3. dictionary (changable, non-dublicate) {}
4. set (non-index form, non-dublicate) {}
'''
# create list:
mylist = [1,'Hello',3,[4,2,1,3],5,(1,2,3,6)]
print('\nType: ', type(mylist), '\nLen: ', len(mylist), '\nMylist: ', mylist)
# List single index postion
print('\nMylist: ', mylist[3])
# Double index postion
print('\nMylist: ', mylist[3][2])
# Get last value from list
print('\nTuple: ', mylist[-1])
# Last index postion
print('\nTuple: ', mylist[-1][3])
# slice + postive and negative slicing
mylist = [2,3,4,5,6,7]
print('\nSLicing: ', mylist[1:4])
# create once class list
class_8 = ['Ram','Shyam','Seeta','Geeta']
# add new student in class
class_8.append('Vani')
# replace student by insert():
class_8[0] = 'Shree Ram'
class_8.insert(1, 'Poorva')
# to get index postion use index()
print('\nTo get Vani\'s Rollnumber: ', class_8.index('Vani'))
# Sort the list
class_8.sort()
# Reverse
# class_8.reverse()
# class_8 copy:
class_9 = class_8.copy()
# new admission in class 9
new_students = ['Raju','Reema','Seema']
# add class 9 and new stuents list
class_9.extend(new_students)
# Pop:
# class_9.pop()
class_9.pop(-2)
# remove()
class_9.remove('Raju')
class_9.clear()
print('\nClass 8th students: ', class_8)
print('\nClass 9th students: ', class_9)
'''
Question:
1. slice + postive and negative slicing in list
2. Check count method how it works?
Programming Questions:
1. Ek python file me multiline comment me list, tuple, set aur dict ke difference serch karke likhna hai.
2. List me positive and negative position values ko print kar ke check karna hai.
3. List me positive and negative slicing bhi print kar ke check karna hai.
4. Find the length of list?
5. Ek list bana hai jisme ki input ka use karke apne friends ke name insert karne hain.
6. Jo friend list banai hai usme se app kisi bhi friend ka name remove karna cahte ho aur aysa karne ke liye app input method ka use karke ye kaam karoge.
''' | true |
a84d2b246a20b42305cc3adcac03d531ca7358da | mathcircle/ccircle | /pyproject/scenario01/solution.py | 2,617 | 4.125 | 4 |
import worlds
# Your solution goes in this file!
'''
GOAL: Fill in the code for 'moveTowardPizza' to ensure that the cat finds the pizza!
Use the following functions to understand the cat's situation:
cat.isBlocked() -> Bool
returns True if the cat is facing a wall or the edge of the maze, False if the coast is clear
cat.isFacingN() -> Bool
True iff cat is facing north
cat.isFacingS() -> Bool
True iff cat is facing south
cat.isFacingE() -> Bool
True iff cat is facing east
cat.isFacingW() -> Bool
True iff cat is facing west
cat.smellsPizza() -> Bool
True iff the cat is right in front of the pizza (and is facing it)
Just a refresher...:
/|\
|
North
|
<-- West --- --- East --->
|
|
South
|
\|/
Use the following functions to instruct the cat:
cat.turnLeft() -> None
Instructs the cat to turn left / counter-clockwise
cat.turnRight() -> None
Instructs the cat to turn right / clockwise
cat.walk() -> None
Instructs the cat to walk in the direction it is facing
NOTE: You can only call cat.walk() ONCE per call to moveTowardPizza!!
'''
class Solution:
def __init__(self):
# If you want to keep track of any variables, you can initialize them here using self.var = value
self.was_wall_on_right_last_frame = False
pass
# Choose your level here: 'worlds.easy()', 'worlds.medium()', or 'worlds.hard()'!
def getLevel(self):
return worlds.hard()
# Smaller pause time = faster simulation
def getPauseTime(self):
return 0.01
def wall_on_right(self, cat):
cat.turnRight()
wall_on_right = cat.isBlocked()
cat.turnLeft()
return wall_on_right
""" Solution assulmes two things:
1) Cat always starts beside a wall.
2) Pizza exists beside a wall.
"""
def moveTowardPizza(self, cat):
# Follow the right wall.
is_wall_on_right = self.wall_on_right(cat)
if not is_wall_on_right and self.was_wall_on_right_last_frame:
cat.turnRight()
cat.walk()
if is_wall_on_right:
if not cat.isBlocked():
cat.walk()
else:
cat.turnLeft()
self.was_wall_on_right_last_frame = is_wall_on_right
| true |
d91cbf6e125ca744f7ec5297f6af76787b9b4dbc | tonyvu2014/algorithm | /bst/check_bst.py | 863 | 4.1875 | 4 | #####
# Check if a given tree is a binary search tree
# min-max algorithm
######
import sys
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def set_left(self, node):
self.left = node
def set_right(self, node):
self.right = node
def isBST(node):
return isBSTMinMax(node, -sys.maxsize-1, sys.maxsize)
def isBSTMinMax(node, minValue, maxValue):
if node is None:
return True
if node.data > maxValue or node.data < minValue:
return False
return isBSTMinMax(node.left, minValue, node.data) and \
isBSTMinMax(node.right, node.data, maxValue)
if __name__=='__main__':
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
print(isBST(root)) | true |
2b8890b2efd52dd0163d956c389b61e9274b1765 | tonyvu2014/algorithm | /game/sudoku_backtracking_solver.py | 2,649 | 4.25 | 4 | # N is the size of the 2D matrix N*N
N = 9
# A utility function to print grid
def printing(arr):
for i in range(N):
for j in range(N):
print(arr[i][j], end = " ")
print()
# Checks whether it will be
# legal to assign num to the
# given row, col
def isSafe(grid, row, col, num):
# Check if we find the same num
# in the similar row , we
# return false
for x in range(9):
if grid[row][x] == num:
return False
# Check if we find the same num in
# the similar column , we
# return false
for x in range(9):
if grid[x][col] == num:
return False
# Check if we find the same num in
# the particular 3*3 matrix,
# we return false
startRow = row - row % 3
startCol = col - col % 3
for i in range(3):
for j in range(3):
if grid[i + startRow][j + startCol] == num:
return False
return True
# Takes a partially filled-in grid and attempts
# to assign values to all unassigned locations in
# such a way to meet the requirements for
# Sudoku solution (non-duplication across rows,
# columns, and boxes) */
def solveSudoku(grid, row, col):
# Check if we have reached the 8th
# row and 9th column (0
# indexed matrix) , we are
# returning true to avoid
# further backtracking
if (row == N - 1 and col == N):
return True
# Check if column value becomes 9 ,
# we move to next row and
# column start from 0
if col == N:
row += 1
col = 0
# Check if the current position of
# the grid already contains
# value >0, we iterate for next column
if grid[row][col] > 0:
return solveSudoku(grid, row, col + 1)
for num in range(1, N + 1, 1):
# Check if it is safe to place
# the num (1-9) in the
# given row ,col ->we
# move to next column
if isSafe(grid, row, col, num):
# Assigning the num in
# the current (row,col)
# position of the grid
# and assuming our assigned
# num in the position
# is correct
grid[row][col] = num
# Checking for next possibility with next
# column
if solveSudoku(grid, row, col + 1):
return True
# Removing the assigned num ,
# since our assumption
# was wrong , and we go for
# next assumption with
# diff num value
grid[row][col] = 0
return False
# Driver Code
# 0 means unassigned cells
grid = [[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0]]
if (solveSudoku(grid, 0, 0)):
printing(grid)
else:
print("no solution exists ")
# This code is contributed by sudhanshgupta2019a
| true |
15f404b3a4a4053326b32fdf7882411d1c33caf9 | luunatek/Python3 | /algorithms/recursion_tasks/task_6.py | 1,412 | 4.375 | 4 | """
6. В программе генерируется случайное целое число от 0 до 100.
Пользователь должен его отгадать не более чем за 10 попыток. После каждой
неудачной попытки должно сообщаться больше или меньше введенное пользователем
число, чем то, что загадано. Если за 10 попыток число не отгадано,
то вывести загаданное число.
Решите через рекурсию. Решение через цикл не принимается.
Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7
Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7
"""
import random
def random_num_generator():
random_num = random.randint(0, 100)
user_input = int(input("Guess the number: "))
if user_input != random_num and user_input < random_num:
print("Entered number is too small, try again: ")
elif user_input != random_num and user_input > random_num:
print("Entered number is too small, try again: ")
elif user_input == random_num:
print(f"Congratulations, {user_input} is correct.")
random_num_generator()
| false |
aafba3d853a06efdc0e39e6192199b1c564ebcab | rosanepernalonga/curso-em-video | /ex.052.py | 298 | 4.125 | 4 | #leia um numero inteiro e diga se ele é ou não um número primo
num = int(input('Digite um número inteiro: '))
if num % num == 0 and num % 2 != 0 and num % 3 != 0:
print('O número {} é um número primo'.format(num))
else:
print('O número {} NÃO é um número primo'.format(num)) | false |
fe3a674c5b1a58ae1ebbfda42e58aaded0151248 | rosanepernalonga/curso-em-video | /ex.042.py | 773 | 4.21875 | 4 | #refaça o ex.35. e mostre que tipo de triangulo será formado.
# equilátero: todos os lados iguais, isósceles: dois lados iguais, escaleno: todos os lados diferentes.
a = int(input('Qual a medida da primeira reta? '))
b = int(input('Qual a medida da segunda reta? '))
c = int(input('Qual a medida da terceira reta? '))
#if a + b > c or b + c > a or c + a > b:
# print('As medidas informadas formam um triangulo!')
if a + b > c or b + c > a or c + a > b:
print('Essas medidas podem formar um triangulo', end = ' ')
if a == b and a == c:
print("equilátero.")
elif (a != b and a != c and b != c):
print('escaleno')
else:
print('isósceles')
else:
print('As medidas informadas não podem formar um triângulo.') | false |
fd8ffcdee1d9be538e22b310663197bb8d35c50f | nimbus8888/GB_Assignments | /hw6_Lena_4.py | 1,163 | 4.34375 | 4 | class Car:
"""Машина"""
def __init__(self, name, color, speed, is_police=False):
self.name = name
self.color = color
self.speed = speed
self.is_police = is_police
print(f"New car: {self.name} (Color {self.color}) Police car - {self.is_police}")
def go(self):
print(f"{self.name}: The car began to move")
def stop(self):
print(f"{self.name}: The car pulled over")
def turn(self, direction):
print(f"{self.name}: The car turned {'left' if direction == 0 else 'right'}")
def show_speed(self):
print(f"{self.name}: The car speed - {self.speed}")
class WorkCar(Car):
def show_speed(self):
return f"{self.name}: The car speed - {self.speed} - NOO OVERSPEED!!!" \
if self.speed > 40 else f"{self.name}: The car speed - {self.speed}" # super().show_speed()
class SportCar(Car):
"""Sport car"""
class PoliceCar(Car):
def __init__(self, name, color, speed, is_police=True):
super().__init__(name, color, speed, is_police)
police_car = PoliceCar('Police', 'White', 80)
police_car.go() | false |
b9a646e58d5f5349c2658970f3bea6df0c3ebcfa | nimbus8888/GB_Assignments | /Homework_Lena6.py | 924 | 4.40625 | 4 | # Спортсмен занимается ежедневными пробежками.
# В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.
# Например: a = 2, b = 3
km = float(input('Сколько км пробежал в первый день? '))
b = float(input('Цель в км'))
i = 1
while km < b:
km *= 1.1
i += 1
print(i)
| false |
2eaa0d5761bb67627b182b0eabde781de9d346a9 | ng3rdstmadgke/CodeKata | /my_fibonacci.py | 1,182 | 4.125 | 4 | __author__ = 'midorikawakeita'
# -*- coding: utf-8 -*-
"""
フィボナッチ数列とは下記の数列のように今の項と前項の和が次の項となるような数列です。
1 1 2 3 5 8 13 21 34 55 89 144
課題1 フィボナッチ数列の第n項を求めるプログラムを再帰呼出しを用いて書いて下さい。ただしnはコマンドライン引数で得るものとします。
課題2 フィボナッチ数列の第n項を求めるプログラムを再帰呼出しを用いずに書いて下さい。ただしnはコマンドライン引数で得るものとします。
課題3 再帰呼出しを用いた場合と用いない場合、どちらがどのような点で優れているかを考えて下さい
"""
#再起処理を用いる関数
def make_fibonacci_1(n,i,j):
if n-3>0:
ret = make_fibonacci_1(n-1,j,i+j)
return ret
return i+j
#再起処理を用いない関数
def make_fibonacci_2(n):
list=[1,1]
for i in range(n-2):
num=list[i]+list[i+1]
list.append(num)
return list[n-1]
if __name__=="__main__":
a=make_fibonacci_1(5,1,1)
print(a)
b=make_fibonacci_2(5)
print(b)
| false |
ca07ee06c603658da974e6f1d4b4121a2369e096 | kingxdlol/Sample-programs | /python/lcm-hcf_acodegirl.py | 583 | 4.21875 | 4 | #find lcm and hcf of two numbers
print("This program finds the LCM and HCF of two numbers")
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
def lcm(n1, n2):
if n1 > n2:
n1, n2 = n2, n1
for i in range(n1, n1*n2+1, n1):
if i % n2 == 0:
return i
def hcf(n1, n2):
if n1 > n2:
n1, n2 = n2, n1
for i in range(n1, 0, -1):
if n1 % i == 0 and n2 % i == 0:
return i
print("The LCM of", n1, "and", n2, "is", lcm(n1, n2))
print("The HCF of", n1, "and", n2, "is", hcf(n1, n2))
| false |
1e04e18513d856e97a845587e083ec956b29efbe | kingxdlol/Sample-programs | /python/swap-numbers_hmrmember.py | 250 | 4.125 | 4 | # a program to swap 2 numbers
print("Enter 2 numbers to swap: ")
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
temp = a
a = b
b = temp
print("After swapping: ")
print("First number: ", a)
print("Second number: ", b)
| true |
3038be7aa8d56a5fb413203e35684b405de8ad44 | Suraj-KD/HackerRank | /python/math/power_modpower.py | 1,054 | 4.65625 | 5 | '''
So far, we have only heard of Python's powers. Now, we will witness them!
Powers or exponents in Python can be calculated using the built-in power function.
pow(a, b)
It is also possible to calculate a to-the-power b mod m.
like pow(a, b, m)
This is very helpful in computations where you have to print the resultant % mod.
Note: Here, a and b can be floats or negatives,
but, if a third argument is present, b cannot be negative.
Note: Python has a math module that has its own pow().
It takes two arguments and returns a float.
Frankly speaking, we will never use math.pow().
Task
You are given three integers: , , and , respectively. Print two lines.
The first line should print the result of pow(a,b).
The second line should print the result of pow(a,b,m).
Input Format
The first line contains , the second line contains , and the third line contains.
Constraints
1 <= a <= 10
1 <= b <= 10
2 <= m <= 1000
Sample Input
3
4
5
Sample Output
81
1
'''
A = int(raw_input())
B = int(raw_input())
M = int(raw_input())
print pow(A, B)
print pow(A, B, M)
| true |
7946829efd1d61f2020d65788f1adb32610ffda7 | Suraj-KD/HackerRank | /regex/Assertions/Positive_Lookbehind.py | 342 | 4.125 | 4 | '''
Task:
You have a test String S.
Write a regex which can match all the occurences of digit which are immediately preceded by odd digit.
Input: 123Go!
Output: Number of matches : 1
'''
import re
Regex_pattern = r'(?<=[13579])\d'
Test_String = input()
match = re.findall(Regex_pattern, Test_String)
print("Number of matches :", len(match))
| true |
796a660811b5641d9f0a32d0223eb7d702a70105 | Suraj-KD/HackerRank | /regex/repetitions/zero_or_more_repetition.py | 396 | 4.125 | 4 | '''
Task :
You have a test string S.
Your task is to write a regex that will match S using the following conditions:
S should begin with 2 or more digits.
After that, S should have 0 or more lowercase letters.
S should end with 0 or more uppercase letters
Input : 14
Output : true
'''
import re
Regex_pattern = r'^\d{2,}[a-z]*[A-Z]*$'
print(str(bool(re.search(Regex_pattern, input()))).lower())
| true |
2a1a848dfb8d2c5bbd35edabce312637173de4ed | zackedwards/Python | /.ipynb_checkpoints/cloud-checkpoint.py | 1,090 | 4.1875 | 4 | # This script reads a text file, clean it in part and generates a word cloud
# using the words in the text
# Importing the required libraries
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
# Read the whole text
file_read = open("trump1.txt", 'rU')
text_raw = file_read.read()
# Replace end of line character with space
text_raw.replace('\n', ' ')
# Save a lower-case version of each word to a list
words_list = []
for word in text_raw.strip().split():
words_list.append(word.lower())
# Eliminate non alpha elements
text_list = [word.lower() for word in words_list if word.isalpha()]
# Transforming the list into a string for displaying
text_str = ' '.join(text_list)
# Crating and updating the stopword list
stpwords = set(STOPWORDS)
stpwords.add('will')
stpwords.add('said')
# Defining the wordcloud parameters
wc = WordCloud(background_color="white", max_words=2000,
stopwords=stpwords)
# Generate word cloud
wc.generate(text_str)
# Store to file
wc.to_file('Trump.png')
# Show the cloud
plt.imshow(wc)
plt.axis('off')
plt.show()
| true |
537c2367f0d1c83ed2aba5e7b6309e73100bca7b | AntonTrainer/practice | /random_walk.py | 1,322 | 4.28125 | 4 | from random import choice
# create a call to create random walks
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
# start all walks at (0,0), these lists will then be appended as the fill_walk function makes decisions
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
# keep taking steps until walk reaches desired len
while len(self.x_values) < self.num_points:
# chose the direction of the step in the walk left or right
x_direction = choice([-1, 1])
# chose the distance left or right for the step
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance # combine the direction and distance
y_direction = choice([-1, 1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# ignore moves that go no where
if x_step == 0 and y_step == 0:
continue
# generate the next x and y values
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
# implement the step
self.x_values.append(next_x)
self.y_values.append(next_y)
| true |
52ccf8d2c95958312c0437520e7b28f4a386d91d | KiyaniBamba/Sprint-Challenge--Data-Structures-Python | /names/binary_tree.py | 1,860 | 4.21875 | 4 | class BinarySearchTree:
def __init__(self, value):
self.value = value # value of current node
self.left = None # left subtree
self.right = None # right subtree
# Insert the given value into the tree
def insert(self, value):
# current node has no value
if not self.value:
self.value = value
return
# value is less than current node and no left subtree exists
# initiate a left subtree with value
elif value < self.value and not self.left:
self.left = BinarySearchTree(value)
# value is less than current node and left subtree exists
# run insert on the left subtree
elif value < self.value and self.left:
self.left.insert(value)
# value is greater than current node and no right subtree exists
# initiate a right subtree with value
elif value > self.value and not self.right:
self.right = BinarySearchTree(value)
# value is greater than current node and right subtree exists
# run insert on the right subtree
elif value > self.value and self.right:
self.right.insert(value)
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
# check if current node is the target value
if target == self.value:
return True
# target is less than current node and left subtree exists
elif target < self.value and self.left:
return self.left.contains(target)
# target is greater than current node and Rigth subtree exists
elif target > self.value and self.right:
return self.right.contains(target)
# target value does not equal current node value and no subtree exists
else:
return False | true |
6f76d4426859a1e57808930c711c80b519469c4b | myfairladywenwen/cs5001 | /hw06/turtle_draw.py | 2,257 | 4.34375 | 4 | import turtle
import math
STAR_SIDES = 5
STAR_SIDE_LEN = 500
STAR_COLOR = 'red'
STAR_FILL_COLOR = 'yellow'
CIRCLE_COLOR = 'blue'
CIRCLE_FILL_COLOR = 'cyan'
PENTA_ANGLE = 540
STRAIGHT_ANGLE = 180
SUM_OF_TRIANGLE = 180
# set the precision for the circle, the bigger this number,
# the closer it looks like a circle
CIRCLE_PRECISION = 500
def draw_circle(pos, color, r, cir_precision, fillcol):
'''This function draws a circle of given size, from the given positon
Tuple, string, float, int, string -> None'''
ROUND_ANGLE = 360
circle_distance = (2 * math.pi * r)/CIRCLE_PRECISION
circle_angle = (ROUND_ANGLE/CIRCLE_PRECISION)
turtle.penup()
turtle.setposition(pos)
turtle.pendown()
turtle.fillcolor(fillcol)
turtle.begin_fill()
for _ in range(CIRCLE_PRECISION):
turtle.pencolor(color)
turtle.forward(circle_distance)
turtle.right(circle_angle)
turtle.end_fill()
def draw_star(pos, color, side_len, number_of_sides, fillcol):
'''This function draws a star of given size, from the given positon
Tuple, string, int, int, string -> None'''
turtle.pencolor(color)
turtle.penup()
turtle.setposition(pos)
take_turn1 = STRAIGHT_ANGLE - PENTA_ANGLE/number_of_sides
turtle.right(take_turn1)
turtle.pendown()
turtle.fillcolor(fillcol)
turtle.begin_fill()
turtle.forward(side_len)
take_turn2 = STRAIGHT_ANGLE - (SUM_OF_TRIANGLE - 2 * take_turn1)
for _ in range(number_of_sides - 1):
turtle.right(take_turn2)
turtle.forward(side_len)
turtle.end_fill()
def main():
'''This program draws a circle and a star of given size,
at the given positon, and fill the graph with given color
None -> None'''
# calculate the radius of the circle
r = (STAR_SIDE_LEN / 2)/math.cos(math.radians((SUM_OF_TRIANGLE -
2 * (STRAIGHT_ANGLE -
PENTA_ANGLE/STAR_SIDES))/2))
star_pos = (0, r)
cir_precision = CIRCLE_PRECISION
draw_circle(star_pos, CIRCLE_COLOR, r, cir_precision, CIRCLE_FILL_COLOR)
draw_star(star_pos, STAR_COLOR, STAR_SIDE_LEN, STAR_SIDES, STAR_FILL_COLOR)
turtle.exitonclick()
main()
| true |
39a2395388a46ba2d5029fd46d0f3a02ce3e2792 | myfairladywenwen/cs5001 | /week09/queue/queue_python_list.py | 528 | 4.1875 | 4 | class Queue:
"""a queue class using a Python
list as its implementation"""
def __init__(self):
self.items = []
def __str__(self):
return self.items.__str__()
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def peek(self): # take a look at the last element in line
return self.items[-1]
def is_empty(self):
if len(self.items) == 0:
return True
else:
return False
| true |
7ac607f5708d2ff0cb7f84b34765ac53e59ed19b | myfairladywenwen/cs5001 | /week14/reverse_list.py | 763 | 4.125 | 4 | class Reverse:
"""takes a list and returns a list with the elements reversed"""
@staticmethod
def rev_list(array):
# if len(array) == 0:
# return
if len(array) <= 1:
return array
else:
return Reverse.rev_list(array[1:]) + [array[0]]
@staticmethod
def rev_list_tr(array, output, length):
# output starts from []
start = 0
if length == len(output):
return output
else:
# return Reverse.rev_list_tr(array[1:], [array[0]] + output, start+1)
# putting the element in front of our reversed list so far
output = [array[start]] + output
return Reverse.rev_list_tr(array[start+1:], output, length)
| true |
2e9963440ce4d695cfeb0afd6badd8c9a7eb5cdf | myfairladywenwen/cs5001 | /lab04/04_draw_circle.py | 707 | 4.1875 | 4 | from sys import argv
from math import sqrt
def main():
'''
This program draws a circle of the radius
get from the command line
'''
r = int(argv[1])
d = 2 * r
# make every dot in the list
lst_of_dots = []
for y in range(d+1):
lst = [(x, y) for x in range(d+1)]
lst_of_dots.append(lst)
# start drawing
for line in lst_of_dots:
for dot in line:
# decide what character should the dot be
x, y = dot
distance = int(sqrt((x - r) ** 2 + (y - r) ** 2))
if distance >= r:
print(' ', end='')
else:
print('o', end='')
print('\n')
main() | true |
06a8e259f684d9529062c5ea7d816f55da8b05ba | myfairladywenwen/cs5001 | /lab05/word_count.py | 1,047 | 4.1875 | 4 | import re
def main():
'''read the file that user input directs,
count the words,
non-whitespace characters (including punctuation),
and alphanumeric characters (letters and numbers, excluding punctuation)
None -> None'''
filename = input('Enter the file name: ')
try:
myfile = open(filename, 'r')
except:
print('Can\'t open', filename)
return
word_count = 0
char_count = 0
alph_num_count = 0
for line in myfile:
if line != "\n":
whole_line_str = line.strip()
word_list = whole_line_str.split(' ')
word_count += len(word_list)
for word in word_list:
word_len = len(word)
char_count += word_len
alph_num_lst = re.findall(r"\w", whole_line_str)
alph_num_count_line = len(alph_num_lst)
alph_num_count += alph_num_count_line
print('Words:', word_count)
print('Characters:', char_count)
print('Letters & numbers:', alph_num_count)
main()
| true |
086e629f7fba8b80ab9755f343c0c08343c514fb | myfairladywenwen/cs5001 | /lab03/dmv.py | 1,645 | 4.21875 | 4 | from random import randint
def main():
EXPIRE_YEAR = 2021
print("Welcome to the DMV (estimated wait time is 3 hours)")
fullname = input("Please enter your first, middle, and last name:"+'\n')
# generate the last_name and the first_and_middle_name
name_break = fullname.rfind(' ')
last_name = fullname[name_break+1:]
first_and_middle_name = fullname[:name_break]
#get date_of_birth and update to year to the expire year
date_of_birth = input("Enter date of birth (MM/DD/YY): "+'\n')
date_to_modify = date_of_birth[6:]
expire_date = date_of_birth.replace(date_to_modify, str(EXPIRE_YEAR))
#generate 7 digit random license num
license_num =''
for count in range(0,7):
num = str(randint(0,9))
license_num += num
print("-------------------------------------")
print("Washington Driver License")
print("DL " + license_num)
print("LN " + last_name)
print("FN " + first_and_middle_name)
print("DOB " + date_of_birth)
print("EXP " + expire_date)
print("-------------------------------------")
main()
# another way to generate the last_name and the first_and_middle_name
# for idx in range (len(fullname)-1, -1, -1):
# # from the last letter, that is index[len-1],traverse backward,
# # to the first letter,that is index[0]
# if fullname[idx] == ' ':
# # since we are travesing backward,
# # the first '' we encounter will be the break of last name
# # in this way, we avoid the edge case of having 2 middle names
# last_name = fullname[idx+1:]
# break
# first_and_middle_name = fullname[: idx]
| true |
922bcc5bc4db04ab16c9a71eefea7ef056793bb9 | myfairladywenwen/cs5001 | /week13/sort.py | 1,959 | 4.25 | 4 | class Sort:
"""Implements two sorting algorithms:
selection sort and bubble sort"""
@staticmethod
def selection_sort(array):
"""Sort a list of numbers using selection sort"""
# Each iteration of this outer for-loop puts one element into its proper place
# After n iterations, every element is in its proper place, i.e., the array is sorted
for i in range(len(array) - 1):
# Find the index of the smallest element in the
# remaining unsorted portion of the array
min_index = i
for j in range(i+1, len(array)):
if array[j] < array[min_index]:
min_index = j
# Swap the ith element and the minimum element
if min_index != i:
array[i], array[min_index] = array[min_index], array[i]
print(i, ": ", array)
# O(n2)
# best: n(no need to swap); worst: n2
# not stable
return array
@staticmethod
def bubble_sort(array):
"""Sort a list of numbers using bubble sort"""
# Each iteration of this outer for-loop puts *at least* one element into its
# proper place. Thus, at most n iterations must be executed to sort the array
# I.e., it's possible for the array to be sorted in fewer than n iterations
for _ in range(len(array)):
swapped = False
for j in range(1, len(array)):
if array[j-1] > array[j]:
array[j-1], array[j] = array[j], array[j-1]
swapped = True
print(_, ": ", array)
# If we went through the whole array and never swapped anything
# then the array must be sorted and we can exit early
if not swapped: # only by adding this flag can we make the best case to be O(n)
return
# O(n2)
# best: O(n); worst:O(n^2); avg:O(n^2)
# stable | true |
4faaaa016c4cd1284922693dc5c3aed76c8ac1fe | myfairladywenwen/cs5001 | /practice/chapter9_objects/8_two_turtles.py | 517 | 4.375 | 4 | from turtle import *
# Part 1
# Create a turtle object named t1
# Create a second turtle object named t2
# t1's pen color is red
t1 = Turtle()
t2 = Turtle()
t1.pencolor('red')
t2.pencolor('blue') # t2's pen color is blue
t2.left(90) # Point t2 up (t1 automatically points to the right)
t1.forward(100)
t2.forward(50)
# Part 2
t2 = t1 # Make the second turtle just like the first?
t2.right(45) # Turn turtle 2 (but not turtle 1?)
t2.forward(50) # Move turtle 2 (why does turtle 1 move instead?)
done()
| false |
b4bd3092046fd48abedf2e4af0317d2f98248e0f | prasadtelkikar/Learning-Python | /LearningPython/LearningPython/4_MakingDecision/CheckNumber.py | 373 | 4.21875 | 4 | while(True) :
print("Enter input value: ")
value = int(input())
if(value > 0 and value < 10):
print("Yes! Value is in between 1 and 9")
#print()
print("Do you want to continue? Press Y/y to stop : ")
toContinue = input()
if(toContinue == 'Y' or toContinue == 'y'):
break
else:
print("Continuing...")
print()
| true |
28ff69f97e4f2d58d4992966a153af9ed96bcbd7 | klane11/CS-Class-Algorithms | /phonebookapp.py | 1,485 | 4.1875 | 4 | # phonebook_dict = {
# 'Alice': '703-493-1834',
# 'Bob': '857-384-1234',
# 'Elizabeth': '484-584-2923'
# }
# #prints Elizabeths phone number
# print phonebook_dict['Elizabeth']
# #adds kareem's phone number
# phonebook_dict['Kareem'] = '938-281-1234'
# print phonebook_dict
# #delets Alice's phone number
# del phonebook_dict['Alice']
# print phonebook_dict
# #changes Bob's phone number
# phonebook_dict['Bob'] = '985-234-1234'
# print phonebook_dict
# # prints all the phone numbers
# print phonebook_dict.values()
# ramit = {
# 'name': 'Ramit',
# 'email': 'ramit@gmail.com',
# 'interests': ['movies', 'tennis'],
# 'friends': [
# {
# 'name': 'Jasmine',
# 'email': 'jasmine@yahoo.com',
# 'interests': ['photography', 'tennis']
# },
# {
# 'name': 'Jan',
# 'email': 'jan@hotmail.com',
# 'interests': ['movies', 'tv']
# }
# ]
# }
# # Write a python expression that gets the email address of Ramit.
# print ramit['email']
# # Write a python expression that gets the first of Ramit's interests.
# print ramit['interests'][0]
# # Write a python expression that gets the email address of Jasmine.
# print ramit['friends'][0]['email']
# # Write a python expression that gets the second of Jan's two interests.
# print ramit['friends'][0]['interests'][1]
word_input = str(raw_input("Please enter a word: "))
counter = {}
for letter in word_input:
if letter in counter:
counter[letter] += 1
else:
counter[letter] = 1
print counter
| false |
c78d573c25e1a60c2e1abd797288a0c63a96d253 | pankajp/moview | /moview/molecule.py | 501 | 4.15625 | 4 | """ Molecule definition. """
class Mol(object):
""" Represents a molecule with atoms and coordinates.
Attributes:
- name: str: name of the molecule
- atoms: list(str): list of symbols of Atoms contained in the molecule
- coords: list([x,y,z]): list of x,y,z coordinate tuples for each
atom in the order listed in `atoms` attribute
"""
def __init__(self, atoms, coords, name=''):
self.atoms = atoms
self.coords = coords
self.name = name
| true |
9d3809979b382084e462873820d718081f965e7d | RoxanaTesileanu/Py_for_kids | /py_for_kids_ch8.py | 2,708 | 4.28125 | 4 | Python 2.7.12 (default, Jul 1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> # an object can be thought of as a member of a class
>>> class Things:
pass
>>> # if a class is a part of another class => child of that class, and parent class
>>> # Inanimate and Animate are both children of the class Things:
>>> class Inanimate(Things) :
pass
>>> class Animate(Things) :
pass
>>> class Sidewalks(Inanimate) :
pass
>>> class Animals (Animate) :
pass
>>> class Mammals (Animals) :
pass
>>> class Giraffes(Mammals) :
pass
>>> # Adding objects to classes
>>> reginald=Giraffes()
>>> # when we create our classes, we also need to define functions that can be used with the objects in that class
>>>
>>> def this_is_a_normal_function() :
print('I am a normal function')
>>> class ThisIsMySillyClass :
def this_is_a_normal_function() :
print ('I am a normal class function')
def this_is_also_a_normal_function() :
print ('I am also a normal class function')
>>>
>>> # a characteristic is a trait that all members of the class (incl. children) share.
>>> class Animals(Animate) :
def breathe (self) :
pass
def move (self) :
pass
def eat_food(self) :
pass
>>> class Mammals(Animals) :
def feed_young_with_milk(self) :
pass
>>> class Giraffes(Mammals) :
def eat_leaves_from_trees(self) :
pass
>>> reginald=Giraffes()
>>> reginald.move()
>>> reginald.eat_leaves_from_trees()
>>> harold=Giraffes()
>>> class Animals(Animate) :
def breathe(self) :
print ('breathing')
def move(self) :
print ('moving')
def eat_food(self) :
print ('eating food')
>>> class Mammals(Animals) :
def feed_young_with_milk(self) :
print ('feeding young')
>>> class Giraffes(Mammals) :
def eat_leaves_from_trees(self) :
print('eating leaves')
>>> reginald.move()
>>> reginald = Giraffes()
>>> harold = Giraffes()
>>> reginald.move()
moving
>>> harold.move()
moving
>>> harold.eat_leaves_from_trees()
eating leaves
>>> reginald.feed_young_with_milk()
feeding young
>>> import turtle
>>> avery = turlte.Pen()
Traceback (most recent call last):
File "<pyshell#83>", line 1, in <module>
avery = turlte.Pen()
NameError: name 'turlte' is not defined
>>> avery=turtle.Pen()
>>> kate=turtle.Pen()
>>> avery.forward(50)
>>> kate.left(90)
>>> kate.forward(100)
>>> avery.right(90)
>>> avery.forward(100)
>>> jacob = turtle.Pen()
>>> jacob.left(180)
>>> jacob.forward(20)
>>> jacob.right(90)
>>> jacob.forward(100)
>>> jacob.forward(20)
>>> jacob.right(90)
>>> jacob.forward(100)
>>> jacob.right(90)
>>> jacob.forward(50)
>>> avery.forward(20)
>>> kate.forward(50)
>>> ### paused at page 104 ###
>>>
| true |
06b0dd1a4416ee75502828f721d02c8966ce6b01 | Lynesn/pyExercises | /one.py | 406 | 4.25 | 4 | # Create a program that asks the user to enter their name and their
# age. Print out a message addressed to them that tells them
# the year that they will turn 100 years old.
from datetime import datetime
name = input("please enter your name:")
age = int(input("please enter your age:"))
year100 = int((100-age) + datetime.now().year)
print("Hello" + name + "," "you will turn 100 years in", + year100) | true |
e46e0b1c6f386fb9e720ddf527542ec5fb9d0fd5 | mzdu/asciichan | /AlgoDS/PythonDS/chapter4/recur_palindrome.py | 783 | 4.21875 | 4 | '''
Write a function that takes a string as a parameter and returns True if the string is a palindrome, False otherwise.
Remember that a string is a palindrome if it is spelled the same both forward and backward.
for example: radar is a palindrome. for bonus points palindromes can also be phrases,
but you need to remove the spaces and punctuation before checking.
for example: madam i’m adam is a palindrome. Other fun palindromes include:
kayak
aibohphobia
Live not on evil
Reviled did I live, said I, as evil I did deliver
Go hang a salami; I’m a lasagna hog.
Able was I ere I saw Elba
Kanakanak – a town in Alaska
Wassamassaw – a town in South Dakota
'''
def checkPalindrome(str1):
puncList=",./" :;-"
if str1[0] not in puncList and str1[] | true |
d4fdecab2d0ba1f8f5dc9e647feb0bb0affb0b24 | mzdu/asciichan | /AlgoDS/stack/decimal_to_binary.py | 392 | 4.125 | 4 | def binary_to_decimal(number):
# use stack to keep the left
stack = []
res = []
while number // 2 > 0:
left = number % 2
stack.append(left)
number = number // 2
stack.append(number)
#use pop to reverse the output
res = ''
while stack:
res += str(stack.pop())
return res
print binary_to_decimal(8) | true |
23ccd6f495308efbe0379a93a3572013180a6065 | Vyshnavmt94/Python_Design_Patterns | /patterns/creational/factory/with_abstract_factory_method.py | 1,140 | 4.3125 | 4 | import random
class DSA:
"""Class for Data Structure and Algorithms"""
def Fee(self):
return 11000
def __str__(self):
return "DSA"
class STL:
"""Class for Standard Template Library"""
def Fee(self):
return 8000
def __str__(self):
return "STL"
class SDE:
"""Class for Software Development Engineer"""
def Fee(self):
return 15000
def __str__(self):
return 'SDE'
class Course_At_GFG:
""" GeeksforGeeks portal for courses """
def __init__(self, courses_factory=None):
"""course factory is out abstract factory"""
self.course_factory = courses_factory
def show_course(self):
"""creates and shows courses using the abstract factory"""
course = self.course_factory()
print(f'We have a course named {course}')
print(f'its price is {course.Fee()}')
def random_course():
"""A random class for choosing the course"""
return random.choice([SDE, STL, DSA])()
if __name__ == "__main__":
course = Course_At_GFG(random_course)
for i in range(5):
course.show_course()
| true |
965bf2a629dca69362523575dd9df39000b48384 | VestOfHolding/Cryptography | /Monoalphabetic/KeywordCipher.py | 1,588 | 4.34375 | 4 | import string
def keywordCipher(message, keyword, keyShift=0, encrypt=True):
"""Given a message and keyword, encrypt or decrypt a message using a keyword cipher.
Args:
message - The message to encrypt or decrypt.
keyword - The keyword used in the cipher.
keyShift - The amount to shift the new alphabet created by the keyword by. (default: 0)
encrypt - True if encrypting, False otherwise. (default: True)
Return:
The resulting message.
"""
message = message.lower().replace(' ', '')
alphabet = string.ascii_lowercase
# First, remove repeated characters from the keyword.
# If anyone reading this can do it faster than O(n^2), let me know.
keyword = ''.join(sorted(set(keyword), key=keyword.index))
# Then build the new alphabet.
newAlpha = keyword + ''.join(sorted(set(alphabet).difference(keyword)))
# Then shift the new alphabet if there's any shifting to do.
if not keyShift == 0:
newAlpha = newAlpha[keyShift:] + newAlpha[:keyShift]
# Now construct the new message
# Normally, this would be the way to go:
# for char in message:
# if encrypt:
# newMessage += newAlpha[alphabet.find(char)]
# else:
# newMessage += alphabet[newAlpha.find(char)]
#
# But that's just to make what's going on more clear. I think we can move on
# for efficiency sake by now.
if encrypt:
return message.translate(str.maketrans(alphabet, newAlpha))
else:
return message.translate(str.maketrans(newAlpha, alphabet))
| true |
3f4406e788890f7c8aff9935bfb90db11c675dc0 | Meghashrestha/assignment-python | /24.py | 355 | 4.25 | 4 | #24. Write a Python program to clone or copy a list.
def copylist(list2):
list2=[]
list2=list.copy()
return list2
list=[]
list2=[]
n=int(input("enter the number of item in list :"))
for i in range(0, n):
element = int(input("enter element"))
list.append(element)
print(f"list 1 is ",list)
print(f"copied list is ", copylist(list2))
| true |
8883a21a17e7356797dec3cd02fd5d8533412df8 | Meghashrestha/assignment-python | /61.py | 258 | 4.25 | 4 | # 14. Write a Python program to sort a list of dictionaries using Lambda.
list = [{"a": 2, "rank": 7}, {"b": 3, "rank": 2}, {"c": 1, "rank": 3}, {"d": 9, "rank": 9}, {"e": 4, "rank": 1} ]
print(list)
list = sorted(list, key = lambda x: x['rank'])
print(list) | true |
5bdac2ff1465392a91e615f3e6bea0179a084985 | Meghashrestha/assignment-python | /43.py | 223 | 4.3125 | 4 | # 43. Write a Python program to remove an item from a tuple.
tup = (1, 2, 3, 4, 5)
print(tup)
tupl = list(tup)
element = int(input("enter key of an item you want to remove "))
tupl.pop(element)
tup = tuple(tupl)
print(tup)
| true |
1d442961c644f78e0202c301517d94e5f214f2d2 | Meghashrestha/assignment-python | /30.py | 413 | 4.25 | 4 | # Write a Python script to check whether a given key already exists in a
# dictionary.
my_dict = dict()
n= int(input("enter the number of item in the dictionary you want to input : "))
for i in range(0,n):
key = input("Enter the key: ")
value = input("Enter the value: ")
my_dict[key] = value
print(my_dict)
m=input("enter a key to check: ")
if m in my_dict:
print("yes")
else:
print("no")
| true |
516e357c146195cebcd721f85b2526dc8cddf797 | Meghashrestha/assignment-python | /15.py | 478 | 4.28125 | 4 | #Write a Python function to insert a string in the middle of a string.
# Sample function and result :
# insert_sting_middle('[[]]<<>>', 'Python') -> [[Python]]
# insert_sting_middle('{{}}', 'PHP') -> {{PHP}}
def string(str, function):
length = len(str)
place_holder = length/2
new_str = str[:int(place_holder)] + function + str[int(place_holder):]
return new_str
str = input("enter string :")
function = input("enter function :")
print(string(str, function)) | true |
53fa664d0c318c842362f448482ae737333f51a4 | MZoltan79/Python_Idomar | /P0013_lists.py | 328 | 4.1875 | 4 | #!/usr/bin/env python3
heros = []
hero = None
print('This program stores names.\nTo stop input, hit ENTER without any text!')
while hero != '':
hero = input('please type a fairytale hero\'s name here:... ')
if hero: # this line equals: if hero != '' - because '' means False!!!
heros.append(hero)
print(heros)
| true |
fa79a74a987711b6171d0a04281e54dc76051ce2 | MZoltan79/Python_Idomar | /p0006_trip.py | 447 | 4.28125 | 4 | #!/usr/bin/env python3
season = input('What season is it? (summer/fall) ')
rains = input('Is it raining? (y/n) ')
wind = input('Is it windy out there? (y/n) ')
##if (season == 'summer' and wind == 'n') or (season == 'fall' and rains == 'n' and wind == 'n'):
if wind == 'n' and (season == 'summer' or (season == 'fall' and rains == 'n')):
print('Let\'s go!')
else:
print('Okay, it\'s cold out there, thus we stay at home.\nLet\'s code!')
| true |
e343d5c1b76a588fc90e434510a37fc2b96ae142 | scottjstewart/learn-python | /classes.py | 1,237 | 4.40625 | 4 | # A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object
# Create a class
class User:
# constructor
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
# method
def greeting(self):
return f'My name is {self.name} and I am {self.age}'
def has_birthday(self):
self.age += 1
# extend class this greeting could also be accessed from the parent by calling rob.greeting() in a print
class Customer(User):
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def set_balance(self, balance):
self.balance = balance
def greeting(self):
return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'
# init customer
rob = Customer('rob', 'rob@rob.com', 27)
rob.set_balance(500)
print(rob.greeting())
# initialize user object
scott = User('Scott', 'scott@test.com', 25)
print(type(scott), scott.name)
scott.has_birthday()
print(scott.greeting())
| true |
4f9e837eec5467e317fea7cdca147c70c4700e24 | shravan0409/LTI-preparation | /Hackerrank/Python Fundamentals/Map and Lambda.py | 1,393 | 4.65625 | 5 | # The map() function applies a function to every member of an iterable and returns the result. It takes two parameters: first,the function that is to be applied and
# secondly, the iterables.
# Let's say you are given a list of names, and you have to print a list that contains the length of each name.
# >> print (list(map(len, ['Tina', 'Raj', 'Tom'])))
# [4, 3, 3]
# Lambda is a single expression anonymous function often used as an inline function. In simple words, it is a function that has only one line in its body. It proves very handy in functional and GUI programming.
# >> sum = lambda a, b, c: a + b + c
# >> sum(1, 2, 3)
# 6
#Fibbonacci
cube = lambda x:x*x*x # complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
n1, n2 = 0, 1
l = list()
count = 0
if n <= 0:
# print("Please enter a positive integer")
return l
elif n == 1:
# print("Fibonacci sequence upto",n,":")
# print(n1)
l.append(n1)
else:
# print("Fibonacci sequence:")
while count < n:
l.append(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
return l
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
#Input: 5
#OUTPUT: [0, 1, 1, 8, 27]
| true |
add2ab98c8ab3baf81ccaa0ff5345c684d2cd98a | shravan0409/LTI-preparation | /Hackerrank/Date and time/calendar module.py | 298 | 4.1875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import calendar
mm,dd,yy = map(int,input().split())
print((calendar.day_name[calendar.weekday(yy,mm,dd)]).upper()) #weekday returns the day of the week in number format. so we need weekday function to get the name of the week.
| true |
f2c79650e4709e8df2cc1156d9191865db07aa82 | jackandsnow/LeetCodeCompetition | /hot100/22generateParenthesis.py | 1,043 | 4.375 | 4 | """
22. 括号生成
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
"""
def new_insert(st):
"""
在有效括号序列中插入一对新的括号
:param st: 有效括号序列
:return: 插入后的有效括号序列
"""
if not st:
return {'()'}
result = set()
for s in st:
for i in range(len(s)):
result.add(s[:i+1] + '()' + s[i+1:])
return result
def generateParenthesis(n):
"""
动态规划方法
:type n: int
:rtype: List[str]
"""
# 保存 i=1 to n 对括号的生成结果
result = []
temp = set()
while n > 0:
temp = new_insert(temp)
result.append(list(temp))
n -= 1
return result[-1]
if __name__ == '__main__':
ans = generateParenthesis(4)
print(ans)
print(len(ans))
| false |
2d2e88adf3d8dfcc41de7f49a95dfa2eae856a20 | Shubham-Z/amazon-401d1-python | /class-02/challenge/array-shift/array_shift/array_shift_module.py | 845 | 4.21875 | 4 | def insertShiftArray(input_array, n):
l = len(input_array)
if l % 2 == 0:
index = int(l/2)
else:
index = int(l/2) + 1
last = input_array[l-1]
for i in range(l-1, -1, -1):
if (i == index):
input_array[i] = n
break
input_array[i] = input_array[i-1]
input_array.append(last)
return input_array
if __name__ == "__main__":
input_array = []
print("Enter size of array:")
n = int(input())
print("Enter the array:")
for i in range(0, n):
x = int(input())
input_array.append(x)
m = int(input("Enter the number to be inserted: "))
print(f"array before inserting: {input_array}")
input_array = insertShiftArray(input_array, m)
print(f"array after inserting: {input_array}")
| false |
27f5126cecf1e0f91ef5d663f015a915f7d78425 | mayfiec/IntroductionToPython | /src/m5_your_turtles.py | 1,927 | 4.4375 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,
their colleagues and Clayton Mayfield.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# TOD: 2.
#
# You should have RUN the PREVIOUS module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOUR WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
import rosegraphics as rg
window = rg.TurtleWindow()
turtle_1 = rg.SimpleTurtle('turtle')
turtle_1.pen = rg.Pen('blue', 3)
turtle_1.speed = 8 # Fast
turtle_2 = rg.SimpleTurtle('turtle')
turtle_2.pen = rg.Pen('red', 3)
turtle_2.speed = 5 # Fast
size_1 = 50
size_2 = 200
for k in range(15):
turtle_1.draw_circle(size_1)
turtle_1.pen_up()
turtle_1.forward(20)
turtle_1.left(50)
turtle_1.backward(25+k)
turtle_1.pen_down()
size_1 = size_1 - 14
turtle_2.draw_square(size_2)
turtle_2.pen_up()
turtle_2.backward(50)
turtle_2.right(45)
turtle_2.backward(50-k)
turtle_2.left(30)
turtle_2.forward(100)
turtle_2.pen_down()
size_2 = size_2 - 14
window.close_on_mouse_click()
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT your work by using VCS ~ Commit and Push.
########################################################################
| true |
3c5f92ad9d44accb5b785bd01580a1779c50aa21 | destleon/python | /RandomFunction.py | 433 | 4.125 | 4 | #functions
import random
#WE ARE GOING TO CREATE A GUESSING GAME
number = random.randint(1,10)
IsGuessRight = False
while IsGuessRight !=True :
guess = input("please guess any number between 1 to 10 : ")
if str(guess) == "hello" :
print(" you have guessed the right number ")
IsGuessRight = True
continue
elif str(guess) == "quit":
break
else:
print("please try again ")
| true |
2b59a950058dfb3e6942a2289e3a722d8cbfdb03 | ballib/Forritun-aftur | /Assignment 3/4. Proper fractions.py | 342 | 4.34375 | 4 | num_float = float(input("Input a decimal: ")) # Do not change this line
# Fill in the missing code below
count = 1
the_fraction = False
while count <= 100:
if num_float == 1/count:
the_fraction = True
break
count += 1
if the_fraction:
print(f"The fraction is 1/{count}.")
else:
print("Fraction not found!") | true |
b39f65ed8193cdbe84280a31ff4f7babf29a0af7 | ballib/Forritun-aftur | /Assignment 7/1. Find maximum.py | 312 | 4.1875 | 4 | # find_min function definition goes here
def find_min(first, second):
if first > second:
return first
return second
first = int(input("Enter first number: "))
second = int(input("Enter second number: "))
# Call the function here
minimum = find_min(first, second)
print("Maximum: ", minimum) | true |
b5d8fff090a1c900622a3646b0463baefb0023cc | Aytch2eso4/python_challenge | /python_challenge/PyParagraph/main.py | 2,640 | 4.1875 | 4 |
import os
# Module for reading CSV files
import csv
import re
# In[16]:
def readfile(myfile):
totlettercount = 0
totwordcount = 0
totsentcount = 0
paragraphnum = 0
with open("raw_data/" + myfile) as file_object:
#totlettercount = 0
#totwordcount = 0
#totsentcount = 0
lines = file_object.readlines()
print("The file you chose:" + myfile)
for paragraph in lines:
totlettercount = 0
totwordcount = 0
totsentcount = 0
wordcount = 0
#print(paragraph)
#ericinput = input("pause here")
#re.split("(?<=[.!?]) +", paragraph)
wordlist = re.split(" ", paragraph) #split on spaces
wordcount = len(wordlist) #word count (REQUIRED)
totwordcount = totwordcount + wordcount # to account for possible multiple paragraphs in file
#print(wordcount)
sentencelist = re.split("(?<=[.!?]) +", paragraph)
sentcount = len(sentencelist)
totsentcount = totsentcount + sentcount
for word in wordlist:
lettercount = len(word)
totlettercount = totlettercount + lettercount
avglettercount = totlettercount / wordcount # REQUIRED
avgsentencelength = wordcount / sentcount # REQUIRED
if wordcount > 1:
paragraphnum = paragraphnum + 1
print("\n#Paragraph Analysis")
print("#-----------------")
print(f"#Paragraph # {paragraphnum}")
print(paragraph + "\n")
print(f"#Approximate Word Count: {totwordcount}")
print(f"#Approximate Sentence Count: {totsentcount}")
print(f"#Average Letter Count: {avglettercount}")
print(f"#Average Sentence Length: {avgsentencelength}")
userinput = input("Select (1) for file paragraph_1.txt or (2) for file paragraph_2.txt or (3) for Adam Wayne snippet for processing..")
if userinput == "1":
chosenfile = "paragraph_1.txt"
readfile(chosenfile)
elif userinput == "2":
chosenfile = "paragraph_2.txt"
print("Showing stats for each paragraph in the file!")
readfile(chosenfile)
elif userinput == "3":
chosenfile = "AdamWayne.txt"
print("2 words off in my count. README.md says 122 words and so does Notepad++, I get 120!")
readfile(chosenfile)
else:
print("Please pick number for your file selection. Please re-run the program")
chosenfile = ""
print("\nFinished!")
| true |
21876cd398818650391b28baa9af0e149b97f3bf | Adark-Amal/Python-for-Everybody | /PYTHON 4 EVERYONE/Programming for Everybody (Getting Started with Python)/WEEK 4/assignment_2.3.py | 774 | 4.25 | 4 | """
2.3 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25).
You should use input to read a string and float() to convert the string to a number.
Do not worry about error checking or bad user data.
"""
# Ask the user input which is usually a string and convert the input to float data type
user_input1 = input("Enter number of hours: ")
hours = float(user_input1)
# Ask for user input which is usually a string and convert the input to float data type
user_input2 = input("Enter rate: ")
rate = float(user_input2)
# Compute the grosspay and print the results
grossPay = hours * rate
print("Pay:", grossPay) | true |
aef3ee5e1118a1f8cb62c586e516fe51e2e5764b | salina-k/IW-Python-Assignment-II | /Q5.py | 650 | 4.59375 | 5 | # Create a tuple with your first name, last name, and age. Create a list,
# people, and append your tuple to it. Make more tuples with the
# corresponding information from your friends and append them to the
# list. Sort the list. When you learn about sort method, you can use the
# key parameter to sort by any field in the tuple, first name, last name,
# or age.
my_tuple = ('Salina', 'Karki', 22)
people = []
people.append(my_tuple)
print(people)
t1 = ('Cece', 'Thapa', 23)
t2 = ('Phoebe', 'Tuitui', 21)
people.extend([t1, t2])
print(people)
sorted_list = sorted(people, key=lambda tup: tup[2]) # sorting tuple by age field
print(sorted_list)
| true |
ba0646c33dc3342ebb7f5782189690dac7f85cfd | Hamng/hamnguyen-sources | /python/xml_count_attrib.py | 2,678 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 15:26:30 2019
@author: Ham
HackerRanch Challenge: XML 1 - Find the Score
You are given a valid XML document, and you have to print its score.
The score is calculated by the sum of the score of each element.
For any element, the score is equal to the number of attributes it has.
Input Format
The first line contains N, the number of lines in the XML document.
The next N lines follow containing the XML document.
Output Format
Output a single line, the integer score of the given XML document.
Sample Input (also see STDIN_SIO below)
6
<feed xml:lang='en'>
<title>HackerRank</title>
<subtitle lang='en'>Programming challenges</subtitle>
<link rel='alternate' type='text/html' href='http://hackerrank.com/'/>
<updated>2013-12-25T12:00:00</updated>
</feed>
Sample Output
5
Explanation
The feed and subtitle tag have one attribute each - lang.
The title and updated tags have no attributes.
The link tag has three attributes - rel, type and href.
So, the total score is 1 + 0 + 1 + 3 + 0 == 5.
There may be any level of nesting in the XML document. To learn about XML parsing, refer here.
NOTE: In order to parse and generate an XML element tree, use the following code:
>> import xml.etree.ElementTree as etree
>> tree = etree.ElementTree(etree.fromstring(xml))
Here, XML is the variable containing the string.
Also, to find the number of keys in a dictionary, use the len function:
>> dicti = {'0': 'This is zero', '1': 'This is one'}
>> print (len(dicti))
2
"""
#import io
import xml.etree.ElementTree as etree
STDIN_SIO = """
15
<feed xml:lang='en'>
<entry>
<author gender='male'>Harsh</author>
<question type='medium' language='python'>XML 2</question>
<description type='text'>This is related to XML parsing</description>
</entry><entry>
<author gender='male'>Harsh</author>
<question type='medium'>XML 2</question>
<description type='text'>This is related to XML parsing</description>
</entry><entry>
<author gender='male'>Harsh</author>
<question type='medium'>XML 2</question>
<description type='text'>This is related to XML parsing</description>
</entry>
</feed>
""".strip()
def get_attr_number(node):
"doc"
return len(node.attrib) + sum(get_attr_number(child) for child in node)
if __name__ == '__main__':
STDIN_SIO = STDIN_SIO.split("\n", 1)[1:] # discard 1st line
#print(len(STDIN_SIO), "<" + STDIN_SIO[0] + ">")
tree = etree.ElementTree(etree.fromstring(STDIN_SIO[0]))
print(get_attr_number(tree.getroot()))
| true |
d10447e6631e20727f56e1ad9d4d01aced76eeb2 | Hamng/hamnguyen-sources | /python/HackerRank/beautiful_days.py | 2,896 | 4.53125 | 5 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 07:59:28 2020
@author: Ham
HackerRank > Practice > Algorithms > Implementation
Beautiful Days at the Movies
Problem
Lily likes to play games with integers.
She has created a new game where she determines the difference between
a number and its reverse.
For instance, given the number 12, its reverse is 21. Their difference is 9.
The number 120 reversed is 21, and their difference is 99.
She decides to apply her game to decision making.
She will look at a numbered range of days
and will only go to a movie on a beautiful day.
Given a range of numbered days, [i ... j] and a number k,
determine the number of days in the range that are beautiful.
Beautiful numbers are defined as numbers
where |i - reverse(i)| is evenly divisible by k.
If a day's value is a beautiful number, it is a beautiful day.
Print the number of beautiful days in the range.
Function Description
Complete the beautifulDays function in the editor below.
It must return the number of beautiful days in the range.
beautifulDays has the following parameter(s):
i: the starting day number
j: the ending day number
k: the divisor
Input Format
A single line of three space-separated integers
describing the respective values of i, j, and k.
Constraints
Output Format
Print the number of beautiful days in the inclusive range between i and j.
Sample Input
20 23 6
Sample Output
2
Explanation
Lily may go to the movies on days 20, 21, 22, and 23.
We perform the following calculations to determine which days are beautiful:
Day 20 is beautiful because the following evaluates to a whole number:
Day 21 is not beautiful because the following doesn't evaluate to a whole number:
Day 22 is beautiful because the following evaluates to a whole number:
Day 23 is not beautiful because the following doesn't evaluate to a whole number:
Only two days, 20 and 22, in this interval are beautiful.
Thus, we print 2 as our answer.
"""
#!/bin/python3
#import math
#import os
#import random
#import re
#import sys
import io
# Test case 6: Expected Output: 9657
STDIN_SIO = io.StringIO("""
1 123456 13
""".strip())
def backward(i):
res = 0
while i != 0:
res = res*10 + (i % 10)
i //= 10
return res
def divisible(i, k):
return abs(i - backward(i)) % k == 0
# Complete the beautifulDays function below.
def beautifulDays(i, j, k):
return len([True for e in range(i, j + 1) if divisible(e, k)])
if __name__ == '__main__':
#fptr = open(os.environ['OUTPUT_PATH'], 'w')
#ijk = input().split()
ijk = STDIN_SIO.readline().split()
i = int(ijk[0])
j = int(ijk[1])
k = int(ijk[2])
result = beautifulDays(i, j, k)
print(result)
#fptr.write(str(result) + '\n')
#fptr.close()
| true |
5806a5706d4c607edfc644b428fbb1937557c25e | Hamng/hamnguyen-sources | /python/one-liner/set_add.py | 1,599 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 19:55:30 2019
@author: Ham
HackerRanch Challenge: Set .add()
If we want to add a single element to an existing set,
we can use the .add() operation.
It adds the element to the set and returns 'None'.
Example
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])
Task
Apply your knowledge of the .add() operation to help your friend Rupal.
Rupal has a huge collection of country stamps.
She decided to count the total number of distinct country stamps in her collection.
She asked for your help.
You pick the stamps one by one from a stack of country stamps.
Find the total number of distinct country stamps.
Input Format
The first line contains an integer N, the total number of country stamps.
The next N lines contains the name of the country where the stamp is from.
Constraints
Output Format
Output the total number of distinct country stamps on a single line.
Sample Input
7
UK
China
USA
France
New Zealand
UK
France
Sample Output
5
"""
import io
STDIN_SIO = io.StringIO("""
7
UK
China
USA
France
New Zealand
UK
France
""".strip())
if __name__ == '__main__':
#print(len({input().strip() for _ in range(int(input()))}))
print(len({STDIN_SIO.readline().strip().strip()
for _ in range(int(STDIN_SIO.readline().strip()))}))
#print(stamps)
#print(len(stamps))
| true |
43d1be126f436bad5dd424daa3c5084866e9eff6 | Hamng/hamnguyen-sources | /python/one-liner/list_comp.py | 986 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 23 18:49:34 2019
@author: Ham
HackerRank Challenge: List Comprehensions
Let's learn about list comprehensions! You are given three integers x, y and z
representing the dimensions of a cuboid along with an integer n.
You have to print a list of all possible coordinates given by (i,j,k)
on a 3D grid where the sum of i+j+k is not equal to n.
Here, 0 <= i <= x; 0 <= j <= y; 0 <= k <= z
Input Format
Four integers and each on four separate lines, respectively.
Constraints
Print the list in lexicographic increasing order.
Sample Input 0
1
1
1
2
Sample Output 0
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
"""
if __name__ == '__main__':
#x = int(input())
#y = int(input())
#z = int(input())
#n = int(input())
x, y, z, n = 1, 1, 1, 2
print([[i, j, k] for i in range(x+1)
for j in range(y+1)
for k in range(z+1) if i+j+k != n])
| true |
1227987542d7b92225c77dd078eb61b04bb19bdf | GloriaAnholt/PythonProjects | /Algorithms-DataStructures/recursive_factorial.py | 736 | 4.25 | 4 | # Algorithms & Data Structures: Recursive Exercises
# 03.29.16
# @totallygloria
import unittest
'''
Write a recursive function to compute the factorial of a number
'''
def factorial_calc(num):
if num <= 1:
return 1
else:
total = num * factorial_calc(num-1)
return total
class Factorial_Calc_Tester(unittest.TestCase):
def factorial_calc(self):
self.assertEqual(factorial_calc(0), 1)
self.assertEqual(factorial_calc(-243), 1)
self.assertEqual(factorial_calc(2), 2)
self.assertEqual(factorial_calc(5), 120)
self.assertEqual(factorial_calc(9), 362880)
self.assertNotEquals(factorial_calc(4), 12)
if __name__ == '__main__':
unittest.main()
| true |
f808093e69c634b0758ac7b749b616cb9f9898a3 | GloriaAnholt/PythonProjects | /Algorithms-DataStructures/test_QuickSort.py | 2,268 | 4.25 | 4 | # Algorithms and Data Structures: Quick Sort
# 07.07.2016
# @totallygloria
import unittest
import random
from QuickSort import QuickSort
class QuickSortTester(unittest.TestCase):
def test_getpivot(self):
qs = QuickSort()
# Basic case, find middle of three, regardless of location in list
qs.array = [1,2,3]
self.assertEquals(qs.getpivot(0, 2), 2)
qs.array = [2,1,3]
self.assertEquals(qs.getpivot(0, 2), 2)
qs.array = [1,3,2]
self.assertEquals(qs.getpivot(0, 2), 2)
# One-item list
qs.array = [-7]
self.assertEquals(qs.getpivot(0, 0), -7)
# List of the same item repeated
qs.array = [2,2,2,2,2,2,2,2,2,2]
self.assertEquals(qs.getpivot(0, 9), 2)
# Find middle of three when they're the same and the list is longer
qs.array = [10, 2, 2, 2, 10, 2, 2, 2, 2, 10]
self.assertEquals(qs.getpivot(0, 9), 10)
# Find middle of three when only two are the same
qs.array = [10, 2, 2, 2, 10, 2, 2, 2, 2, 0]
self.assertEquals(qs.getpivot(0, 9), 10)
qs.array = [0, 2, 2, 2, 10, 2, 2, 2, 2, 10]
self.assertEquals(qs.getpivot(0, 9), 10)
qs.array = [10, 2, 2, 2, 0, 2, 2, 2, 2, 10]
self.assertEquals(qs.getpivot(0, 9), 10)
def test_quicksort(self):
qs = QuickSort()
# Base case: empty list or list of one element should return itself
self.assertEquals(qs.quicksort(), [])
qs.array = [1]
self.assertEquals(qs.quicksort(), [1])
# quicksort doesn't return anything, it just calls exchanger
# probably not possible to test that the list comes back sorted
def test_exchanger(self):
qs = QuickSort()
# A list of len <= 1 should return the list itself
self.assertEquals(qs.exchanger(10, 10), None)
self.assertEquals(qs.exchanger(10, 0), None)
for trial in range(100):
qs.array = []
for i in range(10000):
qs.array.append(random.randrange(-100000,100000))
copyqs = list(qs.array)
copyqs.sort()
qs.exchanger(0, 9999)
self.assertEquals(qs.array,copyqs)
if __name__ == '__main__':
unittest.main()
| true |
79598573ad0486cce572cf7791066ad59e2974f0 | GloriaAnholt/PythonProjects | /Algorithms-DataStructures/hashtable_openaddressing.py | 2,518 | 4.34375 | 4 | # Algorithms and Data Structures: Hash Tables & Hashing
# 4.21.2016
# @totallygloria
"""
Uses a python list to hold the values in the hash table.
Hash function is a basic module arithmetic:
h(item) = item**2 % table_size
If there's a collision, resolves using open addressing.
"""
def create_table(des_len):
# Returns a list 2x the desired length, populated with None
return [None] * (2 * des_len)
def insert_hash(item, table):
# Hashes item, if the slot is empty it inserts, otherwise it walks the table
# until it finds an open slot (None) or a 'USED' slot and puts it there.
# Wraps at the end of the table. Does not accept duplicate entries.
size = len(table)
hashed_val = item**2 % size
if table[hashed_val] == item:
return
elif table[hashed_val] is None or table[hashed_val] == 'USED':
table[hashed_val] = item
else:
while table[hashed_val] is not None and table[hashed_val] != 'USED':
hashed_val += 1
if hashed_val >= size:
hashed_val = 0
if table[hashed_val] == item:
return
table[hashed_val] = item
def search_hash(item, table):
# Hashes item, checks if it's in the hash table - if it's not where it's expected
# to be, walks the table until a None is found. Returns a boolean.
size = len(table)
hashed_val = item**2 % size
if table[hashed_val] == item:
return True
else:
if table[hashed_val] is not None:
while table[hashed_val] is not None:
if table[hashed_val] == item:
return True
hashed_val += 1
if hashed_val >= size:
hashed_val = 0
return False
def remove_item(item, table):
# Searches for an item in the hash table, if it's not in the proper slot,
# checks until you hit the first None. When the item is found, it's replaced
# with a marker and returns a boolean.
size = len(table)
hashed_val = item**2 % size
if table[hashed_val] == item:
table[hashed_val] = 'USED'
return True
else:
if table[hashed_val] != item and table[hashed_val] is not None:
while table[hashed_val] is not None:
if table[hashed_val] == item:
table[hashed_val] = 'USED'
return True
hashed_val += 1
if hashed_val >= size:
hashed_val = 0
return False
| true |
05d0f36b0940e23841af8faf391fb21c66ec735b | abraham953/Python | /FifthExample.py | 211 | 4.28125 | 4 | name = input('What is your name?')
length = len(name)
print(length)
if length < 3:
print('The name is too short')
elif length > 50:
print('The name is too ling')
else:
print('The name looks good!!!') | true |
82b41e444e97e23abaf5ce6d9c42a935f67eb55f | SubsanMainali/Capstone_Project | /factorial.py | 615 | 4.34375 | 4 | # Calculate factorial of a given number
# Making sure the value is a positive integer
# This program cannot handle very large numbers; maximum value is 998
# recursive function to calculate factorial
def factorial(number):
if number == 0:
return 1
elif number == 1:
return number
else:
return number*factorial(number-1)
num = 0
flag = True
while flag:
try:
num = int(input("Enter a counting number"))
flag = False
num = abs(num)
except ValueError:
print("Expected a counting number")
print(f'Factorial of {num} is {factorial(num)}')
| true |
3cd6c9e6f486380fddb2727858f3c076c0daab00 | Icecarry/learn | /day10/动物类.py | 711 | 4.4375 | 4 | """
创建一个动物类,
并通过__init__方法接受参数(name),
使用私有属性name保存参数值,并打印"init被调用".
在动物类中定义一个__del__()方法,
使其在删除的时候自动被调用,
并打印"del被调用".
使用动物类,实例化一个dog对象取名"八公"
"""
# 创建动物类
class Animal(object):
# 初始化属性
def __init__(self, name):
self.__name = name
print('init被调用')
# 删除时调用
def __del__(self):
print('del被调用')
# 创建对象dog
dog = Animal('八公')
dog1 = dog
dog2 = dog
print('删除对象dog')
del dog
print('删除对象dog1')
del dog1
print('删除对象dog2')
del dog2
| false |
641c60d5744c3da4d46aabee3a4816fb659902b1 | Icecarry/learn | /day09/动物类.py | 1,322 | 4.53125 | 5 | """
. 任意定义一个动物类
2. 使用`__init__`方法,在创建某个动物对象时接收参数,
为其添加name、age、color,food等属性,如“熊猫”,5, “黑白”,“竹子”
3. 为动物类定义一个run方法,
调用run方法时打印相关信息,
如打印出“熊猫正在奔跑”
4. 为动物类定义一个get_age方法,
调用get_age方法时打印相关信息,
如打印出“这只熊猫今年5岁了”
5. 为动物类定义一个eat方法,
调用eat方法时打印相关信息,
如打印出“熊猫正在吃竹子”
6. 通过动物类分别创建出3只不同种类的动物,
分别调用它们的方法,让他们跑起来,吃起来
"""
class Animal:
def __init__(self, name, age, food, color='黑白'):
self.name = name
self.age = age
self.color = color
self.food = food
def run(self):
print('%s 正在奔跑' % self.name)
def get_age(self):
print("这只 %s 今年 %d 岁了" % (self.name, self.age))
def eat(self):
print('%s 正在吃 %s' % (self.name, self.food))
cat = Animal('cat', 3, '鱼')
cat.run()
cat.get_age()
cat.eat()
panda = Animal('熊猫', 4, '竹子')
panda.run()
panda.get_age()
panda.eat()
dog = Animal('dog', 5, 'shite')
dog.run()
dog.get_age()
dog.eat()
| false |
ac413635a453223098c46310896148957fb9cb39 | Icecarry/learn | /day04/字符串长度统计及逆序.py | 678 | 4.25 | 4 | '''
完成字符串的长度统计以及逆序打印
* 设计一个程序,要求只能输入长度低于31的字符串,否则提示用户重新输入
* 打印出字符串长度
* 使用切片逆序打印出字符串
'''
while True:
# 用户输入,且字符串长度小于31
string = input("请输入字符串,长度请低于31:")
#把字符串存放在列表里方便排序
# string_list = []
# 判断长度是否低于31
length = len(string)
if length < 32:
print("字符串长度为 %d" % length)
print(string[::-1])
break
else:
print("超出长度,请重新输入!")
continue | false |
be3f13268c90ccc0083ac488c03d19acab05f234 | tiagoestrela/cpp210 | /aula1T33.py | 844 | 4.21875 | 4 | #SAÍDA DE DADOS
#A print() serve para exibir na tela para o usuário
#informações como uma mensagem ou conteúdos
#de uma variável
#IMPRIMIR TEXTO->
#conteúdo fixo
#sintaxe print(" texto")
#\n pula linha
#\n dentro das aspas duplas da função print
print("Quero ver o jogo do psg. \n ")
#IMPRIMIR VARIÁVEL
#sintaxe print(nome_da_variável)
nome="Tiago"
idade=38
print(nome)
print(idade)
# sintaxe print() serve para pular linha
print()
#IMPRIMIR TEXTO E VARIÁVEL
#sintaxe print("texto",nome_da_variável)
#ENTRADA DADOS
#função que serve para usuário entrar com
#com os dados via digitação
#sintaxe->input("diga o que você quer colocar")
nome=input("Diga seu nome: \n")
#entrada de dados-> meu nome-> colocado caixinha nome
print("Boa noite", nome, "até amanhã!")
| false |
fb169062e537585131533405d1ab555ce24d167e | sebito91/challenges | /exercism/python/archive/leap/leap.py | 335 | 4.21875 | 4 | """ module to calculate whether this is a leap year """
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
def is_leap_year(year=0):
""" method to check for the leap year """
if year == 0:
return False
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
return False
| true |
2ee6a85bffdcd5a1bfe80f4a2678a50e25e6e278 | sebito91/challenges | /exercism/python/archive/rectangles/rectangles.py | 2,112 | 4.15625 | 4 | """Module to count the ASCII rectangles in a given input."""
def rectangles(strings: list[str]) -> int:
"""Count the number of ASCII rectangles within the given string input.
:param strings: list[str] - series of ASCII rectangles to count
:return: int - number of ASCII rectangles found in a given set of `strings` input.
"""
output = set()
hash_marks = sorted({(line_num, idx) for line_num, line in enumerate(strings) for idx, char in enumerate(line) if char == "+"})
for idx, hash_mark in enumerate(hash_marks):
trs = sorted({coord for coord in hash_marks[idx + 1:] if coord[0] == hash_mark[0]})
brs = sorted({coord for coord in hash_marks[idx + 1:] for tr in trs if coord[1] == tr[1] and coord != tr})
bls = sorted({coord for coord in hash_marks[idx + 1:] for br in brs if coord[0] == br[0] and coord[1] == hash_mark[1]})
for tr in trs:
for br in brs:
for bl in bls:
if hash_mark[1] == bl[1] and br[0] == bl[0] and tr[1] == br[1]:
output.add((hash_mark, tr, br, bl)) # top-left, top-right, bottom-right, bottom-left
bad_options = set()
for option in output:
tl, tr, br, bl = option
# check top side, left-to-right
chars = set(strings[tl[0]][tl[1]:tr[1]])
if chars != {"+", "-"} and chars != {"+"}:
bad_options.add(option)
continue
# check bottom side, left-to-right
chars = set(strings[bl[0]][bl[1]:br[1]])
if chars != {"+", "-"} and chars != {"+"}:
bad_options.add(option)
continue
# check left side, top-to-bottom
chars = {string[tl[1]] for string in strings[tl[0]:bl[0]]}
if chars != {"+", "|"} and chars != {"+"}:
bad_options.add(option)
continue
# check right side, top-to-bottom
chars = {string[tr[1]] for string in strings[tr[0]:br[0]]}
if chars != {"+", "|"} and chars != {"+"}:
bad_options.add(option)
continue
return len(output - bad_options)
| false |
5b4d1782d1b0a9c6bceae50ce2ae96204c81ea7e | meet-projects/welcome_Y2_yearlong | /warmups/week5.py | 1,012 | 4.53125 | 5 | '''
You've built an in-flight entertainment system with on-demand movie streaming.
Users on longer flights like to start a second movie right when their first one ends, but they complain that the plane usually lands before they can see the ending. So you're building a feature for choosing two movies whose total runtimes will equal less than the flight length.
Write a function that takes an integer flight_length (in minutes) and a list of integers movie_lengths (in minutes) and returns a list of tuples containing movie pairs the flight attendents can show along with the total time the movies will take to run.
When building your function:
-Assume your users will watch exactly two movies
-Don't make your users watch the same movie twice
-Optimize for runtime over memory (extra credit)
'''
flight_length = 250
movie_lengths = {"Free Willie" : 90, "Finding Nemo" : 145, "Pirates of the Caribbean": 185, "Interstellar": 65}
def in_flight_movies(flight_length, movie_lengths):
#YOUR CODE HERE
pass
| true |
9cc14eaf47f906b8c650476286033efb17f2cd16 | Rachel-commits/CSparkAssignments | /ads02_eda_supervised/postcodes_mod.py | 1,762 | 4.1875 | 4 | def return_post_codes(df):
"""
Write a function that takes a pandas DataFrame with one column, text, that
contains an arbitrary text. The function should extract all post-codes that
appear in that text and concatenate them together with " | ". The result is
a new dataframe with a column "postcodes" that contains all concatenated
postcodes.
Example input:
text
0 Great Doddington, Wellingborough NN29 7TA, UK\nTaylor, Leeds LS14 6JA, UK
1 This is some text, and here is a postcode CB4 9NE
Expected output:
postcodes
0 NN29 7TA | LS14 6JA
1 CB4 9NE
Note: Postcodes, in the UK, are of one of the following form where `X` means
a letter appears and `9` means a number appears:
X9 9XX
X9X 9XX
X99 9XX
XX9 9XX
XX9X 9XX
XX99 9XX
Even though the standard layout is to include one single space
in between the two halves of the post code, there are occasional formating
errors where an arbitrary number of space is included (0, 1, or more). You
should parse those codes as well.
:param df: a DataFrame with the text column
:return: new DataFrame with the postcodes column
"""
raise NotImplementedError
#custom
print re.findall(r'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b', s)
#regex from #http://en.wikipedia.orgwikiUK_postcodes#Validation
print re.findall(r'[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}', s) | true |
65970ba472934a19a474f4565f758ff931110e22 | Rachel-commits/CSparkAssignments | /ads05_databases/pt1_essentials.py | 1,868 | 4.125 | 4 | # Part 1: Essentials
def business_ids_count():
"""
Write a SQL query that finds the number of business ids in the businesses table
:return: a string representing the SQL query
:rtype: str
"""
query = 'SELECT COUNT(business_id) FROM businesses'
return query
def unique_business_names_count():
"""
Write a SQL query that finds out how many unique business names are registered
with San Francisco Food health investigation organization
and name the column as unique restaurant name count.
:return: a string representing the SQL query
:rtype: str
"""
query = """SELECT COUNT(DISTINCT name) FROM businesses"""
return query
def first_and_last_investigation():
"""
Write a SQL query that finds out what is the earliest and latest date
a health investigation is recorded in this database.
:return: a string representing the SQL query
:rtype: str
"""
query = """SELECT
MIN(date) as earliest_date,
MAX(date) as latest_date
FROM inspections"""
return query
def business_local_owner_count():
"""
How many businesses are there in San Francisco where their owners live
in the same area (postal code/ zip code) as the business is located?
:return: a string representing the SQL query
:rtype: str
"""
query = """SELECT COUNT(business_id)
FROM businesses
WHERE postal_code = owner_zip"""
return query
def business_local_owner_reg_count():
"""
Out of those businesses, how many of them has a registered business certificate?
:return: a string representing the SQL query
:rtype: str
"""
query = """SELECT COUNT(*)
FROM businesses
WHERE
postal_code = owner_zip AND
business_certificate iS NOT NULL"""
return query
| true |
56657c8f5a00488c2d5de4a085feb4d9e0310862 | sajib1066/python-projects | /list_app.py | 2,234 | 4.375 | 4 | #THIS IS AN SIMPLE LIST OPERATION APPLICATION
print('------------List Application------------')
print(' 1. Add Element')
print(' 2. Change Element')
print(' 3. Delete Element')
print(' 4. Show List')
print(' 5. Show Indexed Data')
print(' 0. Exit')
print('------------List Application------------')
storage = [] #DECLARE LIST
while True:
operation = int(input('Please Enter Operation: '))
#EXIT OPERATION
if operation == 0:
confirm = input('Are you sure to exit! Enter \'yes\': ')
if confirm == 'yes':
break
#ADD ELEMENT OPERATION
if operation == 1:
item = input('Enter an item: ').split()
storage.extend(item)
print('{} is added in list!'.format(item))
#CHANGE ELEMENT OPERATION
if operation == 2:
if len(storage) < 1:
print('List is Empty!')
else:
index = int(input('Enter item\'s index 0 to {}: '.format(len(storage)-1)))
if index < len(storage)-1:
print('Old item is {}'.format(storage[index]))
new_item = input('Enter an new item: ')
storage[index] = new_item
print('Data: ', storage)
else:
print('Index out of Range!')
#print('{} as new item add on {} position!'.format(new_item, index))
#DELETE ELEMENT OPERATION
if operation == 3:
index = int(input('Enter item\'s index: '))
confirm = input('Enter yes for confirm: ')
if (index <= len(storage)-1):
print('{} is deleted from {} position!'.format(storage[index], index))
if confirm == 'yes':
del storage[index]
print('Data delete successfully!')
else:
print('Data: ', storage, 'Length: ', len(storage))
print('Data not deleted!')
else:
print('Index out of bound!')
#SHOW LIST OPERATION
if operation == 4:
print('Data: ', storage)
print('Length: ', len(storage))
#SHOW INDEXED DATA OPERATION
if operation == 5:
for data in storage:
print(data)
print('Length: ', len(storage))
| true |
a13a7fe0d8466f78fc02738815f1751679da3d86 | Gibran2001/CursoPython | /CURSO PYTHON/Promedio.py | 1,021 | 4.25 | 4 | '''
EJERCICIO 9
Programa hecho por Mauricio Gibrán Colima Flores
Curso de Introducción a Python
'''
#Importar librería
import os
os.system("cls")
#Mensajes iniciales
print("\t\t\tEste programa pide datos de alumnos y genera su promedio del grupo")
#Proceso
op=0
nAlmumnos=0
sumaCalf=0
lista=[]
while(op!=2):
print("1.Agregar alumno\n2.Salir y promediar")
op=int(input("Presiona la opcion que quieres realizar: "))
if(op==1):
nAlmumnos=nAlmumnos+1
nom=input("Introdice el nombre del alumno: ")
calf=input("\nIntroduce su calificacion: ")
sumaCalf=sumaCalf+int(calf)
reg=nom+", "+calf+"\n"
lista.append(reg)
elif(op==2):
if(nAlmumnos==0):
print("No hay alumnos en este grupo")
else:
print("El grupo est[a conformado por: "+str(lista))
prom=sumaCalf/nAlmumnos
print("\n\nEl promedio del grupo es: "+str(prom))
else:
print("Opcion incorrecta... Reiniciando programa") | false |
aed87e0a450bc040f40304ae3568a0a1685fb076 | umberahmed/python-practice | /rolldice.py | 1,220 | 4.3125 | 4 | """This program will roll a dice and ask the user to guess the sum."""
from random import randint # importing randit from random for number to guess
from time import sleep # importing sleep to delay output and build player suspense
def get_user_guess():
"""Ask user to guess a number"""
guess = int(raw_input("Guess a number: "))
return guess
def roll_dice(number_of_sides = 6):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print "The maximum possible value is: %d" % max_val
guess = get_user_guess()
if guess > max_val:
print "No guessing higher than the maximum possible value!"
else:
print "\nRolling..."
sleep(2)
print "The 1st roll is: %d" % first_roll
sleep(1)
print "The 2nd roll is: %d" % second_roll
sleep(1)
total_roll = first_roll + second_roll
print "Result..."
sleep(1)
print "\n %d" % total_roll
if guess == total_roll:
print "You guessed correctly! You win!"
else:
print "You lose :-("
roll_dice(20)
| true |
8cec315ee2d11338aac932d65f0a35bb2105d6fd | hkk828/DataStructures | /OrderedLinkedList.py | 1,660 | 4.1875 | 4 | from LinkedList import *
# Values are ordered in ascending order (Smaller the value, closer to head)
class OrderedLinkedList(LinkedList):
# Overriding a method from LinkedList so that the values are ordered
def append(self, val):
if len(self) == 0:
self.head = ListNode(val)
else:
# 'cursor' loops over the list, 'prev' is the previous node,
# and 'found' checks whether a value bigger than val is found
prev = None
cursor = self.head
while cursor:
if cursor.val > val:
break
prev = cursor
cursor = cursor.get_next()
new_node = ListNode(val, cursor)
# val should be appended in front if it is the smallest
# self.head is changed to the 'val'
if prev == None:
self.head = new_node
# val is appended on other than the front. It can be added at the end.
else:
prev.set_next(new_node)
self.size += 1
if __name__ == '__main__':
l = OrderedLinkedList()
l.append(9)
l.append(7)
l.append(1)
l.append(5)
l.append(3)
print(l) # head-> 1-> 3-> 5-> 7-> 9
from random import randint
messy = LinkedList()
for i in range(10):
messy.append(randint(0, 1000))
print(messy) # head-> ... random values in [0, 1000]
# function that sorts a unordered LinkedList using OrderedLinkedList data structure
def sort_list(l: LinkedList) -> LinkedList:
temp = OrderedLinkedList()
cursor = l.head
while cursor:
temp.append(cursor.get_value())
cursor = cursor.get_next()
sorted = LinkedList()
cursor = temp.head
while cursor:
sorted.append(cursor.get_value())
cursor = cursor.get_next()
return sorted
print(sort_list(messy)) # head-> ... sorted messy
| true |
c97cc0eadd5f6b73c44b9a54fcb7172b1e8b4675 | jjagdishh/python-practice-codes | /functions.py | 1,844 | 4.375 | 4 | # This is a sample to show the functions in pyton
# we have two list of expensis one for vikas and one for ram. we want to calculate it
# to calculate it we have two options in python one is simple defining for loop for each list and print the total
# second is we can define a function and we can call them may time as we need and we do not have to define for loop each time for each list.
vikas_total_exp=[100,200,500,50,150] # expense list of vikas
ram_total_exp=[200, 300, 400, 300] # expense list of ram
# First Method!
# uncomment when you want run first method and comment secon method
total=0 # defining variable total
for item in vikas_total_exp: # make a for loop for vikas list
total=total+item # calculating the total items from list
print("Vikas total expenses = ",total) # printing the output from total
# same way calculation done for ram expenses
total=0
for item in ram_total_exp:
total=total+item
print("Ram's total expenses =",total)
# Second Method
'''def calculating_total(exp): # defining a function called "calculating_total". exp is the local variable input
total=0 # Defining variable total
for item in exp: # for loop for expense list "input = exp"
total=total+item # calculating the total items from input list
return total # returning the total output. Note ! return shoud start from where the for loop start. mind the space
# so our function is ready now we have to calculate the vikas and ram expenses via this function
vikas_total=calculating_total(vikas_total_exp) # calling the function and input the list you want to calculate
ram_total= calculating_total(ram_total_exp)
print (vikas_total) # print the total calculated for the variable
print (ram_total)'''
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.