blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
acd10df184f13bb7c54a6f4a5abac553127b27af | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_create_grade_calculator.py | 830 | 4.25 | 4 | #Python code for the Grade
#Calculate program in action
#Creating a dictionary which
#consists of the student name,
#assignment result test results
#And their respective lab results
def grade(student_grade):
name=student_grade['name']
assignment_marks=student_grade['assignment']
assignment_score=sum(assignment_marks)/len(assignment_marks)
test_marks=student_grade['test']
test_score=sum(test_marks)/len(test_marks)
lab_marks=student_grade['lab']
lab_score=sum(lab_marks)/len(lab_marks)
score=0.1*assignment_score+0.7*test_score+0.2*lab_score
if score>=90 :return 'A'
elif score>=80 :return 'B'
elif score>=70 :return 'C'
elif score>=60 :return 'D'
jack={"name":"Jack Frost","assignment":[80,50,40,20],"test":[75,75],"lab":[78,20,77,20]}
x=grade(jack)
print(x)
| true |
968829ff7ec07aabb3dedfb89e390334b9b9ee57 | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_check_if_a_string_is_palindrome_or_not.py | 450 | 4.3125 | 4 | print("This is python program to check if a string is palindrome or not")
string=input("Enter a string to check if it is palindrome or not")
l=len(string)
def isPalindrome(string):
for i in range(0,int(len(string)/2)):
if string[i]==string[l-i-1]:
flag=0
continue
else :
flag=1
return flag
ans=isPalindrome(string)
if ans==0:
print("Yes")
else:
print("No")
| true |
06132de9f0dd0dfbf3138ead23bd4a936ca4a70a | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_interchange_first_and_last_elements_in_a_list_using_pop.py | 277 | 4.125 | 4 | print("This is python program to swap first and last element using swap")
def swapList(newList):
first=newList.pop(0)
last=newList.pop(-1)
newList.insert(0,last)
newList.append(first)
return newList
newList=[12,35,9,56,24]
print(swapList(newList))
| true |
0901c75662df3c0330deb4d25087868ba0693e94 | dipesh1011/NameAgeNumvalidation | /multiplicationtable.py | 360 | 4.1875 | 4 | num = input("Enter the number to calculate multiplication table:")
while(num.isdigit() == False):
print("Enter a integer number:")
num = input("Enter the number to calculate multiplication table:")
print("***************************")
print("Multiplication table of",num,"is:")
for i in range(1, 11):
res = int(num) * i
print(num,"*",i,"=",res) | true |
8ed94e5a5bc207a34271e2bb52029d7b6b71870d | darlenew/california | /california.py | 2,088 | 4.34375 | 4 | #!/usr/bin/env python
"""Print out a text calendar for the given year"""
import os
import sys
import calendar
FIRSTWEEKDAY = 6
WEEKEND = (5, 6) # day-of-week indices for saturday and sunday
def calabazas(year):
"""Print out a calendar, with one day per row"""
BREAK_AFTER_WEEKDAY = 6 # add a newline after this weekday
c = calendar.Calendar()
tc = calendar.TextCalendar(firstweekday=FIRSTWEEKDAY)
for month in range(1, 12+1):
print()
tc.prmonth(year, month)
print()
for day, weekday in c.itermonthdays2(year, month):
if day == 0:
continue
print("{:2} {} {}: ".format(day,
calendar.month_abbr[month],
calendar.day_abbr[weekday]))
if weekday == BREAK_AFTER_WEEKDAY:
print()
def calcium(year, weekends=True):
"""Print out a [YYYYMMDD] calendar, no breaks between weeks/months"""
tc = calendar.TextCalendar()
for month_index, month in enumerate(tc.yeardays2calendar(year, width=1), 1):
for week in month[0]: # ?
for day, weekday in week:
if not day:
continue
if not weekends and weekday in (WEEKEND):
print()
continue
print(f"[{year}{month_index:02}{day:02}]")
def calzone(year):
"""Prints YYYYMMDD calendar, like calcium without weekends"""
return calcium(year, weekends=False)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="print out a calendar")
parser.add_argument('year', metavar='YEAR', type=int, help='the calendar year')
parser.add_argument('style', metavar='STYLE', help='calendar style')
args = parser.parse_args()
style = {'calcium': calcium,
'calabazas': calabazas,
'calzone': calzone,
}
try:
style[args.style](args.year)
except KeyError:
raise(f"Calendar style {args.style} not found")
| true |
d86ab402a950557261f140137b2771e84ceafbbe | priyankagarg112/LeetCode | /MayChallenge/MajorityElement.py | 875 | 4.15625 | 4 | '''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
'''
from typing import List
#Solution1:
from collections import Counter
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return Counter(nums).most_common(1)[0][0]
#Solution2:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
visited = []
for i in nums:
if i in visited:
continue
if nums.count(i) > (len(nums)/2):
return i
visited.append(i)
if __name__ == "__main__":
print(Solution().majorityElement([3,1,3,2,3]))
| true |
433027b761e728e242c5b58c11866208fe39ca23 | caesarbonicillo/ITC110 | /quadraticEquation.py | 870 | 4.15625 | 4 | #quadratic quations must be a positive number
import math
def main():
print("this program finds real solutions to quadratic equations")
a = float(input("enter a coefficient a:"))
b = float(input("enter coefficient b:"))
c = float(input("enter coefficient c:"))
#run only if code is greater or qual to zero
discrim = b * b - 4 * a *c
if(discrim < 0): #1, 2, 3
print("no real roots") # should always put the default in before any real work that way it doesn't do any unnessesary work.
elif(discrim ==0):#1, 2, 1
root = -b / (2 * a)
print("there is a double root at", root)
else:#1, 5, 6
discRoot = math.sqrt(b * b -4 *a *c)
root1 = (-b + discRoot) / (2* a)
root2 = (-b - discRoot) / (2 * a)
print ("\nThe solutions are:", root1, root2)
main()
| true |
12c96ea6817d91f8d488f13c119752f747971c94 | caesarbonicillo/ITC110 | /Temperature.py | 496 | 4.125 | 4 | #convert Celsius to Fehrenheit
def main(): #this is a function
#input
celsius = eval (input ("Enter the temp in Celsius ")) #must convert to number call function EVAL
#processing
fahrenheit = round(9/5 * celsius + 32, 0)
#output
print (celsius, "The Fehrenheit temp is", fahrenheit)
main() # press f5 to run
def kiloMile():
kilo = eval (input("enter kilometers "))
miles = 1.6 * kilo
print ( kilo, "The conversion is", miles)
kiloMile()
| true |
d8325a2d9e1214a72880b37b023d4af1a8d88469 | pandeesh/CodeFights | /Challenges/find_and_replace.py | 556 | 4.28125 | 4 | #!/usr/bin/env python
"""
ind all occurrences of the substring in the given string and replace them with another given string...
just for fun :)
Example:
findAndReplace("I love Codefights", "I", "We") = "We love Codefights"
[input] string originalString
The original string.
[input] string stringToFind
A string to find in the originalString.
[input] string stringToReplace
A string to replace with.
[output] string
The resulting string.
"""
def findAndReplace(o, s, r):
"""
o - original string
s - substitute
r - replace
"""
return re.sub(s,r,o)
| true |
5fa88d472f98e125a2dd79e2d6986630bbb28396 | pandeesh/CodeFights | /Challenges/palindromic_no.py | 393 | 4.125 | 4 | #!/usr/bin/env python
"""
You're given a digit N.
Your task is to return "1234...N...4321".
Example:
For N = 5, the output is "123454321".
For N = 8, the output is "123456787654321".
[input] integer N
0 < N < 10
[output] string
"""
def Palindromic_Number(N):
s = ''
for i in range(1,N):
s = s + str(i)
return s + str(N) + s[::-1]
#tests
print(Palindromic_Number(5))
| true |
83a2fe0e985ffa4d33987b15e6b4ed8a6eb5703b | Nbouchek/python-tutorials | /0001_ifelse.py | 836 | 4.375 | 4 | #!/bin/python3
# Given an integer, , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5, print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
# Input Format
#
# A single line containing a positive integer, .
#
# Constraints
#
# Output Format
#
# Print Weird if the number is weird; otherwise, print Not Weird.
#
# Sample Input 0
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input("Enter a number >>> ").strip())
if n % 2 == 1:
print("Weird")
if n % 2 == 0 and 2 <= n <= 5:
print("Not Weird")
if n % 2 == 0 and 6 <= n <= 20:
print("Weird")
if n % 2 == 0 and n > 20:
print("Not Weird")
| true |
a30b0e3f5120fc484cd712f932171bd322e757df | ByketPoe/gmitPandS | /week04-flow/lab4.1.3gradeMod2.py | 1,152 | 4.25 | 4 | # grade.py
# The purpose of this program is to provide a grade based on the input percentage.
# It allows for rounding up of grades if the student is 0.5% away from a higher grade bracket.
# author: Emma Farrell
# The percentage is requested from the user and converted to a float.
# Float is appropriate in this occasion as we do not want people to fail based on rounding to an integer.
percentage = float(input("Enter the percentage: "))
# In this modification of the program, the percentage inputted by the user is rounded.
# As we want to round up if the first decimal place is 0.5 or greater, we do not need to state number of decimal places.
percentageRounded = round(percentage)
# The if statements are executed as in the original program, but evaluating the new variable "percentageRounded" instead of "percentage"
if percentageRounded < 0 or percentageRounded > 100:
print("Please enter a number between 0 and 100")
elif percentageRounded < 40:
print("Fail")
elif percentageRounded < 50:
print("Pass")
elif percentageRounded < 60:
print("Merit 1")
elif percentageRounded < 70:
print("Merit 2")
else:
print("Distinction") | true |
6f16bc65643470b2bca5401667c9537d88187656 | ByketPoe/gmitPandS | /week04-flow/lab4.1.1isEven.py | 742 | 4.5 | 4 | # isEven.py
# The purpose of this program is to use modulus and if statements to determine if a number is odd or even.
# author: Emma Farrell
# I prefer to use phrases like "text" or "whole number" instead of "string" and "integer" as I beleive they are more user friendly.
number = int(input("Enter a whole number: "))
# Modulus (%) is used to calculated the remainder of the input number divided by 2.
# The if statement evaluates if the remainder is equal to 0.
# If true, the number is even and a message to indicate this is printed.
# Otherwise, the number is odd and the message diplayed will state that it is odd.
if (number % 2) == 0:
print("{} is an even number".format(number))
else:
print("{} is an odd number".format(number)) | true |
5901b1fcabefe69b1ecc24f2e15ffe2d3daed18b | MaurizioAlt/ProgrammingLanguages | /Python/sample.py | 454 | 4.125 | 4 |
#input
name = input("What is your name? ")
age = input("What is your age? ")
city = input("What is your city ")
enjoy = input("What do you enjoy? ")
print("Hello " + name + ". Your age is " + age )
print("You live in " + city)
print("And you enjoy " + enjoy)
#string stuff
text = "Who dis? "
print(text*3)
#or for lists
listname.reverse
#reverse
print(text[::-1])
len(text)
#if condition:
# code...
#else if condition:
# code...
#else:
# code...
| true |
e91613869c1751c8bb3a0a0abaeb1dfb9cafa5c3 | MingCai06/leetcode | /7-ReverseInterger.py | 1,118 | 4.21875 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
class Solution:
def reverse(self, x: int) -> int:
r_x = ''
if x > -10 and x<10:
return x
elif x > pow(2,31)-1 or x < -pow(2,31):
return 0
else:
str_x =str(x)
if x>0:
r_x = r_x
elif x<0:
str_x = str_x[1:]
r_x += '-'
for i in reversed(range(len(str_x))):
if i== len(str_x)-1 and str_x[i]==0:
r_x = r_x
else:
r_x = r_x + str_x[i]
if int(r_x)> pow(2,31)-1 or int(r_x) < -pow(2,31):
return 0
else:
return int(r_x)
| true |
169aab304dfd600a169822c65e448b7e4a4abeb3 | simgroenewald/Variables | /Details.py | 341 | 4.21875 | 4 | # Compulsory Task 2
name = input("Enter your name:")
age = input ("Enter your age:")
house_number = input ("Enter the number of your house:")
street_name = input("Enter the name of the street:")
print("This is " + name + " he/she is " + age + " years old and lives at house number " + house_number + " on " + street_name +" street.")
| true |
4e8834fd82ae0c6b78a0d134058afbdb11d2da95 | MaxiFrank/calculator-2 | /new_arithmetic.py | 1,560 | 4.28125 | 4 | """Functions for common math operations."""
def add(ls):
sum = 0
for num in ls:
sum = sum + num
return sum
def subtract(ls):
diff = 0
for num in ls:
diff = num - diff
return diff
# def multiply(num1, num2):
def multiply(ls):
"""Multiply the two inputs together."""
result = 1
for num in ls:
result = result * num
return result
def divide(ls):
"""Divide the first input by the second and return the result."""
result = 1
for num in ls:
result = num / result
return result
def square(num1):
# doesn't make sense to have a list
"""Return the square of the input."""
return num1 * num1
def cube(num1):
# doesn't make sense to have a list
"""Return the cube of the input."""
return num1 * num1 * num1
def power(ls):
"""Raise num1 to the power of num2 and return the value."""
result = ls[0]
for num in ls[1:]:
result = result ** num
return result # ** = exponent operator
def mod(num1, num2):
"""Return the remainder of num1 / num2."""
result = None
for num in ls:
result = result %num
return result
def add_mult(num1, num2, num3):
"""Add num1 and num2 and multiply sum by num3."""
# uncertain about how this one works. for for example ([1, 2, 3, 4])
return multiply(add(num1, num2), num3)
def add_cubes(ls):
"""Cube num1 and num2 and return the sum of these cubes."""
sum = 0
for num in ls:
sum = sum + cube(num)
return sum
print(divide([2,4,2])) | true |
3264f6baf0939442a45689f1746d62d6be07eece | aacampb/inf1340_2015_asst2 | /exercise2.py | 2,014 | 4.5 | 4 | #!/usr/bin/env python
""" Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing
This module converts performs substring matching for DNA sequencing
"""
__author__ = 'Aaron Campbell, Sebastien Dagenais-Maniatopoulos & Susan Sim'
__email__ = "aaronl.campbell@mail.utoronto.ca, sebastien.maniatopoulos@mail.utoronto.ca & ses@drsusansim.org"
__copyright__ = "2015 Aaron Campbell & Sebastien Dagenais-Maniatopoulos & Susan Sim"
__license__ = "MIT License"
def find(input_string, substring, start, end):
"""
Function to find a substring within a longer string.
:param input_string: phrase or string of letters
:param substring: string found within input_string
:param start: first index position of input_string
:param end: last index position of input_string
:return : index value of the first character of substring found in input_string
:raises :
"""
index = 0
input_string = input_string.lower() # correct for variations in case
substring = substring.lower()
for ch in range(start, end): # iterate through the string
if input_string[index:index + len(substring)] == substring: # compare slice from both strings
return index
index += 1
else:
return -1
# find()
def multi_find(input_string, substring, start, end):
"""
Function to find all of the instances of a substring within in a longer string.
Return a list of the index value for the first character of each found instance.
:param input_string: phrase or string of letters
:param substring: string found within input_string
:param start: first index position of input_string
:param end: last index position of input_string
:return: list of index values of first character of each instance of substring found in input_string,
returns empty string if no instances found
"""
index = 0
input_string = input_string.lower()
substring = substring.lower()
result = ""
while index < end:
for ch in range(start, end):
if input_string[index:index + len(substring)] == substring:
result += str(index) + "," # convert int
index += 1
result = result[0:-1] # return slice of all index points
return result
else:
return ""
# multi_find()
| true |
bb81d71014e5d45c46c1c34f10ee857f5763c75a | sicou2-Archive/pcc | /python_work/part1/ch03/c3_4.py | 1,813 | 4.125 | 4 | #Guest list
dinner_list = ['Sam Scott', 'Tyler Jame', 'Abadn Skrettn', 'Sbadut Reks']
def invites():
print(f'You want food {dinner_list[0]}? Come get food!')
print(f'Please honor me {dinner_list[1]}. Dine and talk!')
print(f'Hunger gnaws at you {dinner_list[2]}. Allow me to correct that.')
print(f'Poison is not for {dinner_list[3]}. You are safe eating here.')
invites()
list_len = len(dinner_list)
print(list_len)
print(f'\n{dinner_list[1]} will do me no honor. His name struck from the fun list\n\n')
del dinner_list[1]
dinner_list.append('Nahony Simpho')
invites()
print('\n\nThe council of Elders has seen fit to commission a more grand dining table. We have thus allowed for an expanded guest list.\n\n')
dinner_list.insert(0, 'Havlone of Maxuo')
dinner_list.insert(2, 'Barben Blorts')
dinner_list.append('Bill')
def expanded_invites():
print(f'We must talk {dinner_list[4]}. The food will be good.')
print(f'Be there of be dead {dinner_list[5]}. You will not starve.')
print(f'You have been asking forever. This one time {dinner_list[6]}, you may sit with us.')
invites()
expanded_invites()
list_len = len(dinner_list)
print(list_len)
print('\nWar! Trechery! The table has been destroyed by the vile Choob! Dinner for many has been lost to the sands of time. Our two closest advisors will be allowed council.\n')
list_len = len(dinner_list) - 2
for i in range(0, list_len):
dis_invited = dinner_list.pop()
print(f'Your dishonor shall be avenged {dis_invited}! Further preperations for correction are forthcoming!\n')
list_len = len(dinner_list)
print(list_len)
for i in range(0, list_len):
print(f'We urgently must consult, {dinner_list[0]}! We must correct our table tragedy!\n')
del dinner_list[0]
print(dinner_list)
# note(BCL): Working on 3-7
| true |
434f69b6fd36753ac13589061bec3cd3da51124a | Alex0Blackwell/recursive-tree-gen | /makeTree.py | 1,891 | 4.21875 | 4 | import turtle as t
import random
class Tree():
"""This is a class for generating recursive trees using turtle"""
def __init__(self):
"""The constructor for Tree class"""
self.leafColours = ["#91ff93", "#b3ffb4", "#d1ffb3", "#99ffb1", "#d5ffad"]
t.bgcolor("#abd4ff")
t.penup()
t.sety(-375)
t.pendown()
t.color("#5c3d00")
t.pensize(2)
t.left(90)
t.forward(100) # larger trunk
t.speed(0)
self.rootPos = t.position()
def __drawHelp(self, size, pos):
"""
The private helper method to draw the tree.
Parameters:
size (int): How large the tree is to be.
pos (int): The starting position of the root.
"""
if(size < 20):
if(size % 2 == 0):
# let's only dot about every second one
t.dot(50, random.choice(self.leafColours))
return
elif(size < 50):
t.dot(50, random.choice(self.leafColours))
# inorder traversial
t.penup()
t.setposition(pos)
t.pendown()
t.forward(size)
thisPos = t.position()
thisHeading = t.heading()
size = size - random.randint(10, 20)
t.setheading(thisHeading)
t.left(25)
self.__drawHelp(size, thisPos)
t.setheading(thisHeading)
t.right(25)
self.__drawHelp(size, thisPos)
def draw(self, size):
"""
The method to draw the tree.
Parameters:
size (int): How large the tree is to be.
"""
self.__drawHelp(size, self.rootPos)
def main():
tree = Tree()
tree.draw(125)
t.hideturtle()
input("Press enter to terminate program: ")
if __name__ == '__main__':
main()
| true |
002464d45f720f95b4af89bfa30875ae2ed46f70 | spencerhcheng/algorithms | /codefights/arrayMaximalAdjacentDifference.py | 714 | 4.15625 | 4 | #!/usr/bin/python3
"""
Given an array of integers, find the maximal absolute difference between any two of its adjacent elements.
Example
For inputArray = [2, 4, 1, 0], the output should be
arrayMaximalAdjacentDifference(inputArray) = 3.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer inputArray
Guaranteed constraints:
3 ≤ inputArray.length ≤ 10,
-15 ≤ inputArray[i] ≤ 15.
[output] integer
The maximal absolute difference.
"""
def maxDiff(arr):
max_diff = float('-inf')
for idx in range(1, len(arr)):
max_diff = max(max_diff, abs(arr[idx] - arr[idx - 1]))
return max_diff
if __name__ == "__main__":
arr = [2, 4, 1, 0]
print(maxDiff(arr))
| true |
ecaa063b18366d5248e01f5392fcb51e59612c1e | borisnorm/codeChallenge | /practiceSet/levelTreePrint.py | 591 | 4.125 | 4 | #Print a tree by levels
#One way to approach this is to bfs the tree
def tree_bfs(root):
queOne = [root]
queTwo = []
#i need some type of switching mechanism
while (queOne or queTwo):
print queOne
while(queOne):
item = queOne.pop()
if (item.left is not None):
queTwo.append(item.left)
if (item.right is not None):
queTwo.append(item.right)
print queTwo
while(queTwo):
item = queTwo.pop()
if (item.left is not None):
queOne.append(item.left)
if (item.right is not None):
queOne.append(item.right)
| true |
582d85050e08a6b8982aae505cdc0acc273aec74 | Kyle-Koivukangas/Python-Design-Patterns | /A.Creational Patterns/4.Prototype.py | 1,661 | 4.1875 | 4 | # A prototype pattern is meant to specify the kinds of objects to use a prototypical instance,
# and create new objects by copying this prototype.
# A prototype pattern is useful when the creation of an object is costly
# EG: when it requires data or processes that is from a network and you don't want to
# pay the cost of the setup each time, especially when you know the data won't change.
from copy import deepcopy
class Car:
def __init__(self):
self.__wheels = []
self.__engine = None
self.__body = None
def setBody(self, body):
self.___body = body
def attachWheel(self, wheel):
self.__wheels.append(wheel)
def setEngine(self, engine):
self.__engine = engine
def specification(self):
print(f"body: {self.__body.shape}")
print(f"engine horsepower: {self.__engine.horsepower}")
print(f"tire size: {self.__wheels[0].size}")
#it's pretty similar to the builder pattern, except you have a method that will easily allow you to copy the instance
# this stops you from having to
def clone(self):
return deepcopy(self)
# Here is another separate example
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
print(f"({self.x}, {self.y})")
def move(self, x, y):
self.x += x
self.y += y
def clone(self, move_x, move_y):
""" This clone method allows you to clone the object but it also allows you to clone it at a different point on the plane """
obj = deepcopy(self)
obj.move(move_x, move_y)
return obj
| true |
1d55b37fbef0c7975527cd50a4b65f2839fd873a | Kyle-Koivukangas/Python-Design-Patterns | /A.Creational Patterns/2.Abstract_Factory.py | 1,420 | 4.375 | 4 | # An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.
# it's basically just another level of abstraction on top of a normal factory
# === abstract shape classes ===
class Shape2DInterface:
def draw(self): pass
class Shape3DInterface:
def build(self): pass
# === concrete shape classes ===
class Circle(Shape2DInterface):
def draw(self):
print("Circle.draw")
class Square(Shape2DInterface):
def draw(self):
print("Square.draw")
class Sphere(Shape3DInterface):
def draw(self):
print("Sphere.build")
class Cube(Shape3DInterface):
def draw(self):
print("Cube.build")
# === Abstract shape factory ===
class ShapeFactoryInterface:
def getShape(self, sides): pass
# === Concrete shape factories ===
class Shape2DFactory(Shape2DInterface):
@staticmethod
def getShape(sides):
if sides == 1:
return Circle()
if sides == 4:
return Square()
assert 0, f"Bad 2D shape creation: shape not defined for {sides} sides"
class Shape3DFactory(Shape3DInterface):
@staticmethod
def getShape(sides):
"""technically, sides refers to faces"""
if sides == 1:
return Sphere()
if sides == 6:
return Cube()
assert 0, f"Bad 3D shape creation: shape not defined for {sides} sides"
| true |
1994561a1499d77769350b55a6f32cdd111f31fa | Ajat98/LC-2021 | /easy/buy_and_sell_stock.py | 1,330 | 4.21875 | 4 | """
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
minProfit = float('inf') #to represent largest possible val
#TOO SLOW on large arrays
# for i in range(len(prices)):
# for x in range(i, len(prices)):
# profit = prices[x] - prices[i]
# if profit > maxProfit:
# maxProfit = profit
#compare min buy price difference to max sell price at every step, keep tracking as you go.
for i in prices:
minProfit = min(i, minProfit)
profit = i - minProfit
maxProfit = max(profit, maxProfit)
return maxProfit
| true |
8e0e070279b4e917758152ea6f833a26bc56bad7 | chirag16/DeepLearningLibrary | /Activations.py | 1,541 | 4.21875 | 4 | from abc import ABC, abstractmethod
import numpy as np
"""
class: Activation
This is the base class for all activation functions.
It has 2 methods -
compute_output - this is used during forward propagation. Calculates A given Z
copute_grad - this is used during back propagation. Calculates dZ given dA and A
"""
class Activation(ABC):
@abstractmethod
def compute_output(self, Z):
pass
@abstractmethod
def compute_grad(self, A, dA):
pass
"""
class: Sigmoid
This activation is used in the last layer for networks performing binary classification.
"""
class Sigmoid(Activation):
def __init__(self):
pass
def compute_output(self, Z):
return 1. / (1 + np.exp(-Z))
def compute_grad(self, Y, A, dA):
return dA * A * (1 - A)
"""
class: Softmax
This activation is used in the last layer for networks performing multi-class classification.
"""
class Softmax(Activation):
def __init__(self):
pass
def compute_output(self, Z):
return np.exp(Z) / np.sum(np.exp(Z), axis=0)
def compute_grad(self, Y, A, dA):
return A - Y
"""
class ReLU
This activation is used in hidden layers.
"""
class ReLU(Activation):
def __init__(self):
pass
def compute_output(self, Z):
A = Z
A[Z < 0] = 0
return A
def compute_grad(self, Y, A, dA):
dZ = dA
dZ[A == 0] = 0
return dZ
| true |
9c5afd492bc5f9a4131d440ce48636ca03fa721c | viharika-22/Python-Practice | /Problem-Set-2/prob1.py | 332 | 4.34375 | 4 | '''1.) Write a Python program to add 'ing' at the end of a given
string (length should be at least 3). If the given string
already ends with 'ing' then add 'ly' instead.
If the string length of the given string is less than 3,
leave it unchanged.'''
n=input()
s=n[len(n)-3:len(n)]
if s=='ing':
print(n[:len(n)-3]+'ly')
| true |
bd512cbe3014297b8a39ab952c143ec153973495 | CarolinaPaulo/CodeWars | /Python/(8 kyu)_Generate_range_of_integers.py | 765 | 4.28125 | 4 | #Collect|
#Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max)
#Task
#Implement a function named
#generateRange(2, 10, 2) // should return iterator of [2,4,6,8,10]
#generateRange(1, 10, 3) // should return iterator of [1,4,7,10]
#Note
#min < max
#step > 0
#the range does not HAVE to include max (depending on the step)
def generate_range(min, max, step):
hey = []
contador = min
while contador < max:
hey.append(contador)
if step > max:
break
contador = contador + step
return hey
| true |
80643111235604455d6372e409fa248db684da97 | s56roy/python_codes | /python_prac/calculator.py | 1,136 | 4.125 | 4 | a = input('Enter the First Number:')
b = input('Enter the Second Number:')
# The entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.
sum = float(a)+float(b)
print(sum)
print('The sum of {0} and {1} is {2}'.format(a, b, sum))
print('This is output to the screen')
print ('this is output to the screen')
print ('The Sum of a & b is', sum)
print('The sum is %.1f' %(float(input('Enter again the first number: '))+float(input('Enter again the second number: '))))
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
# Output: I love butter and bread
print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
# Hello John, Goodmorning
x = 12.3456789
print('The value of x is %3.2f' %x)
# The value of x is 12.35
print('The value of x is %3.4f' %x)
# The value of x is 12.3457
import math
print(math.pi)
from math import pi
pi
| true |
9060d68c59660d4ee334ee824eda15cc49519de9 | ykcai/Python_ML | /homework/week5_homework_answers.py | 2,683 | 4.34375 | 4 | # Machine Learning Class Week 5 Homework Answers
# 1.
def count_primes(num):
'''
COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number
count_primes(100) --> 25
By convention, 0 and 1 are not prime.
'''
# Write your code here
# --------------------------------Code between the lines!--------------------------------
primes = [2]
x = 3
if num < 2: # for the case of num = 0 or 1
return 0
while x <= num:
for y in range(3, x, 2): # test all odd factors up to x-1
if x % y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
# ---------------------------------------------------------------------------------------
def count_primes2(num):
'''
COUNT PRIMES FASTER
'''
primes = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in primes: # use the primes list!
if x % y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
# Check
print(count_primes(100))
# 2.
def palindrome(s):
'''
Write a Python function that checks whether a passed in string is palindrome or not.
Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
'''
# Write your code here
# --------------------------------Code between the lines!--------------------------------
# This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces)
s = s.replace(' ', '')
return s == s[::-1] # Check through slicing
# ---------------------------------------------------------------------------------------
print(palindrome('helleh'))
print(palindrome('nurses run'))
print(palindrome('abcba'))
# 3.
def ran_check(num, low, high):
'''
Write a function that checks whether a number is in a given range (inclusive of high and low)
'''
# Write your code here
# --------------------------------Code between the lines!--------------------------------
# Check if num is between low and high (including low and high)
if num in range(low, high+1):
print('{} is in the range between {} and {}'.format(num, low, high))
else:
print('The number is outside the range.')
# ---------------------------------------------------------------------------------------
# Check
print(ran_check(5, 2, 7))
# 5 is in the range between 2 and 7 => True
| true |
e25a8fc38ef3e98e5dc34aae30fbbea316e709c2 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/3.py | 1,029 | 4.21875 | 4 | # 3. Budget Analysis
# Write a program that asks the user to enter the amount that he or she has budgeted for amonth.
# A loop should then prompt the user to enter each of his or her expenses for the month, and keep a running total.
# When the loop finishes, the program should display theamount that the user is over or under budget.
def main():
budget = float(input("Enter the amount you have budgeted this month: "))
total = 0
cont = "Y"
while cont == "Y" or cont == "y":
expense = float(input("Enter the expense amount you want tabulated from the budget: "))
cont = str(input("Enter y to continue or any other key to quit: "))
total += expense
if total < budget:
bottom_line = budget - total
print(f"You are {bottom_line:.2f} under budget.")
elif total > budget:
bottom_line = total - budget
print(f"You are {bottom_line:.2f} over budget.")
else:
print("Your expenses matched your budget.")
main() | true |
2b1cf90a6ed89d0f5162114a103397c0f2a211e8 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/iter.py | 612 | 4.25 | 4 | # Python iterators
# mylist = [1, 2, 3, 4]
# for item in mylist:
# print(item)
# def traverse(iterable):
# it = iter(iterable)
# while True:
# try:
# item = next(it)
# print(item)
# except: StopIteration:
# break
l1 = [1, 2, 3]
it = iter(l1)
# print next iteration in list
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# print(it.__next__())
# or you can use this
print(next(it))
print(next(it))
print(next(it))
# print(next(it))
# some objects are not itreable and will error
iter(100) | true |
b62ba48d92de96b49332b094f8b34a5f5af4a6cb | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/More advance things/map.py | 607 | 4.375 | 4 | # The map() function
# Takes in at least 2 args. Can apply a function to every item in a list/iterable quickly
def square(x):
return x*x
numbers = [1, 2, 3, 4, 5]
squarelist = map(square, numbers)
print(next(squarelist))
print(next(squarelist))
print(next(squarelist))
print(next(squarelist))
print(next(squarelist))
sqrlist2 = map(lambda x : x*x, numbers)
print(next(sqrlist2))
print(next(sqrlist2))
print(next(sqrlist2))
print(next(sqrlist2))
print(next(sqrlist2))
tens = [10, 20, 30, 40, 50]
indx = [1, 2, 3, 4, 5]
powers = list(map(pow, tens, indx[:3]))
print(powers)
| true |
8abfe167d6fa9e524df27f0adce9f777f4e2df58 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/5.py | 1,278 | 4.5625 | 5 | # 5. Average Rainfall
# Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years.
# The program should first ask for the number of years. The outer loop will iterate once for each year.
# The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month.
# After all iterations,the program should display the number ofmonths, the total inches of rainfall, and the average rainfall per month for the entire period.
monthdict = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
months = 0
years = int(input("Enter a number of years to enter rainfall data for: "))
total_rainfall = 0
for i in range(years):
for key in monthdict:
rainfall = float(input(f"Enter the rainfall for {monthdict.get(key):}: "))
total_rainfall += rainfall
months += 1
average = total_rainfall / months
print(f"The total rainfall per for {months:} months is", total_rainfall, "\n"
f"The average rainfall a month is {average:}"
) | true |
60f890e1dfb13d2bf8071374024ef673509c58b2 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 1.py | 1,870 | 4.59375 | 5 | """
1. Employee and ProductionWorker Classes
Write an Employee class that keeps data attributes for the following pieces of information:
• Employee name
• Employee number
Next, write a class named ProductionWorker that is a subclass of the Employee class. The
ProductionWorker class should keep data attributes for the following information:
• Shift number (an integer, such as 1, 2, or 3)
• Hourly pay rate
The workday is divided into two shifts: day and night. The shift attribute will hold an integer value representing the shift that the employee works. The day shift is shift 1 and the
night shift is shift 2. Write the appropriate accessor and mutator methods for each class.
Once you have written the classes, write a program that creates an object of the
ProductionWorker class and prompts the user to enter data for each of the object’s data
attributes. Store the data in the object and then use the object’s accessor methods to retrieve
it and display it on the screen.
"""
import worker
def main():
shift1 = employees()
shift2 = employees()
shift3 = employees()
displaystuff(shift1)
displaystuff(shift2)
displaystuff(shift3)
def employees():
name = input('Enter the employees name: ')
number = int(input('Enter the employee number: '))
shift = int(input('Enter the shift number for the employee, 1 - Days, 2 - Swings, 3 - Mids: '))
pay = float(input('Enter the hourly pay rate of the employee: '))
return worker.ProdWork(name, number, shift, pay)
def displaystuff(thingy):
print()
print('Name: ', thingy.get_name())
print('Employee Number: ', thingy.get_number())
print('Employees Shift: ', thingy.get_shift())
print(f'Employees hourly pay rate ${thingy.get_pay()}')
main() | true |
d5b0d5d155c1733eb1a9fa27a7dbf11902673537 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/FunctionExercise/4.py | 1,166 | 4.1875 | 4 | # 4. Automobile Costs
# Write a program that asks the user to enter the monthly costs for the following expenses incurred from operating his or her automobile:
# loan payment, insurance, gas, oil, tires, andmaintenance.
# The program should then display the total monthly cost of these expenses,and the total annual cost of these expenses
loan = 0.0
insurance = 0.0
gas = 0.0
oil = 0.0
tire = 0.0
mx = 0.0
def main():
global loan, insurance, gas, oil, tire, mx
print("Enter the monthly loan cost")
loan = getcost()
print("Enter the monthly insurance cost")
insurance = getcost()
print("Enter the monthly gas cost")
gas = getcost()
print("Enter the monthly oil cost")
oil = getcost()
print("Enter the monthly tire cost")
tire = getcost()
print("Enter the monthly maintenance cost")
mx = getcost()
total()
def getcost():
return float(input())
def total():
monthly_amount = loan+insurance+gas+oil+tire+mx
print("Your monthly costs are $", monthly_amount)
annual_amount = monthly_amount*12
print("Your annual cost is $", annual_amount)
main() | true |
e51cbe700da1b5305ce7dfe9c1748ad3b2369690 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/Dictionaries and Sets/Sets/notes.py | 2,742 | 4.59375 | 5 | # Sets
# A set contains a collection of unique values and works like a mathematical set
# 1 All the elements in a set must be unique. No two elements can have the same value
# 2 Sets are unordered, which means that the elements are not stored in any particular order
# 3 The elements that are stored in a set can be of different data types
# Creating a set
my_set = set(['a', 'b', 'c'])
print(my_set)
my_set2 = set('abc')
print(my_set2)
# will remove the duplicates for us
my_set3 = set('aabbcc')
print(my_set3)
# will error, set can only take one argument
# my_set4 = set('one', 'two', 'three')
# print(my_set4)
# Brackets help
my_set5 = set(['one', 'two', 'three'])
print(my_set5)
# find length
print(len(my_set5))
# add and remove elements of a set
# initialize a blank set
new_set = set()
new_set.add(1)
new_set.add(2)
new_set.add(3)
print("New set", new_set)
# Update works
new_set.update([4, 5, 6])
print("After update: ", new_set)
new_set2 = set([7, 8, 9])
new_set.update(new_set2)
print(new_set)
# cannot do 10 instead would use .discard discard will do nothing if it won't work as opposed to return an error
new_set.remove(1)
print(new_set)
# using a for loop to iterate over a set
new_set3 = set(['a', 'b', 'c'])
for val in new_set3:
print(val)
# using in and not operator to test the value of a set
numbers_set = set([1, 2, 4])
if 1 in numbers_set:
print('The value 1 is in the set. ')
if 99 not in numbers_set:
print('The value 99 is not in the set. ')
# Find the union of sets
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
set3 = set1.union(set2)
print('set3', set3)
# the same as above
set5 = set1 | set2
print('set5', set5)
# Find the intersection of sets
set4 = set1.intersection(set2)
print('set 4', set4)
# same as above
set6 = set1 & set2
print('set6', set6)
char_set = set(['abc'])
char_set_upper = set(['ABC'])
char_intersect = char_set.intersection(char_set_upper)
print('character intersect upper and lower', char_intersect)
char_union = char_set.union(char_set_upper)
print('character union upper lower', char_union)
# find the difference of sets
set7 = set1.difference(set2)
print('1 and 2 diff', set7)
print('set 1', set1)
print('set 2', set2)
set8 = set2.difference(set1)
print('set 8', set8)
set9 = set1 - set2
print('set9', set9)
# finding symmetric difference in sets
set10 = set1.symmetric_difference(set2)
print('set10', set10)
set11 = set1 ^ set2
print('set11', set11)
# find the subsets and supersets
set12 = set([1,2,3,4])
set13 = set([1,2])
print(' is 13 a subset of 12', set13.issubset(set12))
print('is 12 a superset of 13', set12.issuperset(set13))
| true |
d2e06b65113045bf009e371c53cc73750f8184a7 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Recursion/Practice/7.py | 1,181 | 4.21875 | 4 | """
7. Recursive Power Method
Design a function that uses recursion to raise a number to a power. The function should
accept two arguments: the number to be raised and the exponent. Assume that the exponent is a
nonnegative integer.
"""
# define main
def main():
# Establish vars
int1 = int(input("Enter the first integer: "))
int2 = int(input("Enter the second integer: "))
# pass to function
exp(int1, int2, 1)
# define exponent
# def exp(x, y, z, a):
# if z is greater than the exponent then print the formatted number
# if z > y:
# print(f'{a:,.2f}')
# # If not cal lthe function again passing z, y and z plus 1 and the total times the base number
# else:
# return exp(x, y, z + 1, a * x)
# A better way less lines, simpler
def exp(x, y, a):
# While y is greater than 0 call the function again passing x, y - 1 and a (the total) times the base number
while y > 0: return exp(x, y - 1, a * x)
print(f'{a:,.2f}')
# call main
main()
# 7.
# def power(x,y):
# if y == 0:
# return 1
# else:
# return x * power(x, y - 1)
# print(power(3,3)) | true |
f149ee1bf7a78720f53a8688d83d226cb00dc5eb | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/Cars.py | 2,383 | 4.8125 | 5 | """
2. Car Class
Write a class named Car that has the following data attributes:
• __year_model (for the car’s year model)
• __make (for the make of the car)
• __speed (for the car’s current speed)
The Car class should have an __init__ method that accept the car’s year model and make
as arguments. These values should be assigned to the object’s __year_model and __make
data attributes. It should also assign 0 to the __speed data attribute.
The class should also have the following methods:
• accelerate
The accelerate method should add 5 to the speed data attribute each time it is
called.
• brake
The brake method should subtract 5 from the speed data attribute each time it is called.
• get_speed
The get_speed method should return the current speed.
Next, design a program that creates a Car object, and then calls the accelerate method
five times. After each call to the accelerate method, get the current speed of the car and
display it. Then call the brake method five times. After each call to the brake method, get
the current speed of the car and display it.
"""
# define the class of cars
class Cars:
# define the init with all the variables
def __init__(self, year, make, model, speed):
self.__year = year
self.__make = make
self.__model = model
self.__speed = speed
# def setting the year of the car
def set_year(self, year):
self.__year = year
# def function to set the make of the car
def set_make(self, make):
self.__make = make
# def function to set the model of the car
def set_model(self, model):
self.__model = model
# def function to accelerate
def accelerate(self):
self.__speed += 5
return self.__speed
# def function to begin braking
def brake(self):
self.__speed -= 5
return self.__speed
# define a function to get the speed
def get_speed(self):
return self.__speed
# return the year
def get_year(self):
return self.__year
# returns the make
def get_make(self):
return self.__make
# return the model
def get_model(self):
return self.__model
| true |
eaa53c820d135506b1252749ab50b320d11d53b5 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/5 - RetailItem.py | 1,427 | 4.625 | 5 | """
5. RetailItem Class
Write a class named RetailItem that holds data about an item in a retail store. The class
should store the following data in attributes: item description, units in inventory, and price.
Once you have written the class, write a program that creates three RetailItem objects
and stores the following data in them:
Description Units in Inventory Price
Item #1 Jacket 12 59.95
Item #2 Designer Jeans 40 34.95
Item #3 Shirt 20 24.95
"""
# import the important things
import RetailItem
# establish the dictionary with the data
item_dict = {1 : { 'description' : 'Jacket', 'units' : 12, 'price' : 59.95},
2 : { 'description' : 'Designer Jeans', 'units' : 40, 'price' : 34.95},
3 : { 'description' : 'Shirt', 'units' : 20, 'price' : 24.95}}
# define the main function
def main():
# set the variable to call the class and use dictionary info to populate it
item1 = RetailItem.RetailItem(item_dict[1]['description'], item_dict[1]['units'], item_dict[1]['price'])
item2 = RetailItem.RetailItem(item_dict[2]['description'], item_dict[2]['units'], item_dict[2]['price'])
item3 = RetailItem.RetailItem(item_dict[3]['description'], item_dict[3]['units'], item_dict[3]['price'])
# display the data
print(item1, item2, item3)
# call main
main() | true |
b046b95c144bbe51ac2c77b5363814b8b5d2b5cc | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/LoopsPractice/6.py | 503 | 4.46875 | 4 | # 6. Celsius to Fahrenheit Table
# Write a program that displays a table of the Celsius temperatures 0 through 20 and theirFahrenheit equivalents.
# The formula for converting a temperature from Celsius toFahrenheit is
# F = (9/5)C + 32 where F is the Fahrenheit temperature and C is the Celsius temperature.
# Your programmust use a loop to display the table.
fahr = [((9/5) * cel + 32) for cel in range(21)]
for x, y in enumerate(fahr):
print(f'{x:} celcius is {y:.2f} fahrenheit.')
| true |
9e6bdd3adc3e850240f3c9a94dd766ecdd4abe97 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/FileExercises/9.py | 1,013 | 4.28125 | 4 | # 9. Exception Handing
# Modify the program that you wrote for Exercise 6 so it handles the following exceptions:
# • It should handle any IOError exceptions that are raised when the file is opened and datais read from it.
# Define counter
count = 0
# Define total
total = 0
try:
# Display first 5 lines
# Open the file
infile = open("numbers.txt", 'r')
# Set readline
line = infile.readline()
while line != '':
# Convert line to a float
display = int(line)
# Increment count and total
count += 1
total += display
# Format and display data
print(display)
# Read the next line
line = infile.readline()
print(f"\n The average of the lines is {total/count:.2f}")
# If file doesn't exist, show this error message
except:
print(f"\n An error occured trying to read numbers.txt")
if count > 0:
print(f" to include line {count:} \n") | true |
2118efbe7e15e295f6ceea7b4a4c26696b22edb1 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Hard Stuff/Unit Testing and Multithreading/MultiThreading/Multithreadingclassdemo1/multithreading.py | 1,434 | 4.15625 | 4 | '''
RUnning things concurrently is known as multithreading
Running things in parallel is known as multiprocessing
I/O bound tasks - Waiting for input and output to be completed
reading and writing from file system, network
operations.
These all benefit more from threading
You get the illusion of running code at the same time,
however other code starts running while other code is waiting
CPU bound tasks - Good for number crunching
Using CPU
Data Crunching
These benefit more from multiprocessing and running in parallel
Using multiprocessing might be slower if you have overhead from creating
and destroying files.
'''
import threading
import time
start = time.perf_counter()
def do_something():
print('Sleeping 1 second....')
time.sleep(1)
print('Done Sleeping....')
# how we did it
# do_something()
# do_something()
# create threads for new way
t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)
#start the thread
t1.start()
t2.start()
# make sure the threads complete before moving on to calculate finish time:
t1.join()
t2.join()
finished = time.perf_counter()
print(f'Our program finished in {finished - start:.6f} seconds.') | true |
f1923bf1fc1a3ab94a7f5d32c929cd6914fc7605 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Test Stuff/First Test/shapes1.py | 2,305 | 4.25 | 4 | class GeometricObject:
def __init__(self, color = "green", filled = True):
self.color = color
self.filled = filled
def getColor(self):
return self.color
def setColor(self, color):
self.color = color
def isFilled(self):
return self.filled
def setFilled(self, filled):
self.filled = filled
def toString(self):
return "color: " + self.color + " and filled: " + str(self.filled)
'''
(The Triangle class) Design a class named Triangle that extends the
GeometricObject class defined below. The Triangle class contains:
- Three float data fields named side1, side2, and side3 to denote the three
sides of the triangle.
- A constructor that creates a triangle with the specified side1, side2, and
side3 with default values 1.0.
- The accessor methods for all three data fields.
- A method named getArea() that returns the area of this triangle.
- A method named getPerimeter() that returns the perimeter of this triangle.
- A method named __str__() that returns a string description for the triangle.
'''
class TriangleObject:
def __init__(self, color = "green", filled = True, side1 = 1.0, side2 = 1.0, side3 = 1.0):
super().__init__(color, filled)
self.side1 = side1
self.side2 = side2
self.side3 = side3
def set_side1(self, side1):
self.side1 = side1
def set_side2(self, side2):
self.side2 = side2
def set_side3(self, side3):
self.side3 = side3
def get_side1(self, side1):
return self.side1
def get_side2(self, side2):
return self.side2
def get_side3(self, side3):
return self.side3
def getPerimeter(self):
self.perimeter = (self.side1 + self.side2 + self.side3)/2
return self.perimeter
def getArea(self):
self.area = (self.perimeter * (self.perimeter - self.side1) * (self.perimeter - self.side2) * (self.perimeter - self.side3)) ** (1/2.0)
return self.area
def __str__(self):
return f'A triangle is a 3 sided shape. The current sides have a length of {self.side1}, {self.side2}, and {self.side3}'
| true |
cd2b8237503c74dfc7864dd4ec64d7f334c9ecb0 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Practice/8 - trivia.py | 2,521 | 4.4375 | 4 | """
8. Trivia Game
In this programming exercise you will create a simple trivia game for two players. The program will
work like this:
• Starting with player 1, each player gets a turn at answering 5 trivia questions. (There
should be a total of 10 questions.) When a question is displayed, 4 possible answers are
also displayed. Only one of the answers is correct, and if the player selects the correct
answer, he or she earns a point.
• After answers have been selected for all the questions, the program displays the number
of points earned by each player and declares the player with the highest number of points
the winner.
To create this program, write a Question class to hold the data for a trivia question. The
Question class should have attributes for the following data:
• A trivia question
• Possible answer 1
• Possible answer 2
• Possible answer 3
• Possible answer 4
• The number of the correct answer (1, 2, 3, or 4)
The Question class also should have an appropriate __init__ method, accessors, and
mutators.
The program should have a list or a dictionary containing 10 Question objects, one for
each trivia question. Make up your own trivia questions on the subject or subjects of your
choice for the objects.
"""
question_dict = {"Blue, Black or Red?" : ['Blue', 'Red', 'Clear', 'Black'],
"Yes or No?" : ['Yes', 'Maybe', 'True', 'No'],
"Laptop or Desktop?" : ['Cell Phone', 'Tablet', 'Laptop', 'Desktop']}
import trivia
import random
def main():
global question_dict
questions = trivia.Trivia()
questions.bulk_add(question_dict)
for key in questions.get_questions():
print(key)
# print(questions.get_questions()[key])
answerlist = []
answerlist2 = []
for i in questions.get_questions()[key]:
answerlist.append(i)
answerlist2.append(i)
random.shuffle(answerlist2)
print("1", answerlist)
print("2", answerlist2)
count = 0
for i in answerlist2:
print(f"Number {count}: {i}")
count += 1
choice = int(input("Enter the number choice for your answer: "))
if answerlist[3] == answerlist2[choice]:
print("You got it right!")
else:
print("You got it wrong!")
main() | true |
8b72f14467bc40821bc0fb0c7c2ad9f05be58cd0 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/Inheritance/Practice/Inheritance Exercises - 3.py | 2,460 | 4.46875 | 4 | """
3. Person and Customer Classes
Write a class named Person with data attributes for a person’s name, address, and
telephone number. Next, write a class named Customer that is a subclass of the
Person class. The Customer class should have a data attribute for a customer
number and a Boolean data attribute indicating whether the customer wishes to be
on a mailing list. Demonstrate an instance of the Customer class in a simple
program.
"""
import assets
import pprint
pppl_lst = []
cust_lst = []
def main():
global pppl_lst, cust_lst
pppl_num = int(input('Enter the number of people you need to add: '))
setthelist(pppl_num)
print("Not Customers: ")
print_list(pppl_lst)
print("Customers: ")
print_list(cust_lst)
def setthelist(theamount):
global pppl_lst, cust_lst
for i in range(theamount):
print("Person", i+1)
customerinput = int(input('Is this person a customer? 1 for yes 0 for no: '))
if customerinput == 1:
name = input('Enter the persons name: ')
address = input('Enter the address: ')
phone = input('Enter the phone number for the person: ')
cust_num = int(input('Enter the customer number: '))
mail = 2
while mail != 0 and mail != 1:
mail = int(input('Does the customer want to be on the mailing list? 1 = yes 0 = no: '))
print('mail', mail)
customer = assets.Customer(name, address, phone, cust_num, bool(mail))
cust_lst.append(customer)
elif customerinput == 0:
name = input('Enter the persons name: ')
address = input('Enter the address: ')
phone = input('Enter the phone number for the person: ')
notcustomer = assets.Person(name, address, phone)
pppl_lst.append(notcustomer)
def print_list(listss):
if listss is pppl_lst:
for i in listss:
print('Name: ', i.get_name())
print('Address: ', i.get_address())
print('Phone: ', i.get_phone())
elif listss is cust_lst:
for i in listss:
print('Name: ', i.get_name())
print('Address: ', i.get_address())
print('Phone: ', i.get_phone())
print('Customer Number: ', i.get_cust_num())
print('Is on mailing address: ', i.get_mail())
main()
| true |
ab93e5065c94a86f8ed6c812a3292100925a1bb5 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Basic Stuff/IfElsePractice/5.py | 1,575 | 4.4375 | 4 | # 5. Color Mixer
# The colors red, blue, and yellow are known as the primary colors because they cannot be
# made by mixing other colors. When you mix two primary colors, you get a secondary color,
# as shown here:
# When you mix red and blue, you get purple.
# When you mix red and yellow, you get orange.
# When you mix blue and yellow, you get green.
# Design a program that prompts the user to enter the names of two primary colors to mix.
# If the user enters anything other than “red,” “blue,” or “yellow,” the program should display an
# error message. Otherwise, the program should display the name of the secondary color that results.
def main():
color_one = color()
checker(color_one)
color_two = color()
checker(color_two)
blender(color_one, color_two)
def checker(color):
if color == "red" or color == "blue" or color == "yellow":
print("You chose", color)
else:
print("Choose one of the primary colors!")
exit()
def color():
return input("Enter 'red', 'blue', or 'yellow'. ")
def blender(first, second):
if (first == "red" or second == "red") and (first == "blue" or second == "blue"):
print("Your blend is purple")
elif (first == "yellow" or second == "yellow") and (first == "blue" or second == "blue"):
print("Your blend is green")
elif (first == "red" or second == "red") and (first == "yellow" or second == "yellow"):
print("Your blend is orange")
else:
print("Your colors were the same")
main() | true |
d63f59488d65ba81d647da41c15424a0901d18b4 | DimitrisMaskalidis/Python-2.7-Project-Temperature-Research | /Project #004 Temperature Research.py | 1,071 | 4.15625 | 4 | av=0; max=0; cold=0; count=0; pl=0; pres=0
city=raw_input("Write city name: ")
while city!="END":
count+=1
temper=input("Write the temperature of the day: ")
maxTemp=temper
minTemp=temper
for i in range(29):
av+=temper
if temper<5:
pl+=1
if temper>maxTemp:
maxTemp=temper
if temper<minTemp:
minTemp=temper
temper=input("Write the temperature of the day: ")
print "The differance between highest and lowest temperature is",maxTemp-minTemp
av=av/30.0
if count==1:
max=av
if av>max:
max=av
maxname=city
if av>30:
pres+=1
if pl==30:
cold+=1
pl=0
city=raw_input("Write city name: ")
print "The percentage of the cities with average temperature more than 30 is",count/pres*100,"%"
print "The city with the highest average temperature is",maxname,"with",max,"average temperature"
if cold>0:
print "There is a city with temperature below 5 every day"
| true |
431e4b3687f6e41381331f315f13108fc029d396 | wangyunge/algorithmpractice | /eet/Check_Completeness_of_a_Binary_Tree.py | 1,354 | 4.21875 | 4 | """
Given the root of a binary tree, determine if it is a complete binary tree.
In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:
Input: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.max_val = 0
self.sum = 0
def _dfs(node, value):
if node:
self.max_val = max(self.max_val, value)
self.sum += value
_dfs(node.left, 2 * value)
_dfs(node.right, 2 * value + 1)
_dfs(root, 1)
return self.sum == self.max_val/2 * (1+self.max_val)
| true |
597bdffceea740761f6280470d81b9deaf73f400 | wangyunge/algorithmpractice | /int/517_Ugly_Number.py | 926 | 4.125 | 4 | '''
Write a program to check whether a given number is an ugly number`.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Notice
Note that 1 is typically treated as an ugly number.
Have you met this question in a real interview? Yes
Example
Given num = 8 return true
Given num = 14 return false
'''
class Solution:
# @param {int} num an integer
# @return {boolean} true if num is an ugly number or false
def isUgly(self, num):
if num < 1:
return False
while True:
if num % 2 == 0:
num = num/2
elif num % 3 == 0:
num = num/3
elif num % 5 == 0:
num = num/5
else:
break
if num != 1:
return False
else:
return True
| true |
2e3a39178816c77f9f212cb1629a8f17950da152 | wangyunge/algorithmpractice | /int/171_Anagrams.py | 692 | 4.34375 | 4 | '''
Given an array of strings, return all groups of strings that are anagrams.
Notice
All inputs will be in lower-case
Have you met this question in a real interview? Yes
Example
Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].
Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].
'''
class Solution:
# @param strs: A list of strings
# @return: A list of strings
def anagrams(self, strs):
table = {}
res = []
for word in strs:
setOfWord = set(word)
if setOfWord not in table:
table[setOfWord] = word
else:
res.append(word)
return res
| true |
e3ee7499abf955e0662927b7341e93fa81843620 | wangyunge/algorithmpractice | /eet/Arithmetic_Slices.py | 960 | 4.15625 | 4 | """
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
Example 2:
Input: nums = [1]
Output: 0
"""
class Solution(object):
def numberOfArithmeticSlices(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
diff = [nums[i] - num[i-1] for i in range(1, len(nums))]
consecutive = [0] * len(nums)
for i in range(2, len(nums)):
consecutive[i] = 2 * consecutive[i-1] - consecutive[i-2] + 1
for i in range(diff):
| true |
3859966faca648ffe0b7e83166049c07676ba93b | wangyunge/algorithmpractice | /eet/Maximum_Units_on_a_Truck.py | 2,304 | 4.125 | 4 | """
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:
numberOfBoxesi is the number of boxes of type i.
numberOfUnitsPerBoxi is the number of units in each box of the type i.
You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.
Return the maximum total number of units that can be put on the truck.
Example 1:
Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
Explanation: There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.
Example 2:
Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91
"""
class Solution(object):
def maximumUnits(self, boxTypes, truckSize):
"""
:type boxTypes: List[List[int]]
:type truckSize: int
:rtype: int
"""
if truckSize < 0:
return 0
last_dp = [0 for _ in range(truckSize+1)]
dp = [0 for _ in range(truckSize+1)]
for i in range(len(boxTypes)):
for j in range(1, truckSize+1):
for num in range(1, boxTypes[i][0]+1):
spare_track = j - num
if spare_track >= 0:
dp[j] = max(dp[j],last_dp[spare_track]+num*boxTypes[i][1])
last_dp = dp[:]
return dp[-1]
"""
Notes:
last dp and dp, need two states.
"""
class Solution(object):
def maximumUnits(self, boxTypes, truckSize):
"""
:type boxTypes: List[List[int]]
:type truckSize: int
:rtype: int
"""
order_box = sorted(boxTypes, key=lambda x: x[1])
space = 0
res = 0
for box_num, box_unit in order_box:
for num in range(1, box_num+1):
if 1 + space <= truckSize:
space += 1
res += box_unit
return res
| true |
d620071842e6003015b2a9f34c72b85a64e00a04 | wangyunge/algorithmpractice | /eet/Multiply_Strings.py | 1,183 | 4.125 | 4 | """
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
1 <= num1.length, num2.length <= 200
num1 and num2 consist of digits only.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
"""
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
l1 = len(num1)
l2 = len(num2)
res = [0] * (l1 + l2 +1)
for i in range(l1)[::-1]:
for j in range(l2)[::-1]:
pdc = int(num1[i]) * int(num2[j])
plus = res[i+j] + pdc
res[i+j] += pdc % 10
res[i+j+1] = pdc / 10
res = map(res, lambda x: str(x))
if res[0] == '0':
return ''.join(res[1:])
else:
return ''.join(res)
| true |
bdfc9caa3090f7727fd227548a83aaf19bf66c14 | wangyunge/algorithmpractice | /eet/Unique_Binary_Search_Tree_II.py | 1,269 | 4.25 | 4 | '''
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Subscribe to see which companies asked this question
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def generateByList(self,list):
root = TreeNode(list[0])
for i in xrange(1,len(list)):
self.BSTappend(root,list[i])
return root
def BSTappend(self,root,num):
parent = root
while root:
parent = root
if root.val < num:
root = root.right
else:
root = root.left
if parent.val < num:
parent.right = TreeNode(num)
else:
parent.left = TreeNode(num)
| true |
9eba4c97143250a68995688a62b41145ab39485f | wangyunge/algorithmpractice | /int/165_Merge_Two_Sorted_Lists.py | 944 | 4.125 | 4 | '''
Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
Have you met this question in a real interview? Yes
Example
Given 1->3->8->11->15->null, 2->null , return 1->2->3->8->11->15->null.
'''
z"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param two ListNodes
@return a ListNode
"""
def mergeTwoLists(self, l1, l2):
helper = ListNode(0,None)
index = helper
while l1 and l2:
if l1.val <= l2.val:
index.next = l1
l1 = l1.next
else:
index.next = l2
l2 = l2.next
index = index.next
index.next = l1 if l1 else l2
return helper.next | true |
ba2b9d296a98edfb414c89aba262142b031014ea | tasver/python_course | /lab7_4.py | 782 | 4.375 | 4 |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
def input_str() -> str:
""" This function make input of string data"""
input_string = str(input('Enter your string: '))
return input_string
def string_crypt(string: str) -> str:
""" This function make crypt string"""
result_string = str()
string = string.lower()
for symb in string:
result_string += chr(ord(symb) + 1)
return result_string
def string_check_crypt(check_str:str) -> str:
""" this funtion checking out of range crypt """
check_str = check_str.replace("{","a")
check_str = check_str.replace("ѐ","а")
print(check_str)
return check_str
def output_str(string:str) -> str:
""" This function print result"""
print(string)
output_str(string_check_crypt(string_crypt(input_str())))
| true |
e18e81c8986c383ac6d6cec86017d3bf948af5b3 | tasver/python_course | /lab6_1.py | 719 | 4.21875 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
import math
def input_par() -> list:
""" This function make input of data"""
a, b, c = map(float, input('Enter 3 numbers: ').split())
return [a, b, c]
def check_triangle(a:list) -> bool:
""" This function check exists triangle"""
if (((a[0] + a[1]) > a[2]) and ((a[0] + a[2]) > a[1]) and ((a[2] + a[1] > a[0]))):
return True
else:
return False
def calculate(a:list) -> float:
""" This function calculate area triangle """
if check_triangle(a):
half_perimetr = (a[0]+a[1]+a[2])/2
area = math.sqrt(half_perimetr*(half_perimetr-a[0])*(half_perimetr-a[1])*(half_perimetr-a[2]))
return area
else: return 'Triangle not exists'
print(calculate(input_par()))
| true |
3a5ee700dce71d3f72eb95a8d7b5900e309270ec | ahmetYilmaz88/Introduction-to-Computer-Science-with-Python | /ahmet_yilmaz_hw6_python4_5.py | 731 | 4.125 | 4 | ## My name: Ahmet Yilmaz
##Course number and course section: IS 115 - 1001 - 1003
##Date of completion: 2 hours
##The question is about converting the pseudocode given by instructor to the Python code.
##set the required values
count=1
activity= "RESTING"
flag="false"
##how many activities
numact= int(input(" Enter the number of activities: "))
##enter the activities as number as numact that the user enter
while count < numact:
flag= " true "
activity= input( "Enter your activity: ")
##display the activity
if activity=="RESTING":
print ( " I enjoy RESTING too ")
else:
print ("You enjoy " , activity)
count=count+1
if flag== "false":
print (" There is no data to process ")
| true |
8d07696850cc5f7371069a98351c51266b77da6b | lintangsucirochmana03/bigdata | /minggu-02/praktik/src/DefiningFunction.py | 913 | 4.3125 | 4 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
>>> print()
>>> # Now call the function we just defined:
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>> fib
<function fib at 0x02C4CE88>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
>>> fib(0)
>>> print(fib(0))
None
>>> def fib2(n): # return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below
a, b = b, a+b
return result
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>
| true |
652990fdc99924c1810dddc60be12a8d81709a6e | ashwani8958/Python | /PyQT and SQLite/M3 - Basics of Programming in Python/program/module/friends.py | 379 | 4.125 | 4 | def food(f, num):
"""Takes total and no. of people as argument"""
tip = 0.1*f #calculates tip
f = f + tip #add tip to total
return f/num #return the per person value
def movie(m, num):
"""Take total and no. of the people as arguments"""
return m/num #returns the per persons value
print("The name attribute is: ", __name__)#check for the name attribute
| true |
95e0619eeb977cefe6214f8c50017397ec35af3b | SURBHI17/python_daily | /prog fund/src/assignment40.py | 383 | 4.25 | 4 | #PF-Assgn-40
def is_palindrome(word):
word=word.upper()
if len(word)<=1:
return True
else:
if word[0]==word[-1]:
return is_palindrome(word[1:-1])
else:
return False
result=is_palindrome("MadAMa")
if(result):
print("The given word is a Palindrome")
else:
print("The given word is not a Palindrome") | true |
114dd9807e3e7a111c6e1f97e331a7a98e6e074a | KanuckEO/Number-guessing-game-in-Python | /main.py | 1,491 | 4.28125 | 4 | #number_guessing_game
#Kanuck Shah
#importing libraries
import random
from time import sleep
#asking the highest and lowest index they can guess
low = int(input("Enter lowest number to guess - "))
high = int(input("Enter highest number to guess - "))
#array
first = ["first", "second", "third", "fourth", "fifth"]
#variables
second = 0
#tries counter
tries = 1
#array for highest and lowest index that they can guess
numbers = [low, high]
#choosing random number between array above
number = random.randint(low, high)
#printting for style
print("\n")
print("************************************")
print("Welcome to the number guessing game.")
print("************************************")
print("\n")
print("You will have to choose a number between", low ,"and", high ,"in eight tries")
#delay
sleep(1)
print(".")
sleep(1)
print(".")
sleep(1)
print(".")
sleep(1)
print("\n")
while tries < 8:
tries += 1
print("choose your", first[second] ,"number ", end="")
ans1 = int(input(""))
second += 1
print("You have tried to guess", tries, "times.")
if int(number) > ans1:
print("\n")
print("Too low go higher")
elif int(number) < ans1:
print("\n")
print("Too high go lower")
elif int(number) == ans1:
print("\n")
print("Ding Ding Ding")
print("You are right")
print("The number was", number)
break
if tries >= 8:
print("\n")
print("The number was", number)
print("Too many tries session ended")
print("Better luck next time :(") | true |
9bab6ff99aa72e668524b63523c2106181049f6f | IamBiasky/pythonProject1 | /SelfPractice/function_exponent.py | 316 | 4.34375 | 4 | # Write a function called exponent(base, exp)
# that returns an int value of base raises to the power of exp
def exponent(base, exp):
exp_int = base ** exp
return exp_int
base = int(input("Please enter a base integer: "))
exp = int(input("Please enter an exponent integer: "))
print(exponent(base, exp))
| true |
2d4cf0b46c47fad8a5cc20cdf98ebf9ab379a151 | sooryaprakash31/ProgrammingBasics | /OOPS/Exception_Handling/exception_handling.py | 1,347 | 4.125 | 4 | '''
Exception Handling:
- This helps to avoid the program crash due to a segment of code in the program
- Exception handling allows to manage the segments of program which may lead to errors in runtime
and avoiding the program crash by handling the errors in runtime.
try - represents a block of code that can throw an exception.
except - represents a block of code that is executed when a particular exception is thrown.
else - represents a block of code that is executed when there is no exception
finally - represents a block of code that is always executed irrespective of exceptions
raise - The raise statement allows the programmer to force a specific exception to occur.
'''
dividend = float(input("Enter dividend "))
divisor = float(input("Enter divisor "))
#runs the code segment which may lead to error
try:
result = dividend/divisor
#executed when there is an exception
except ZeroDivisionError:
print("Divisor is Zero")
#executed when there is no exception
else:
print(format(result,'.2f'))
#always executed
finally:
print("End of Program")
'''
try:
if divisor == 0:
raise ZeroDivisionError()
except ZeroDivisionError:
print("Divisor is zero")
else:
result = dividend/divisor
print(format(result, '.2f'))
finally:
print("End of Program")
''' | true |
79dda99fe42354f17d03eb33a1aab1ee9ebe61ab | sooryaprakash31/ProgrammingBasics | /Algorithms/Sorting/Quick/quick.py | 2,027 | 4.25 | 4 | '''
Quick Sort:
- Picks a pivot element (can be the first/last/random element) from the array
and places it in the sorted position such that the elements before the pivot
are lesser and elements after pivot are greater.
- Repeats this until all the elements are placed in the right position
- Divide and conquer strategy
Example:
arr=[3,6,4,5,9]
Takes pivot as arr[2] (i.e (first_index+last_index)/2)
pivot is 4.
After 1st partition
arr=[3,4,6,5,9]
i) The elements before pivot are lesser then pivot and
the elements after pivot are greater than pivot
- quick_sort method calls itself for left and right blocks having
partition as the midpoint until all the elements are sorted.
'''
def partition(arr, left,right,pivot):
#left should always less than or equal to right
#otherwise it will lead to out of bounds error
while left<=right:
#finds the first element that is greater than pivot
#from the start
while arr[left]<pivot:
left=left+1
#finds the first element that is lesser than pivot
#from the end
while arr[right]>pivot:
right=right-1
#swapping the elements at indices left and right
if left<=right:
arr[left],arr[right]=arr[right],arr[left]
left=left+1
right=right-1
#returning the current index of the pivot element
return left
def quick_sort(arr,left,right):
#checks if the block contains atleast two elements
if left<right:
#Middle element is chosen as the pivot
pivot=arr[(left+right)//2]
#gives the sorted pivot index
p = partition(arr,left,right,pivot)
#calls quick_sort for elements left to the partition
quick_sort(arr,left,p-1)
#calls quick_sort for elements right to the partition
quick_sort(arr,p,right)
arr=list(map(int,input("Enter array ").split()))
print("Before sort:",*arr)
#calling sort function
quick_sort(arr,0,len(arr)-1)
print("Sorted array:",*arr) | true |
4bdde3d9684f505ae85c0446465aa211a012a02d | luizfirmino/python-labs | /Python I/Assigments/Module 5/Ex-2.py | 415 | 4.3125 | 4 | #
# Luiz Filho
# 3/14/2021
# Module 5 Assignment
# 2. In mathematics, the factorial of a number n is defined as n! = 1 ⋅ 2 ⋅ ... ⋅ n (as the product of all integer numbers from 1 to n).
# For example, 4! = 1 ⋅ 2 ⋅ 3 ⋅ 4 = 24. Write a recursive function for calculating n!
def calculateN(num):
if num == 1:
return num
else:
return num * calculateN(num-1)
print(calculateN(4))
| true |
7372b7c995d2302f29b8443656b50cae298a566b | luizfirmino/python-labs | /Python I/Assigments/Module 6/Ex-4.py | 742 | 4.40625 | 4 | #
# Luiz Filho
# 3/23/2021
# Module 6 Assignment
# 4. Write a Python function to create the HTML string with tags around the word(s). Sample function and result are shown below:
#
#add_html_tags('h1', 'My First Page')
#<h1>My First Page</h1>
#
#add_html_tags('p', 'This is my first page.')
#<p>This is my first page.</p>
#
#add_html_tags('h2', 'A secondary header.')
#<h2>A secondary header.</h2>
#
#add_html_tags('p', 'Some more text.')
#<p>Some more text.</p>
def add_html_tags(tag, value):
return "<" + tag + ">" + value + "</" + tag + ">"
print(add_html_tags('h1', 'My First Page'))
print(add_html_tags('p', 'This is my first page.'))
print(add_html_tags('h2', 'A secondary header.'))
print(add_html_tags('p', 'Some more text.'))
| true |
c13619368c38c41c0dbf8649a3ca88d7f2788ee8 | luizfirmino/python-labs | /Python Networking/Assignment 2/Assignment2.py | 564 | 4.21875 | 4 | #!/usr/bin/env python3
# Assignment: 2 - Lists
# Author: Luiz Firmino
list = [1,2,4,'p','Hello'] #create a list
print(list) #print a list
list.append(999) #add to end of list
print(list)
print(list[-1]) #print the last element
list.pop() #remove last element
print(list)
print(list[0]) #print first element
list.remove(1) #remove element
print(list)
del list[3] #remove an element by index
print(list)
list.insert(0,'Baby') #insert an element at index
print(list) | true |
51d1e3a48b954c1de3362ea295d4270a884fea98 | luizfirmino/python-labs | /Python I/Assigments/Module 7/Ex-3.py | 1,042 | 4.3125 | 4 | #
# Luiz Filho
# 4/7/2021
# Module 7 Assignment
# 3. Gases consist of atoms or molecules that move at different speeds in random directions.
# The root mean square velocity (RMS velocity) is a way to find a single velocity value for the particles.
# The average velocity of gas particles is found using the root mean square velocity formula:
#
# μrms = (3RT/M)½ root mean square velocity in m/sec
#
# R = ideal gas constant = 8.3145 (kg·m2/sec2)/K·mol
#
# T = absolute temperature in Kelvin
#
# M = mass of a mole of the gas in kilograms. molar mass of O2 = 3.2 x 10-2 kg/mol
#
# T = °C + 273
#
# a. By using the decimal module, create a decimal object and apply the sqrt and quantize method (match pattern “1.000”)
# and provide the answer to the question:
# What is the average velocity or root mean square velocity of a molecule in a sample of oxygen at 25 degrees Celsius?
number = 3237945.76
print("{:25,.9f}".format(number))
print("{:.2f}".format(number))
print("{:,.2f}".format(number))
print("{:,.4f}".format(number))
| true |
47d783748c562dd3c3f8b7644dda166f37b5f11e | luizfirmino/python-labs | /Python I/Assigments/Module 5/Ex-6.py | 238 | 4.5 | 4 | #
# Luiz Filho
# 3/14/2021
# Module 5 Assignment
# 6. Write a simple function (area_circle) that returns the area of a circle of a given radius.
#
def area_circle(radius):
return 3.1415926535898 * radius * radius
print(area_circle(40)) | true |
6ca6fbf8e7578b72164ab17030f1c01013604b04 | luizfirmino/python-labs | /Python I/Assigments/Module 5/Ex-4.py | 549 | 4.28125 | 4 | #
# Luiz Filho
# 3/14/2021
# Module 5 Assignment
# 4. Explain what happens when the following recursive functions is called with the value “alucard” and 0 as arguments:
#
print("This recursive function is invalid, the function won't execute due an extra ')' character at line 12 column 29")
print("Regardless any value on its parameters this function will not execute or compile.")
def semordnilap(aString,index):
if index < len(aString):
print(aString[index]), end="")
semordnilap(aString, index+1)
semordnilap("alucard", 0) | true |
796c8bb615635d769a16ae12d9f27f2cfce4631c | luizfirmino/python-labs | /Python I/Assigments/Module 2/Ex-2.py | 880 | 4.53125 | 5 | #
# Luiz Filho
# 2/16/2021
# Module 2 Assignment
# Assume that we execute the following assignment statements
#
# length = 10.0 , width = 7
#
# For each of the following expressions, write the value of the expression and the type (of the value of the expression).
#
# width//2
# length/2.0
# length/2
# 1 + 4 * 5
#
length = 10.0
width = 7
print("-- DEFAULTS --------------")
print("Variable width value = " + str(width))
print("Variable length value = " + str(length))
print("--------------------------")
print("Result of width//2: " + str(width//2) + " output type:" + str(type(width//2)))
print("Result of length/2.0: " + str(length/2.0) + " output type:" + str(type(length/2.0)))
print("Result of length/2: " + str(length/2) + " output type:" + str(type(length/2)))
print("Result of 1 + 4 * 5: " + str((1 + 4 * 5)) + " output type:" + str(type((1 + 4 * 5))))
| true |
2dcdbed4df8b0608780c4d3a226c4f25d0de2b38 | Zetinator/just_code | /python/leetcode/binary_distance.py | 872 | 4.1875 | 4 | """
The distance between 2 binary strings is the sum of their lengths after removing the common prefix. For example: the common prefix of 1011000 and 1011110 is 1011 so the distance is len("000") + len("110") = 3 + 3 = 6.
Given a list of binary strings, pick a pair that gives you maximum distance among all possible pair and return that distance.
"""
def binary_distance(x: 'binary string', y: 'binary string') -> 'distance':
def find_prefix(x, y, n):
if not x or not y: return n
# print(f'STATUS: x:{x}, y:{y}, n:{n}')
if x[0] == y[0]:
return find_prefix(x[1:], y[1:], n+1)
else:
return n
prefix_len = find_prefix(x, y, 0)
x, y = x[prefix_len:], y[prefix_len:]
return len(x) + len(y)
# test
x = '1011000'
y = '1011110'
print(f'testing with: x:{x}, y:{y}')
print(f'ANS: {binary_distance(x, y)}')
| true |
308f485babf73eec8c433821951390b8c2414750 | Zetinator/just_code | /python/leetcode/pairs.py | 966 | 4.1875 | 4 | """https://www.hackerrank.com/challenges/pairs/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=search
You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value.
Complete the pairs function below. It must return an integer representing the number of element pairs having the required difference.
pairs has the following parameter(s):
k: an integer, the target difference
arr: an array of integers.
"""
from collections import Counter
def pairs(k, arr):
counter = Counter()
n_pairs = 0
for e in arr:
# print(f'e: {e}, counter: {counter}, n_pairs: {n_pairs}')
if e in counter:
n_pairs += counter[e]
counter[e+k] += 1
counter[e-k] += 1
return n_pairs
# test
k = 2
arr = [1,3,5,8,6,4,2]
print(f'testing with: {arr}')
print(f'ans: {pairs(k, arr)}')
| true |
e823b273ed44482d8c05499f66bf76e78b06d842 | Zetinator/just_code | /python/leetcode/special_string_again.py | 2,477 | 4.21875 | 4 | """https://www.hackerrank.com/challenges/special-palindrome-again/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=strings
A string is said to be a special string if either of two conditions is met:
All of the characters are the same, e.g. aaa.
All characters except the middle one are the same, e.g. aadaa.
A special substring is any substring of a string which meets one of those criteria. Given a string, determine how many special substrings can be formed from it.
"""
def is_special(s):
"""checks if the substring is "special"
"""
# special case:
if len(s) == 1: return True
# general case
match = s[0]
for i in range(len(s)//2):
if s[i] != match or s[i] != s[-(1+i)]: return False
return True
def substrCount(n, s):
"""counts how many substrings are "special"
somehow not fast enought... maybe because of the function call
"""
n_specials = 0
for i in range(len(s)):
for j in range(i, len(s)):
n_specials += 1 if is_special(s[i:j+1]) else 0
return n_specials
def substrCount(n, s):
res = 0
count_sequence = 0
prev = ''
for i,v in enumerate(s):
# first increase counter for all seperate characters
count_sequence += 1
if i and (prev != v):
# if this is not the first char in the string
# and it is not same as previous char,
# we should check for sequence x.x, xx.xx, xxx.xxx etc
# and we know it cant be longer on the right side than
# the sequence we already found on the left side.
j = 1
while ((i-j) >= 0) and ((i+j) < len(s)) and j <= count_sequence:
# make sure the chars to the right and left are equal
# to the char in the previous found squence
if s[i-j] == prev == s[i+j]:
# if so increase total score and step one step further out
res += 1
j += 1
else:
# no need to loop any further if this loop did
# not find an x.x pattern
break
#if the current char is different from previous, reset counter to 1
count_sequence = 1
res += count_sequence
prev = v
return res
# test
# s = 'asasd'
s = 'abcbaba'
n = 5
print(f'testing with: {s}')
print(f'ans: {substrCount(n, s)}')
| true |
e2b8fe6ba7d4d000b5ef8578aae3caf1847efc9d | Zetinator/just_code | /python/leetcode/unique_email.py | 1,391 | 4.375 | 4 | """
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.)
If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.)
It is possible to use both of these rules at the same time.
Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?
"""
def unique_email(x: 'array with emails')-> 'array with unique emails':
ans = set()
for e in x:
name, domain = e.split('@')
name = e.replace('.','').split('+')[0]
ans.add(f'{name}@{domain}')
return list(ans)
# test
test = ["test.email+alex@leetcode.com",
"test.e.mail+bob.cathy@leetcode.com",
"testemail+david@lee.tcode.com"]
print(f'testing with: {test}')
print(f'ANS: {unique_email(test)}')
| true |
ca54ebba62347e2c3a4107872889e4746c51a922 | malbt/PythonFundamentals.Exercises.Part5 | /anagram.py | 497 | 4.375 | 4 | def is_anagram(first_string: str, second_string: str) -> bool:
"""
Given two strings, this functions determines if they are an anagram of one another.
"""
pass # remove pass statement and implement me
first_string = sorted(first_string)
second_string = sorted(second_string)
if first_string == second_string:
print("anagram")
else:
print("not anagram")
first_string = "dormitory"
second_string = "dirtyroom"
is_anagram(first_string, second_string) | true |
e777115b8048caa29617b9b0e99d6fbac3beef99 | Vipulhere/Python-practice-Code | /Module 8/11.1 inheritance.py | 643 | 4.3125 | 4 | #parent class
class parent:
parentname=""
childname=""
def show_parent(self):
print(self.parentname)
#this is child class which is inherites from parent
class Child(parent):
def show_child(self):
print(self.childname)
#this object of child class
c=Child()
c.parentname="BOB"
c.childname="David"
c.show_parent()
c.show_child()
print("___________________")
class car:
def __init__(self,name="ford",model=2015):
self.name=name
self.model=model
def sport(self):
print("this is sport car")
class sportcar(car):
pass
c=sportcar("sportcar")
print(c.name)
print(c.model)
c.sport()
| true |
347460f3edf3af4e5601a45b287d1a086e1a3bc3 | bopopescu/PycharmProjects | /Class_topic/7) single_inheritance_ex2.py | 1,601 | 4.53125 | 5 | # Using Super in Child class we can alter Parent class attributes like Pincode
# super is like update version of parent class in child class
'''class UserProfile(Profile): # Child Class
def __init__(self,name,email,address,pincode): # constructor of child Class
super(UserProfile, self).__init__(name,email,address) # parent containing three attributes
self.pincode = pincode'''
class Profile: # Parent Class
def __init__(self, name, email, address): # constructor of parent class
self.name = name
self.email = email
self.address = address
def displayProfile(self): # display method in parent class
return "Name:{0}\nEmail:{1}\nAddress:{2}".format(
self.name,
self.email,
self.address
)
class UserProfile(Profile): # Child Class
def __init__(self,name,email,address,pincode): # constructor of child class
super(UserProfile, self).__init__(name,email,address) # parent containing three attributes
self.pincode = pincode
def setCity(self, city): # setCity method of child lass
self.city = city
def displayProfile(self): # display method in child class
return "Name:{0}\nEmail:{1}\nAddress:{2}\nCity:{3}\nPincode:{4}".format(
self.name,
self.email,
self.address,
self.city,
self.pincode
)
user = UserProfile("Raju","raju@gmail.com","BTM","580045") # object of child class
user.setCity("Bangalore") # adding attribute value to child class
temp = user.displayProfile()
print(temp)
| true |
7c693a0fe73b2fe3cbeeddf1551bf3d2f0250ab2 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/lab12/lab12-guess_the_number-v3.py | 694 | 4.34375 | 4 | '''
lab12-guess_the_number-v3.py
Guess a random number between 1 and 10.
V3
Tell the user whether their guess is above ('too high!') or below ('too low!') the target value.'''
import random
x = random.randint(1, 10)
guess = int(input("Welcome to Guess the Number v3. The computer is thinking of a number between 1 and 10.\nEnter your guess: "))
count = 0
while True:
count = count + 1
if guess == x:
print(f"Congrats. You guessed the computer's number and it only took you {count} times!")
break
else:
if guess > x:
guess = int(input("Too high... Try again: "))
if guess < x:
guess = int(input("Too low... Try again: "))
| true |
82ef1519965203526bf480fc9b989e73fb955f54 | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab17-palidrome_anagramv2.py | 312 | 4.5625 | 5 | # Python Program to Check a Given String is Palindrome or Not
string = input("Please enter enter a word : ")
str1 = ""
for i in string:
str1 = i + str1
print("Your word backwards is : ", str1)
if(string == str1):
print("This is a Palindrome String")
else:
print("This is Not a Palindrome String") | true |
81ff46e99809f962f6642b33aa03dd274ac7a16e | mohasinac/Learn-LeetCode-Interview | /Strings/Implement strStr().py | 963 | 4.28125 | 4 | """
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(needle)
h = len(haystack)
if n<1 or needle==haystack:
return 0
if h<1:
return -1
for i, c in enumerate(haystack):
if c==needle[0] and (i+n)<=h and all([haystack[i+j]==needle[j] for j in range(1,n)]):
return i
return -1
| true |
16cbb114d0a13ac1c2a25c4be46dd7c14db6584c | Divyendra-pro/Calculator | /Calculator.py | 761 | 4.25 | 4 | #Calculator program in python
#User input for the first number
num1 = float(input("Enter the first number: "))
#User input for the operator
op=input("Choose operator: ")
#User input for the second number
num2 = float(input("Enter the second number:" ))
#Difine the operator (How t will it show the results)
if op == '+':
print("You choosed for Addition ")
print(num1+num2)
elif op == '-':
print("You choosed for subtraction ")
print(num1-num2)
elif op == '*':
print("You choosed for multiplication ")
print(num1*num2)
elif op == '/':
print("Your choosed for division ")
print(num1/num2)
else:
print("Enter a valid operator")
print("Some valid operators: "
"+ "
"- "
"* "
"/ ")
| true |
c80bffe95bc94308989cec03948a4a91239d13aa | rbngtm1/Python | /data_structure_algorithm/array/remove_duplicate_string.py | 398 | 4.25 | 4 | # Remove duplicates from a string
# For example: Input: string = 'banana'
# Output: 'ban'
##########################
given_string = 'banana apple'
my_list = list()
for letters in given_string:
if letters not in my_list:
my_list.append(letters)
print(my_list)
print (''.join(my_list))
## possile solution exist using set data structure but
## set structure is disorder | true |
a6dd4e5cf972068af342c8e08e10b4c7355188e6 | DivyaRavichandr/infytq-FP | /strong .py | 562 | 4.21875 | 4 | def factorial(number):
i=1
f=1
while(i<=number and number!=0):
f=f*i
i=i+1
return f
def find_strong_numbers(num_list):
list1=[]
for num in num_list:
sum1=0
temp=num
while(num):
number=num%10
f=factorial(number)
sum1=sum1+f
num=num//10
if(sum1==temp and temp!=0):
list1.append(temp)
return list1
num_list=[145,375,100,2,10]
strong_num_list=find_strong_numbers(num_list)
print(strong_num_list)
| true |
4f32d0b2293ff8535a870cd9730528ecf4874190 | comedxd/Artificial_Intelligence | /2_DoublyLinkedList.py | 1,266 | 4.21875 | 4 | class LinkedListNode:
def __init__(self,value,prevnode=None,nextnode=None):
self.prevnode=prevnode
self.value=value
self.nextnode=nextnode
def TraverseListForward(self):
current_node = self
while True:
print(current_node.value, "-", end=" ")
if (current_node.nextnode is None):
print("None")
break
current_node = current_node.nextnode
def TraverseListBackward(self):
current_node = self
while True:
print(current_node.value, "-", end=" ")
if (current_node.prevnode is None):
print("None")
break
current_node = current_node.prevnode
# driver code
if __name__=="__main__":
node1=LinkedListNode("Hello ")
node2=LinkedListNode("Dear ")
node3=LinkedListNode(" AI ")
node4=LinkedListNode("Student")
head=node1
tail=node4
# forward linking
node1.nextnode=node2
node2.nextnode=node3
node3.nextnode=node4
# backward linking
node4.prevnode=node3
node3.prevnode=node2
node2.prevnode=node1
head.TraverseListForward()
tail.TraverseListBackward()
| true |
76348acf643b1cd9764e1184949478b3b888b014 | jdipendra/asssignments | /multiplication table 1-.py | 491 | 4.15625 | 4 | import sys
looping ='y'
while(looping =='y' or looping == 'Y'):
number = int(input("\neneter number whose multiplication table you want to print\n"))
for i in range(1,11):
print(number, "x", i, "=", number*i)
else:
looping = input("\nDo you want to print another table?\npress Y/y for yes and press any key to exit program.\n")
if looping =='y' or looping == 'Y':
looping = looping
else:
sys.exit("program exiting.......")
| true |
e6e94d3d50a56f104d1ad9993d78f8c44394b753 | jdipendra/asssignments | /check square or not.py | 1,203 | 4.25 | 4 | first_side = input("Enter the first side of the quadrilateral:\n")
second_side = input("Enter the second side of the quadrilateral:\n")
third_side = input("Enter the third side of the quadrilateral:\n")
forth_side = input("Enter the forth side of the quadrilateral:\n")
if float(first_side) != float(second_side) and float(first_side) != float(third_side) and float(first_side) != float(forth_side):
print("The Geometric figure is an irregular shaped Quadrilateral.")
elif float(first_side) == float(third_side) and float(second_side) == float(forth_side) and float(first_side) != float(second_side):
digonal1 = input("Enter first digonal:\n")
digonal2 = input("Enter second digonal:\n")
if float(digonal1) == float(digonal2):
print("The Geometric figure is a rectangle.")
else:
print("The Geometric figure is a parallelogram.")
elif float(first_side) == float(second_side) == float(third_side) == float(forth_side):
digonal1 = input("Enter first digonal:\n")
digonal2 = input("Enter second digonal:\n")
if float(digonal1) == float(digonal2):
print("The Geometric figure is a square.")
else:
print("The Geometric figure is a rhombus.") | true |
79b58db5b932f19b7f71f09c37c3942554507803 | RjPatil27/Python-Codes | /Sock_Merchant.py | 840 | 4.1875 | 4 | '''
John works at a clothing store. He has a large pile of socks that he must pair by color for sale.
Given an array of integers representing the color of each sock,
determine how many pairs of socks with matching colors there are.
For example, there are n = 7 socks with colors arr = [1,2,1,2,3,2,1] . There is one pair of color 1 and one of color 2.
There are three odd socks left, one of each color. The number of pairs is 2 .
Write code for this problem.
'''
from __future__ import print_function
def main():
n = int(input().strip())
c = list(map(int, input().strip().split(' ')))
pairs = 0
c.sort()
c.append('-1')
i = 0
while i < n:
if c[i] == c[i + 1]:
pairs = pairs + 1
i += 2
else:
i += 1
print(pairs)
if __name__ == '__main__':
main()
| true |
05432b48af09dc9b89fded6fb53181df2645ee53 | Mat4wrk/Working-with-Dates-and-Times-in-Python-Datacamp | /1.Dates and Calendars/Putting a list of dates in order.py | 569 | 4.375 | 4 | """Print the first and last dates in dates_scrambled.""
# Print the first and last scrambled dates
print(dates_scrambled[0])
print(dates_scrambled[-1])
"""Sort dates_scrambled using Python's built-in sorted() method, and save the results to dates_ordered."""
"""Print the first and last dates in dates_ordered."""
# Print the first and last scrambled dates
print(dates_scrambled[0])
print(dates_scrambled[-1])
# Put the dates in order
dates_ordered = sorted(dates_scrambled)
# Print the first and last ordered dates
print(dates_ordered[0])
print(dates_ordered[-1])
| true |
619f65ba890f6fa2e891f197581b739f02baae40 | Jmwas/Pythagorean-Triangle | /Pythagorean Triangle Checker.py | 826 | 4.46875 | 4 | # A program that allows the user to input the sides of any triangle, and then
# return whether the triangle is a Pythagorean Triple or not
while True:
question = input("Do you want to continue? Y/N: ")
if question.upper() != 'Y' and question.upper() != 'N':
print("Please type Y or N")
elif question.upper() == 'Y':
a = input("Please enter the opposite value: ")
print("you entered " + a)
b = input("Please enter the adjacent value: ")
print("you entered " + b)
c = input("Please enter the hypotenuse value: ")
print("you entered " + c)
if int(a) ** 2 + int(b) ** 2 == int(c) ** 2:
print("The triangle is a pythagorean triangle")
else:
print("The triangle is not a pythagorean triangle")
else:
break
| true |
6273ea18be6a76f5d37c690837830f34f7c516e4 | cahill377979485/myPy | /正则表达式/命名组.py | 1,351 | 4.46875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Python 2.7的手册中的解释:
(?P<name>...)
Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular
expression via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be
defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not
named. So the group named id in the example below can also be referenced as the numbered group 1.
For example, if the pattern is (?P<id>[a-zA-Z_]\w*),
the group can be referenced by its name in arguments to methods of match objects, such as m.group('id') or m.end('id'),
and also by name in the regular expression itself (using (?P=id))
and replacement text given to .sub() (using \g<id>).
"""
import re
# 将匹配的数字乘以 2
def double(matched):
value = int(matched.group('value'))
return str(value * 2)
def double2(matched):
value = int(matched.group(1))
return str(value * 2)
s = 'A23G4HFD567'
# 用命名group的方式
print(re.sub('(?P<value>\\d+)', double, s)) # ?P<value>的意思就是命名一个名字为value的group,匹配规则符合后面的/d+,具体文档看上面的注释
# 用默认的group带数字的方式
print(re.sub('(\\d+)', double2, s))
| true |
5c5199249efa2ba277218ed47e4ae2554a0bbf7e | Adi7290/Python_Projects | /improvise_2numeric_arithmetic.py | 660 | 4.21875 | 4 | #Write a program to enter two integers and then perform all arithmetic operators on them
num1 = int(input('Enter the first number please : \t '))
num2 = int(input('Enter the second number please :\t'))
print(f'''the addittion of {num1} and {num2} will be :\t {num1+num2}\n
the subtraction of {num1} and {num2} will be :\t {num1-num2}\n
the multiplication of {num1} and {num2} will be :\t {num1*num2}\n
the division of {num1} and {num2} will be :\t {num1/num2}\n
the power of {num1} and {num2} will be :\t {num1**num2}\n
the modulus of {num1} and {num2} will be :\t {num1%num2}\n
the floor division of {num1} and {num2} will be :\t {num1//num2}\n''')
| true |
4cc7aabb1e5e2b48cc90c607acce1b67f9fac93d | Adi7290/Python_Projects | /Herons formula.py | 350 | 4.28125 | 4 | #Write a program to calculate the area of triangle using herons formula
a= float(input("Enter the first side :\t"))
b= float(input("Enter the second side :\t"))
c= float(input("Enter the third side :\t"))
print(f"Side1 ={a}\t,Side2 = {b}\t,Side3={c}")
s = (a+b+c)/2
area=(s*(s-a)*(s-b)*(s-c))**0.5
print(f"Semi = {s}, and the area = {area}")
| true |
ea0b627a1ee97b93acd9087b18e36c3fa5d10b4d | Adi7290/Python_Projects | /singlequantity_grocery.py | 942 | 4.1875 | 4 | '''Write a program to prepare a grocery bill , for that enter the name of items , quantity in which it is
purchased and its price per unit the display the bill in the following format
*************BILL***************
item name item quantity item price
********************************
total amount to be paid :
*********************************'''
name = input('Enter the name of item purchased :\t')
quantity = int(input('Enter the quantity of the item :\t'))
amount = int(input('Enter the amount of the item :\t'))
item_price = quantity * amount
print('*****************BILL****************')
print(f'Item Name\t Item Quantity\t Item Price')
print(f'{name}\t\t {quantity}\t\t {item_price}')
print('************************************')
print(f'Price per unit is \t \t {amount}')
print('************************************')
print(f'Total amount :\t\t{item_price}')
print('************************************')
| true |
2b786c15f95d48b9e59555d2557cc497d922d948 | Adi7290/Python_Projects | /Armstrong_number.py | 534 | 4.40625 | 4 | """Write a program to find whether the given number is an Armstrong Number or not
Hint:An armstrong number of three digit is an integer such that the sum of the cubes of its digits is equal
to the number itself.For example 371 is the armstrong number since 3**3+7**3+1**3"""
num = int(input('Enter the number to check if its an Armstrong number or not :\t'))
orig = num
sm =0
while num>0:
sm = sm+(num%10)*(num%10)* (num%10)
num =num//10
if orig == sm:
print('Armstrong')
else:
print('Not Armstrong')
| true |
503700558831bf7513fc8987bb669f0e17d144c0 | deepika7007/bootcamp_day2 | /Day 2 .py | 1,301 | 4.1875 | 4 | #Day 2 string practice
# print a value
print("30 days 30 hour challenge")
print('30 days Bootcamp')
#Assigning string to Variable
Hours="Thirty"
print(Hours)
#Indexing using String
Days="Thirty days"
print(Days[0])
print(Days[3])
#Print particular character from certin text
Challenge="I will win"
print(challenge[7:10])
#print the length of the character
Challenge="I will win"
print(len(Challenge))
#convert String into lower character
Challenge="I Will win"
print(Challenge.lower())
#String concatenation - joining two strings
A="30 days"
B="30 hours"
C = A+B
print(C)
#Adding space during Concatenation
A="30days"
B="30hours"
C=A+" "+B
print(C)
#Casefold() - Usage
text="Thirty Days and Thirty Hours"
x=text.casefold()
print(x)
#capitalize() usage
text="Thirty Days and Thirty Hours"
x=text.capitalize()
print(x)
#find()
text="Thirty Days and Thirty Hours"
x=text.find()
print(x)
#isalpha()
text="Thirty Days and Thirty Hours"
x=text.isalpha()
print(x)
#isalnum()
text="Thirty Days and Thirty Hours"
x=text.isalnum()
print(x)
Result:
30 days 30 hour challenge
30 days Bootcamp
Thirty
T
r
win
10
i will win
30 days30 hours
30days 30hours
thirty days and thirty hours
Thirty days and thirty hours
-1
False
False
** Process exited - Return Code: 0 **
Press Enter to exit terminal
| true |
5571025882b22c9211572e657dd38b1a9ecdfa74 | martinkozon/Martin_Kozon-Year-12-Computer-Science | /Python/extra_sum_of_two.py | 342 | 4.1875 | 4 | #Program which will add two numbers together
#User has to input two numbers - number1 and number2
number1 = int(input("Number a: "))
number2 = int(input("Number b: "))
#add numbers number1 and number2 together and print it out
print(number1 + number2)
#TEST DATA
#Input 1, 17 -> output 18
#Input 2, 5 -> output 7
#Input 66, 33 -> output 99 | true |
fa98a79e66cd7e8575c857dabad5877c3b78cd87 | martinkozon/Martin_Kozon-Year-12-Computer-Science | /Python/06_input-validation.py | 816 | 4.25 | 4 | #User has to input a number between 1 and 10
#eg. if user inputs 3, the result will be as follows: 3 -> 3*1=3, 3*2=6, 3*3=9
#ask a user to input a number
number = int(input("Input number between 1 and 10: "))
#if the input number is 99 than exit the program
if number == 99:
exit()
# end if
#if the number isn't the one we want, the user will have to submit it again
while number < 1 or number > 10:
print("Number needs to be BETWEEN 1 and 10")
number = int(input("Input number between 1 and 10: "))
# end while
#times table running in a for loop with a range of 12
for count in range(12):
table = (count+1) * number #multiply count by the inputted number
print(str(count + 1) + " * " + str(number) + " = " + str(table)) #print out a result
# end for
# 27.9.19 EDIT - updated variable naming | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.