blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2173ad098596254036763aeafa11b98aebfa1fd4 | maro199111/programming-fundamentals | /Exercises/exercise17.py | 583 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 16:26:29 2019
@author: edoardottt
"""
#Write a function that take as input three numbers g,m,a (with a odd, in this way we avoid leap years)
# and it returns True or False depending on the three numbers make a valid date.
#Es. 30/2/2017 False; 1/1/1111 True
def verify_date(g,m,a):
if a > 2019 or (a==2019 and m> 10) or (a==2019 and m==10 and g>16):
return False
elif g>30 and (m==4 or m==6 or m==9 or m==11):
return False
elif g>28 and m==2:
return False
return True | true |
e0398fb3a6d508963caeb41fa5849c642ea2d414 | SairaQadir/python-assignment | /ass2/ass-2.py | 1,590 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
print("Enter 'x' for exit."); #question1
print("Enter marks obtained in 5 subjects: ");
mark1 = input();
if mark1 == 'x':
exit();
else:
mark1 = int(mark1);
mark2 = int(input());
mark3 = int(input());
mark4 = int(input());
mark5 = int(input());
sum = mark1 + mark2 + mark3 + mark4 + mark5;
average = sum/5;
if(average>=91 and average<=100):
print("Your Grade is A+");
elif(average>=81 and average<=90):
print("Your Grade is A");
elif(average>=71 and average<=80):
print("Your Grade is B+");
elif(average>=61 and average<=70):
print("Your Grade is B");
elif(average>=51 and average<=60):
print("Your Grade is C+");
elif(average>=41 and average<=50):
print("Your Grade is C");
elif(average>=0 and average<=40):
print("Your Grade is F");
else:
print("Strange Grade..!!");
# In[4]:
num = int(input("Enter a number: ")) #question2
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
# In[5]:
#question3
str = input("Enter a string: ")
counter = 0
for s in str:
counter = counter+1
print("Length of the input string is:", counter)
# In[6]:
def sum_list(items): #q4
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
# In[7]:
def max_num_in_list( list ): #q5
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
# In[ ]:
| true |
1d16d6b2bcb5ed20b8d80d4644f8faa455f71225 | KrystalGates/Bk1Ch4Dictionaries | /dictionaryOfWords.py | 1,325 | 4.59375 | 5 | # """
# Create a dictionary with key value pairs to
# represent words (key) and its definition (value)
# """
word_definitions = dict()
print(word_definitions)
# """
# Add several more words and their definitions
# Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python"
# """
word_definitions["crick"] = "A common Southernism refering to a pain, spasm, or strain in a joint such as a neck, back, or knee."
word_definitions["number neighbor"] = "Someone who has the same phone number as you, besides the last digit."
word_definitions["prime timing"] = "Staying up late watching TV after midnight. Usually primetiming involves watching reruns of favorite shows."
# """
# Use square bracket lookup to get the definition of two
# words and output them to the console with `print()`
# """
print("crick:", word_definitions["crick"], "primetiming:", word_definitions["prime timing"])
# """
# Loop over the dictionary to get the following output:
# The definition of [WORD] is [DEFINITION]
# The definition of [WORD] is [DEFINITION]
# The definition of [WORD] is [DEFINITION]
# """
# for key,value in my_pairs.items():
# print(f"This came from my_pairs: {value}")
for word,definition in word_definitions.items():
print(f"The definition of {word} is {definition}.") | true |
dd342084a237127b3358df48285c3541cab20ef3 | mrmichaelgallen/Course-Work-TTA | /Python/PythonInADay/Python_Item20_Script.py | 428 | 4.21875 | 4 | # String Manipulation
name = "Guido"
print name[0]
print name.upper()
print name.lower()
print name.capitalize()
# Formate a Date
date = "11/12/2013"
# Go through string and split
# Where there is a '/'
date_manip = date.split('/')
#Show the outcome
print date_manip
print date_manip[0]
print date_manip[1]
print date_manip[2]
print 'Month: ' + date_manip[0] + '. Day: ' + date_manip[1] + '. Year: ' + date_manip[2]
| true |
d1653e5fed55296e9546b46e7a0865072f55470e | vishrutarya/grpc-calculator | /calculator.py | 269 | 4.1875 | 4 | import math
def square_root(num: int):
"""
Returns the square root of the arg `num`.
"""
result = math.sqrt(num)
return result
def square(num: int):
"""
Returns the square of the `num` param.
"""
result = num ** 2
return result | true |
75d37d4417f0fb4dd3decb8aa3fa506139ad9544 | AllieJackson/Rice-Python-Certification | /RPSLS.py | 2,772 | 4.1875 | 4 | # Rock-paper-scissors-lizard-Spock template
#Imports
import random
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
# Take the user's name input and turn it into a number.
def name_to_number(name):
# delete the following pass statement and fill in your code below
pass
# convert name to number using if/elif/else
if name == "rock":
return 0
elif name == 'Spock':
return 1
elif name == 'paper':
return 2
elif name == 'lizard':
return 3
elif name == 'scissors':
return 4
else:
return 'Not a valid user name: fail'
# Take the computer's random number from 0 to 4 and turn it into the correct name.
def number_to_name(number):
# convert number to a name using if/elif/else
if number == 0:
return "rock"
elif number == 1:
return 'Spock'
elif number == 2:
return 'paper'
elif number == 3:
return 'lizard'
elif number == 4:
return 'scissors'
else:
return 'Number not 0 through 4: fail'
def rpsls(player_choice):
# print out the message for the player's choice
print('Player chooses {}'.format(player_choice))
# convert the player's choice to player_number using the function name_to_number()
player_num = name_to_number(player_choice)
# compute random guess for comp_number using random.randrange()
comp_num = random.randrange(0, 5)
# convert comp_number to comp_choice using the function number_to_name()
comp_name = number_to_name(comp_num)
# print out the message for computer's choice
print('Computer chooses {}'.format(comp_name))
# compute difference of comp_number and player_number modulo five
dif_val = (comp_num - player_num) % 5
# Determine the winner. Use the rule discussed in lecture that for Item 1 - Item 2, (Item1-Item2)%5 is
# 1 or 2, then the first Item wins, but if it results in 3 or 4 then the second Item wins. If the value of the
# calculation is zero (e.g., both players chose the same number) then the result is a tie.
if dif_val == 0:
print('Player and computer tie!\n')
return
elif dif_val <3:
print('Computer wins!\n')
return
else:
print('Player wins!\n')
# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE
# Player choices - hardcoded in. Plays 5 games.
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
# End of Rock Paper Scissors Lizard Spock #
| true |
23e5502f4418219a78ab515e60be0a49de72c492 | gmanproxtreme/rps | /rps.py | 1,407 | 4.21875 | 4 | import random, math
def Draw():
print("We both picked the same.")
return
def PWin():
print("Well done you win.")
return
def CWin():
print("You lose.")
return
StrUserType = input("Select Paper, Rock or Scissors (P,R or S)")
ComputerType = math.floor(random.random()*3) #random.random(3)
# 0==Paper, 1==Rock and 2==Scissors
if StrUserType.upper() == "P":
print("You picked Paper")
if ComputerType == 0:
print("The computer picked Paper")
Draw()
elif ComputerType == 1:
print("The computer picked Rock")
PWin()
elif ComputerType == 2:
print("The computer picked Scissors")
CWin()
elif StrUserType.upper() == "R":
print("You picked Rock")
if ComputerType == 0:
print("The computer picked Paper")
CWin()
elif ComputerType == 1:
print("The computer picked Rock")
Draw()
elif ComputerType == 2:
print("The computer picked Scissors")
PWin()
elif StrUserType.upper() == "S":
print("You picked Scissors")
if ComputerType == 0:
print("The computer picked Paper")
PWin()
elif ComputerType == 1:
print("The computer picked Rock")
Cwin()
elif ComputerType == 2:
print("The computer picked Scissors")
Draw()
else:
print("You need to pick a choice by typing the first letter only.") | true |
169fc98fcdeec215e501af357eae3122a46a0396 | ryandancy/project-euler | /problem145.py | 1,361 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project Euler Problem 145:
Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd (decimal) digits.
For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so 36, 63, 409, and 904 are
reversible. Leading zeroes are not allowed in either n or reverse(n).
There are 120 reversible numbers below one-thousand.
How many reversible numbers are there below one-billion (10^9)?
"""
# Largely brute-force: check if each n is reversible from n=1 to n=10^9/2, add 2 for each one
# If n is reversible, reverse(n) is added to a "don't visit" set which each n is check against before proceeding
# n goes only up to 10^9/2 (not 10^9) because any 10^9/2 < n < 10^9 will have a counterpart 0 < reverse(n) < 10^9/2
# and n would already have been found as the reverse of reverse(n)
def reverse(n):
return int(str(n)[::-1])
ODD_DIGITS = {'1', '3', '5', '7', '9'}
def check_reversible(n):
if n % 10 == 0:
return False
rev = reverse(n)
return rev if set(str(n + rev)) <= ODD_DIGITS else False
num_reversible = 0
dont_visit = set()
for n in range(1, 10**9//2):
if n in dont_visit:
dont_visit.remove(n)
continue
rev = check_reversible(n)
if rev:
num_reversible += 2
dont_visit.add(rev)
print(num_reversible)
| true |
3c6b82f854695233a25f58a869b8ed2b3e91239a | ryandancy/project-euler | /problem1.py | 439 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project Euler Problem 1:
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
# Add multiples of 3 to multiples of 5 which are not also multiples of 3
sum_ = sum(range(0, 1000, 3)) + sum(filter(lambda m: m % 3 != 0, range(0, 1000, 5)))
print(sum_)
| true |
31f112f9bddd7f691305e842293e37715bd65616 | vincent507cpu/Comprehensive-Algorithm-Solution | /LintCode/ladder 07 data structure/必修/494. Implement Stack by Two Queues/.ipynb_checkpoints/solution-checkpoint.py | 1,059 | 4.1875 | 4 | # For python class
import queue
class Stack:
def __init__(self):
self.queue1 = queue.Queue()
self.queue2 = queue.Queue()
"""
@param: x: An integer
@return: nothing
"""
def push(self, x):
# write your code here
self.queue1.put(x)
"""
@return: nothing
"""
def pop(self):
# write your code here
while self.queue1.qsize() > 1:
self.queue2.put(self.queue1.get())
item = self.queue1.get()
self.queue1, self.queue2 = self.queue2, self.queue1
return item
"""
@return: An integer
"""
def top(self):
# write your code here
while self.queue1.qsize() > 1:
self.queue2.put(self.queue1.get())
item = self.queue1.get()
self.queue1, self.queue2 = self.queue2, self.queue1
self.push(item)
return item
"""
@return: True if the stack is empty
"""
def isEmpty(self):
# write your code here
return self.queue1.empty() | false |
e474a3325c48bc7ae870cb28bbcccbe756b672e6 | CMWelch/Python_Projects | /Python/Python_Exercises/Paper Doll.py | 293 | 4.1875 | 4 | def paper_doll(string):
new_string = ""
for letter in string:
if letter == " ":
new_string = new_string + letter
else:
new_string = new_string + letter * 3
return new_string
x = input("Input a string: ")
print(paper_doll(x))
| true |
d3ad38b74a30be421c8d3ba453ddfd6df0545d34 | Batukhanyui/pancake | /turtleber/11.py | 227 | 4.1875 | 4 | import turtle
turtle.shape('turtle')
for i in range(1,6):
for j in range(360//i):
turtle.forward(i*i)
turtle.left(i)
for j in range(360//i):
turtle.forward(i*i)
turtle.right(i)
input()
| false |
5c1560c964288474b7a6a91834522b6410396ca5 | imn00133/PythonSeminar | /TeachingMaterials/BookAndLecutreData/python_middle_class/chapter3_data_model/p_chapter03_02.py | 1,143 | 4.1875 | 4 | class Vector(object):
def __init__(self, *args):
"""
Create a vector,
example = Vector(5, 10)
:param args: x, y
"""
if len(args) == 0:
self._x, self._y = 0, 0
else:
self._x, self._y = args
def __repr__(self):
"""
:return: Return the vector information.
"""
return 'Vector(%r, %r)' % (self._x, self._y)
def __add__(self, other):
"""
:param other: Vector
:return: Return the vector addition of self and other
"""
return Vector(self._x + other._x, self._y + other._y)
def __mul__(self, factor):
"""
:param factor: Vector
:return: Return the multiple vector
"""
return Vector(self._x * factor, self._y * factor)
def __bool__(self):
return bool(self._x) and bool(self._y)
v1 = Vector(5, 7)
v2 = Vector(23, 35)
v3 = Vector()
print(Vector.__init__.__doc__)
print(Vector.__repr__.__doc__)
print(Vector.__add__.__doc__)
print(v1, v2, v3)
print(v1 + v2)
print(v1 * 3)
print(v2 * 10)
print(bool(v1), bool(v2))
print(bool(v3))
| false |
a8627eb2f89fc73226d44390e7bf7af895f02ff8 | benjimortal/face_recognition | /first/toturial/2.py | 1,259 | 4.3125 | 4 |
def days_to_units(num_of_days, conversion_unit):
if conversion_unit == 'hours':
return f"{num_of_days} days are {num_of_days * 24} hours"
elif conversion_unit == 'minutes':
return f"{num_of_days} days are {num_of_days * 24 * 60} minutes"
else:
return 'unsupported unit'
def validate_and_execute():
try:
user_input_number = int(days_and_unit_dict['days'])
# we want to do conversion only for positive integers
if user_input_number > 0:
calculated_value = days_to_units(user_input_number, days_and_unit_dict['unit'])
print(calculated_value)
elif user_input_number == 0:
print("you entered a 0, please enter a valid positive number")
else:
print("you entered a negative number, no conversion for you!")
except ValueError:
print("your input is not a valid number. Don't ruin my program!")
user_input = ""
while user_input != "exit":
user_input = input("Hey user, enter number of days and conversion unit!\n")
days_and_unit = user_input.split(":")
print(days_and_unit)
days_and_unit_dict = {"days":days_and_unit[0], "unit": days_and_unit[1]}
print(days_and_unit_dict)
validate_and_execute()
| true |
b105d2c2229bec44e5e3de2400f883ae3669cc70 | benjimortal/face_recognition | /first/Python_Exercises_skolan/6.py | 490 | 4.15625 | 4 | def main():
notes = {
'1' : 'George Washington',
'2' : 'Thomas Jefferson',
'5' : 'Abraham',
'10': 'Alexander Hamilton',
'20': 'Ulysses S.Grant',
'50': 'Andrew Jackson',
'100':'Benjamin Franklin'
}
value = input('Please enter the value of an US dollar note: ')
if value not in notes:
print('Sorry that is not a valid US dollar note.')
else:
print(f'On that note you will find', notes[value])
if __name__ == '__main__':
main()
| true |
161e6533b74de7eafb66172b68746e863a40d121 | eisendaniel/ENGR_PHYS_LABS | /Lab 1/Python_Intorduction.py | 973 | 4.34375 | 4 | #Lets learn Python
3+4
#if we want to see the result we need to print it
print(3+4)
#Printing text needs 'quote marks'
print('abc')
#assign a varible
a=1.602**2
print(a+3)
#can have creative names
newvariblewithmorecreativename=4
print(a+newvariblewithmorecreativename)
#Arrays
A=[1,2,3,4,5]
print(A)
#indexing arrays, printing entry in position [1]
print(A[1])
#printing multiple values in A
print(A[2:5])
print(A[1]+3)
#what if we want to add 3 to each value in A
#print(A+3)
for i in range(5):
print(i)
#what if we don't know how long A is?
n=len(A)
print(n)
#simple for loop
for i in range(n):
print(i)
#lets add 3 to A[i]
for i in range(n):
print(A[i]+a)
#list comprehension (for loop in one line of code)
B=[A[i]+3 for i in range(n)]
print(B)
#Import Pyplot from Matplotlib
from matplotlib import pyplot as plt
plt.plot(A,B)
#search python matlab plot label axes
plt.ylabel("an axis")
#search change colour
| true |
56470a1df35f1b0959fe161adff34183fdc281b9 | zhuhanqing/Data-Structures-Algorithms-Goodrich | /Chapter04_Recursion/xPowerN.py | 232 | 4.1875 | 4 | def power(x,n):
"""
Compute the value of x raised to power n
"""
if n==0:
return (1)
else:
return (x * power(x,n-1))
#Code Fragment 4.11: Computing the power function using trivial recursion. | true |
3bb68bfe85229cc2d0672c672db657c98c31e489 | zhuhanqing/Data-Structures-Algorithms-Goodrich | /Chapter04_Recursion/sumOfArray_UsingBinaryRecursion.py | 549 | 4.1875 | 4 | def binary_sum(S,start,stop):
"""
Return the sum of the numbers in implicit slice S[start:stop].
"""
if start >= stop: # zero elements in slice
return (0)
elif start == stop-1: # One element in slice
return (S[start])
else: # two or more elements in slice
mid = (start + stop)//2
return (binary_sum(S,start,mid) + binary_sum(S,mid,stop))
#Code Fragment 4.13: Summing the elements of a sequence using binary recursion. | true |
1d12a62805e70d7bda3879142c3970e8863bead8 | lvkeeper/programming-language-entry-record | /fuzzing/src/fuzzingbook/fuzzingbook_utils/Timer.py | 2,103 | 4.3125 | 4 | # 官方的代码写的很好,读起来很有收获,我这里敲一遍
# python time 模块:https://docs.python.org/3/library/time.html
# 事实上,当我们向文件导入某个模块时,导入的是该模块中那些名称不以下划线(单下划线“_”或者双下划线“__”)开头的变量、函数和类。
# 因此,如果我们不想模块文件中的某个成员被引入到其它文件中使用,可以在其名称前添加下划线。
# 在普通模块中使用时,表示一个模块中允许哪些属性可以被导入到别的模块中
# 或许这是一个不错的东西,可以直观看到哪些内容会被导入到别的模块
# 仅对模糊导入时起到作用。如:from xxx import *
# __all__ = ["Timer"]
# 与__init__搭配比较好看
if __name__ == "__main__":
print("\n# Timer")
if __name__ == "__main__":
print("\n## Synopsis")
import time
def clock():
try:
return time.perf_counter() # python3 包含睡眠期间经过的时间
# return time.process_time() # python3
except:
return time.clock() # python 2 返回当前处理器时间
class Timer(object):
def __enter__(self):
self.start_time = clock()
self.stop_time = None
return self
def __exit__(self, exc_type, exc_value, tb):
self.stop_time = clock()
def elapsed_time(self):
"""Return elapsed time in seconds"""
if self.stop_time == None:
# still run
return clock() - self.start_time
else:
return self.stop_time - self.start_time
# test class Timer()
if __name__ == "__main__":
print("\n## test class Timer()")
def run_circle():
i = 1000000
while i > 0:
i -= 1
if __name__ == "__main__":
print("\n all spend time:")
with Timer() as t:
run_circle()
print(t.elapsed_time())
if __name__ == "__main__":
with Timer() as t:
i = 10
while i > 0:
i -= 2
print(f"\n middle spend time {t.elapsed_time()}")
if __name__ == "__main__":
print("\n## Synopsis") | false |
f25516ec401c9387a98463b7fefa334e45a5be15 | nathanstouffer/adv-alg | /little-algs/mergesort.py | 1,017 | 4.3125 | 4 | # a short program to mergesort some lists
import random
# method to recursively divide the mergesort
def mergesort(nums):
mid = int(len(nums) / 2)
if (mid == 0):
return nums
else:
nums1 = nums[:mid]
nums2 = nums[mid:]
return merge(mergesort(nums1), mergesort(nums2))
# method to merge to sorted lists into a single sorted list
def merge(nums1, nums2):
nums = []
pos1 = 0
pos2 = 0
while (pos1 < len(nums1) or pos2 < len(nums2)):
if (pos1 >= len(nums1)):
nums.append(nums2[pos2])
pos2 += 1
elif (pos2 >= len(nums2)):
nums.append(nums1[pos1])
pos1 += 1
elif (nums1[pos1] < nums2[pos2]):
nums.append(nums1[pos1])
pos1 += 1
else:
nums.append(nums2[pos2])
pos2 += 1
return nums
nums = []
for i in range(0, 50):
nums.append(random.randrange(-100, 100))
print("initial:", nums)
nums = mergesort(nums)
print("sorted: ", nums)
| true |
b61305eafd0017a606e4490f18c2cfe30125bbcb | chaoticfractal/Python_Code | /Students_Final_Grades.py | 1,979 | 4.125 | 4 | """
This a little script that will take 3 dictonaries of Students name that contain lists of
objects like homework scores, tests scores etc. that are then taken by funcitons to calculate final grade and
averages.
"""
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
#This function gets the "numbers" from each list and performs an average fuction
def average(numbers):
total = float(sum(numbers))
return total/len(numbers)
#This fuction takes in the dictonaries of each student and calc. the average
#of each of the lists
def get_average(student):
homework = float(average(student["homework"])) * 0.1
quizzes = float(average(student["quizzes"])) * 0.3
tests = float(average(student["tests"])) * 0.6
return homework + quizzes + tests
#This function returns the final average of each student
def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
print get_letter_grade(get_average(lloyd))
print get_letter_grade(get_average(alice))
print get_letter_grade(get_average(tyler))
students=[lloyd, alice, tyler]
#This functions gets the entire class average
#It takes in the new list that contains the average grade of each student and
#Calc. the total average of the 3
def get_class_average(students):
results=[]
for student in students:
results.append(get_average(student))
return average(results)
print get_class_average(students)
print get_letter_grade(get_class_average(students))
| true |
1b42d041dcdce21ceeed5837d0a6b052e2f49225 | danielnzlz01/Christmas-tree-drawn-with-characters | /main(9).py | 640 | 4.15625 | 4 | # Pinito de navidad
print("This program will draw a tree, tell me the height of the tree:")
niveles=int(input())
espacios=niveles-1 #número de espacios que van antes del primer asterisco
asteriscos=1
contador=0
while contador<niveles:
contador+=1
for x in range (espacios): #espacios antes de los asteriscos
print(" ",end="") #cantidad de espacios
for y in range (asteriscos): #cantidad de asteriscos
print("* ",end="") #espacios o no después del asterisco
print ("") #salto de línea
asteriscos+=1 #variable que suma un asterisco para el próximo nivel
espacios-=1 #variable que quita un asterisco para el próximo nivel"
| false |
db553849968f52596e9e8494af602051f0913b3d | TinaArts/leetcode | /array/rotate-array.py | 1,220 | 4.3125 | 4 | """Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
"""
from typing import List
nums_ex1 = [1, 2, 3, 4, 5, 6, 7]
k_ex1 = 3
nums_ex2 = [-1, -100, 3, 99]
k_ex2 = 2
def rotate_sol1(nums: List[int], k: int) -> None:
"""
Runtime: 60 ms
Memory Usage: 15.5 MB
:param nums:
:param k:
:return:
"""
left_k = len(nums) - k
left_part = nums[:left_k]
del nums[:left_k]
nums.extend(left_part)
def rotate_sol2(nums: List[int], k: int) -> None:
"""
Runtime: 124 ms
Memory Usage: 15.3 MB
:param nums:
:param k:
:return:
"""
i = 0
while k > i:
nums.insert(0, nums[-1])
del nums[-1]
i += 1
if __name__ == '__main__':
rotate_sol1(nums_ex1, k_ex1)
rotate_sol2(nums_ex1, k_ex1)
| true |
4af14b72dfcd78682fff9235735bc938ffff6165 | MarcosLazarin/Curso-de-Python | /ex072.py | 760 | 4.34375 | 4 | # Criar uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte.
# O programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.
continuar = 'S'
numeros = ('zero', 'um', 'dois', 'três', 'quatro',
'cinco', 'seis', 'sete', 'oito', 'nove',
'dez', 'onze', 'doze', 'treze','quatorze',
'quinze', 'dezesseis', 'dezessete', 'dezoito',
'dezenove', 'vinte')
while continuar == 'S':
while True:
n = int(input('Digite um número entre 0 e 20: '))
if 0 <= n <= 20:
break
print('Tente novamente')
print(f'Você digitou o número {numeros[n]}.')
continuar = input('Quer continuar? [S/N]').upper().strip()
print('Fim do programa!') | false |
d3a4f74658e87b78a086ccbec165af91a3d1536f | MarcosLazarin/Curso-de-Python | /ex039.py | 1,373 | 4.125 | 4 | # Escreva um programa que leia o ano de nascimento de uma pessoa de acordo com sua idade e diga:
# Se ele ainda vai se alistar ao serviço militar
# Se é hora de se alistar
# Se já passou o tempo de alistamento
# O programa deve identificar quanto tempo falta ou passou de se alistar.
from datetime import date
idade = int(input('Qual é a sua idade? '))
b = date.today()
c = b.year
nascimento = c - idade
if 18 > idade > 16:
print('O seu ano de nascimento é {} e você não está na hora de se alistar!'.format(nascimento))
print('Falta 1 ano para o seu alistamento.')
elif idade < 18:
print('O seu ano de nascimento é {} e você não está na hora de se alistar!'.format(nascimento))
print('Faltam {} anos para o seu alistamento.'.format(18 - idade))
print('Seu alistamento deve ocorrer em {} anos.'.format(nascimento + 18))
elif 20 > idade > 18:
print('Seu ano de nascimento é {} e você já se alistou!'.format(nascimento))
print('Você se alistou à exatamente 1 ano atrás, que foi em {}.'.format(c - 1))
elif idade > 18:
print('Seu ano de nascimento é {} e você já se alistou!'.format(nascimento))
print('Você se alistou à {} anos atrás, que foi em {}.'.format(idade - 18, nascimento + 18))
else:
print('Seu ano de nascimento é exatamente {}.'.format(nascimento))
print('Você deve se alistar IMEDIATAMENTE!') | false |
1e2532758ba7e4718381ad1de6f6dff41cb2d675 | xyzhangaa/ltsolution | /BTreeInorder.py | 1,630 | 4.15625 | 4 | ###Given a binary tree, return the inorder traversal of its nodes' values.
# O(n), O(n)
def iterative_inorder(self,root,list):
stack = []
while root or stack:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
list.append(root.val)
root= root.right
return list
def inorder(root):
list = []
self.iterative_inorder(root,list)
return list
# Time: O(n)
# Space: O(1)
#
# Given a binary tree, return the inorder traversal of its nodes' values.
#
# For example:
# Given binary tree {1,#,2,3},
# 1
# \
# 2
# /
# 3
# return [1,3,2].
#
# Note: Recursive solution is trivial, could you do it iteratively?
#
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Morris Traversal Solution
class Solution:
# @param root, a tree node
# @return a list of integers
def inorderTraversal(self, root):
result, prev, cur = [], None, root
while cur:
if cur.left is None:
result.append(cur.val)
prev = cur
cur = cur.right
else:
node = cur.left
while node.right and node.right != cur:
node = node.right
if node.right is None:
node.right = cur
cur = cur.left
else:
result.append(cur.val)
node.right = None
prev = cur
cur = cur.right
return result
| true |
973c6c4a2bc42f7774c6cedb01100948e1e5af8e | xyzhangaa/ltsolution | /ReverseWordsinaStringII.py | 808 | 4.125 | 4 | # Time: O(n)
# Space:O(1)
#
# Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
#
# The input string does not contain leading or trailing spaces and the words are always separated by a single space.
#
# For example,
# Given s = "the sky is blue",
# return "blue is sky the".
#
# Could you do it in-place without allocating extra space?
#
class Solution:
def reversewords(self,s):
self.reverse(s,0,len(s)):
i =0
for j in xrange(len(s)+1):
if j == len(s) or s[j] == ' ':
self.reverse(s,i,j)
i = j+1
def reverse(self,s,begin,end):
for i in xrange((end-begin)/2):
s[begin+i],s[end-1-i] = s[end-1-i],s[being+i]
if __name__ == '__main__':
s=....
Solution().reversewords(s)
preint s
| true |
ad67bdef83de3cc2f3bb7dd4c16bc06f60e3cdce | Quinneth/Election_Analysis | /Temperature.py | 293 | 4.5625 | 5 | #delcared by asking user to input int() wrapped statement-->converts user input type from string to integer then used to assess if-else statement
temperature = int(input("What is the temperature outside"))
if temperature > 80:
print("turn on the AC.")
Else:
print("Open the windows.") | true |
8932a7e8052a2835b793425407c36b84546d1cfc | Jmarshall1994/PRG105 | /99bottles.py | 227 | 4.125 | 4 | bottles = input('How many bottles?')
while bottles > 0:
print bottles, 'bottles of beer on the wall, ',bottles,' of beer. Take one down and pass it around,', bottles-1,' bottles of beer on the wall'
bottles = bottles -1 | true |
c8aa9c40d811e7c302711f32edb49a742f4963cb | arinablake/python-selenium-automation | /hw_algorithms_5/hw_5_2.py | 794 | 4.3125 | 4 | # Вводится ненормированная строка, у которой могут быть пробелы в начале, в конце и между словами более одного пробела.
# Привести ее к нормированному виду, т.е. удалить все пробелы в начале и конце, а между словами оставить только один пробел.
' Enter some abnormal string '
def clean_string(string):
clean_beg_end = string.strip(' ')
array = clean_beg_end.split(' ')
result = []
for item in array:
if not item == '':
result.append(item)
return ' '.join(result)
print(clean_string(' Enter some abnormal string ')) | false |
35c01a577cc7c7fb9517413e112b8c8711699c3d | arinablake/python-selenium-automation | /hw_algorithms_1/Return Negative.py | 317 | 4.46875 | 4 | #In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
def make_negative( number ):
if number > 0:
return - number
elif number < 0:
return number
else:
return 0
print(make_negative(-10))
print(make_negative(25))
| true |
60cfd5e18f77aaef3ed49a163311c3eed17d819e | benjamin22-314/learn_python_the_hard_way | /ex31.py | 649 | 4.1875 | 4 | print("""You enter a room.
There is a chair in the room.
There is a door in the room.""")
print("""Do you sit on the chair (press '1')
or go through the door (press '2')""")
choice = input("> ")
if choice == '1':
print("The chair is an illusion, you fall on your bum")
elif choice == '2':
print("The door is just a painting on the wall.")
else:
print("No choice is still a choice.")
print("""You begin to understand the situation you're in.
Do you try leave the way you came in (press 'a') or
do you start to think of a cunning plan (press 'b')""")
choice = input("> ")
print("You're choice is irrelevant and life has no meaning")
| true |
64a6261b37c4498244a300a8930776e330703f8f | huynhtritaiml2/Python_Basic_Summary | /list2.py | 2,867 | 4.28125 | 4 | greetings = ["hi", "hello", "wassap"]
print(greetings[2]) # wassap
print(len(greetings)) # 3
# n --> list size
# highest index = n - 1
#
for item in greetings:
print(item)
for i in range(len(greetings)):
print(greetings[i]);
#
backpack = ["sword", "rubber duck", "slice of pizza", "parachute", "sword", "sword"]
print(backpack.count("sword"))
if backpack.count("sword") < 5:
backpack.append("sword")
# Insert
'''
list is dynamic array, so we insert new item, it will shift the RIGHT of inserted index all the elements to the RIGHT 1 index
'''
workdays = ["Monday", "Tuesday", "Thursday", "Friday", "Saturday"]
workdays.insert(2, "Wednesday") # ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
print(workdays)
# Remove
'''
list is dynamic array, so we insert new item, it will shift the RIGHT of inserted index all the elements to the LEFT 1 index
NOTE: we do need to know the position of item :))
'''
workdays.remove("Saturday") # ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(workdays)
# Del
'''
NOTE: we know the position to remove
'''
workdays = ["Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday"]
del workdays[5] # == del workdays[-1]
print(workdays)
# Del 2:
workdays = ["Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday"]
del workdays[workdays.index("Wednesday") : workdays.index("Wednesday") + 3] # 3 days off # ['Monday', 'Tuesday', 'Saturday']
workdays = ["Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday"]
del workdays[workdays.index("Wednesday"):] # ['Monday', 'Tuesday']
print(workdays)
########## REMOVE ELEMENT FROM LIST USING DEL AND SLICE ##########
print("########## REMOVE ELEMENT FROM LIST USING DEL AND SLICE ##########")
work_days = ["Monday", "Tuesday", "Thursday", "Friday", "Saturday"]
del work_days[0:2] #remove first 2
print(work_days) # ['Thursday', 'Friday', 'Saturday']
work_days = ["Monday", "Tuesday", "Thursday", "Friday", "Saturday"]
del work_days[-2:] #remove last 2 (start 2 from right and go to end)
print(work_days) # ['Monday', 'Tuesday', 'Thursday']
# Pop
workdays = ["Monday", "Tuesday", "Thursday", "Friday", "Saturday"]
popped = workdays.pop(4) # ['Monday', 'Tuesday', 'Thursday', 'Friday']
print("We just removed", popped) # We just removed Saturday
popped = workdays.pop(1) # ['Monday', 'Thursday', 'Friday']
print("We just removed", popped) # We just removed Tuesday
print(workdays)
########## REMOVING ALL OCCURANCES IN LIST ##########
backpack = ["pizza slice", "button", "pizza slice", "fishing pole",
"pizza slice", "nunchucks", "pizza slice", "sandwich from mcdonalds"]
backpack.remove("pizza slice")
print(backpack) #SO MUCH PIZZA!
while("pizza slice" in backpack): # O(n) # ['button', 'fishing pole', 'nunchucks', 'sandwich from mcdonalds']
backpack.remove("pizza slice")
print(backpack) | true |
ce071793eb12f7205d5eb0726c053024bbf50a58 | giovane-aG/exercicios-curso-em-video-python | /desafio033.py | 281 | 4.15625 | 4 | print('Digite 3 números')
n1 = float(input('Primeiro número:'))
n2 = float(input('Segundo número:'))
n3 = float(input('Terceiro número:'))
numbers = [n1,n2,n3]
bigest = max(numbers)
smallest = min(numbers)
print('O maior número é {} e o menor é {}'.format(bigest, smallest)) | false |
c42e9d6757228d28bb035ff809d6daa1cb0db733 | srea8/cookbook_python | /03/CalculatingWithFractions.py | 698 | 4.1875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Srea
# @Date: 2019-09-26 17:17:22
# @Last Modified by: shenzhijie
# @Last Modified time: 2019-09-26 17:25:09
#****************************#
#fractions 模块可以被用来执行包含分数的数学运算
#****************************#
from fractions import Fraction
a = Fraction(10,19)
print(a)
b = Fraction(10,19)
print(a+b)
print(a*b)
#####获取分数的除数与被除数
c = a*b
print(c.numerator)
print(c.denominator)
print(float(c)) ###将分数转成小数
print(c.limit_denominator(360)) ###最佳近似值,限制值的分母
x = 3.75
y = Fraction(*x.as_integer_ratio()) # 将浮点数转换为分数
print(y) | false |
c4beb3d5a41bbcd6c6c115a13ef7f0f85a60f0da | alinasansevich/coding-playground | /grokking_algorithms/g_a_Ch2_SortSmallestToLargest.py | 870 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 10 14:49:32 2021
@author: alina
Code from the book "Grokking Algorithms",
exercises, examples, my experiments with it, etc.
"""
def find_smallest(arr):
"""
(list of int) -> int
Returns the smallest integer in a list of integers (I could just use min(list))
"""
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
"""
(list of int) -> sorted list
Returns list arr with elements sorted from smallest to largest.
"""
new_arr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr
selection_sort([5, 3, 6, 2, 10]) | true |
1206e0ce85952fbe5508676e1a7bfa99e75195d9 | pronouncedlyle/DS-and-Algos-Practice | /Sandbox/linked_list.py | 1,551 | 4.1875 | 4 | import time
#define node (like the constructor)
class node:
def __init__(self, data = None):
self.data = data
self.next = None
# define a linked list (using the definition of node)
class linked_list:
def __init__(self):
self.head = node()
#add to a linked list
def append (self, data):
new_node = node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
#print a linked list
def display(self):
elems = []
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
elems.append(cur_node.data)
print(elems)
def display_backwards(self):
elems = []
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
elems.append(cur_node.data)
elems.reverse()
print(elems)
def display_backwards2(self):
elems = []
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
elems.insert(0, cur_node.data)
print(elems)
# Testing the linked list and associated functions
my_list = linked_list()
for i in range(9):
my_list.append(i)
my_list.display()
tic = time.perf_counter()
my_list.display_backwards()
toc = time.perf_counter()
print(f"Executed in {toc - tic:0.10f} seconds")
tic = time.perf_counter()
my_list.display_backwards2()
toc = time.perf_counter()
print(f"Executed in {toc - tic:0.10f} seconds") | true |
0dea9e43ee7c33731ce954ac2eef9b6d661fb30a | holdbar/misc_python_stuff | /patterns/creational_patterns/abstract_factory.py | 1,404 | 4.3125 | 4 | # -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
class Beer(metaclass=ABCMeta):
pass
class Snack(metaclass=ABCMeta):
@abstractmethod
def interact(self, beer: Beer) -> None:
pass
class AbstractShop(metaclass=ABCMeta):
@abstractmethod
def buy_beer(self) -> Beer:
pass
@abstractmethod
def buy_snack(self) -> Snack:
pass
class Tuborg(Beer):
pass
class Staropramen(Beer):
pass
class Peanuts(Snack):
def interact(self, beer: Beer) -> None:
print("We've drunk {} and eaten peanuts".format(
beer.__class__.__name__))
class Chips(Snack):
def interact(self, beer: Beer) -> None:
print("We've drunk {} and eaten chips".format(
beer.__class__.__name__))
class ExpensiveShop(AbstractShop):
def buy_beer(self) -> Beer:
return Tuborg()
def buy_snack(self) -> Snack:
return Peanuts()
class CheapShop(AbstractShop):
def buy_beer(self) -> Beer:
return Staropramen()
def buy_snack(self) -> Snack:
return Chips()
if __name__ == "__main__":
expensive_shop = ExpensiveShop()
cheap_shop = CheapShop()
print("OUTPUT:")
beer = expensive_shop.buy_beer()
snack = cheap_shop.buy_snack()
snack.interact(beer)
beer = cheap_shop.buy_beer()
snack = expensive_shop.buy_snack()
snack.interact(beer)
| true |
1e68f059b845813c5070ba6c5ec2e050c96b6050 | spettigrew/cs2-fundamentals-practice | /mod1-Python_Basics/basic_operations.py | 388 | 4.34375 | 4 | """
1. Assign two different types to the variables "a" and "b".
2. Use basic operators to create a list that contains three instances of "a" and three instances of "b".
"""
# Modify the code below to meet the requirements outlined above
a = "Goodbye "
b = "Lambda"
both = a + b
print(both)
a_list = [a] * 3
b_list = [b] * 3
my_list = a_list + b_list
print(my_list)
print(len(my_list)) | true |
a9da736b044dcc59d74510bb1cb4527c12ef3e86 | seb-patron/Algorithms-and-Data-Structures | /mergesort/mergesort.py | 1,176 | 4.15625 | 4 | # implements week 1 merge sort
# Pseudocode
#
# recursive call
# if length of array > 1:
# mergeSort(1st half), mergeSort(2nd half)
#
#
# merge:
# c = outputArray a = 1st sorted Array(n/2) b = 2nd sorted Array(n/2)
#
# i = 1; j = 1
# for k = 1 to n
# if a(i) < b(j):
# c(k) = a(i)
# i++
# else if a(i) > b(j)
# c(k) = b(j)
# j++
# end
# return c
class Merge:
def __init__(self, array):
self.array = array
def sort(self):
return self.mergeSort(self.array)
def mergeSort(self, array):
mid = int(int(len(array))/2)
if len(array) < 2:
return array
a = self.mergeSort( array[ : mid] )
b = self.mergeSort( array[mid :] )
return self.merge(a, b)
def merge(self, a, b):
result = list()
i = 0; j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i = i + 1
else:
result.append(b[j])
j = j + 1
result += a[i:]
result += b[j:]
return result
| false |
3dcc4ac57b0ce744901cf619bb131b7410435c04 | RAMKUMAR7799/Python-program | /Beginner/Gnumbers.py | 286 | 4.25 | 4 | num1=int(input("Enter your number"))
num2=int(input("Enter your number"))
num3=int(input("Enter your number"))
if(num1>=num2 and num1>=num3):
print(num1,"is greatest number")
elif(num2>=num1 and num2>=num3):
print(num2,"is greatest number")
else:
print(num3,"is greatest number")
| true |
c820a8e1c9d53f94054205ccd56514df45e95322 | Eric-Xie98/CrashCoursePython | /CrashCoursePython/Chapter 8/PassingRandom.py | 2,246 | 4.84375 | 5 | ## Sometimes we don't know how many arguments we're going to pass into the function, so Python let's use the *
## and create a tuple that takes in arguments:
def make_pizza(*toppings):
for topping in toppings:
print(topping)
## No matter how many arguments are given, Python treats them the same and packs them into the tuple
make_pizza('macaroni', 'bacon', 'pepperoni', 'joe')
print()
make_pizza('me')
## If we want the function to accept both positional and arbitrary arguments, the arbitrary argument must
## go last, so it can have an unlimited number:
def userList(ageAll, *names):
print("Age: " + str(ageAll))
print("Names: ", end = '')
for name in names:
print(name.title(), end = " ")
userList(17, 'eric', 'max', 'alina', 'edwin', 'nate')
## Now that we know arbitrary arguments, what about arbitrary keyword arguments? Oh yeah.
## You can now write functions that accept as many key value pairs as necessary:
print()
def buildProfile(first, last, **user_info): ## double asterisk indicates arbitrary keyword arguments
profile = {}
profile['first_name'] = first.title()
profile['last_name'] = last.title()
for key, value in user_info.items():
profile[key] = value
return profile
## This time Python creates a dictionary for the arbitrary keyword arguments. Similar to the previous arbitrary,
## we access the elements this time like a dictionary
user1 = buildProfile('albert', 'einstein', location = 'princeton', age = '67', field = 'physics')
print(user1)
## Exercises
print()
def sandwich(*ingredients):
for ingredient in ingredients:
print("Adding: " + ingredient.title())
sandwich('mayo', 'tomato')
sandwich('ham', 'cheese', 'bacon', 'dick', 'balls')
sandwich('fettucini')
print()
print(buildProfile('eric', 'xie', age = '19', university = 'duke', location = 'home'))
print()
def carProfile(manufacturer, model_name, **car_info):
profile = {}
profile['manufacturer'] = manufacturer
profile['model_name'] = model_name
for key, value in car_info.items():
profile[key] = value
return profile
print(carProfile('honda', 'toyota s4 rc', color = 'red', wheels = 4, convertible = True))
| true |
fe6c2bc5f7c1e6bfed845a6ca016675fc6c0246a | Eric-Xie98/CrashCoursePython | /CrashCoursePython/Chapter 10/writingFile.py | 2,196 | 4.5625 | 5 | ## One of the simplest ways to save data is to write to a file. Even after the program is closed, you can
## still look at the output file in its stored location as well as share it to others. You can also
## write programs that read it back into memory and work with it again later.
# To write in a file, we use the open() method and its two arguments:
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
file_object.write("Graphic design is my passion.\n")
# The open method's first argument is the filename while the second argument is the mode we want to open the file in:
# There is ('r') read mode, ('w') write mode, ('a') append mode, and ('r+') read and write mode.
# By default, the open method is in read mode.
# If the file we're opening doesn't exist, the open method will automatically create it for us. However, be careful when
# you open an existing file in write mode, it can erase the previous contents and return a new file_object.
# These lines should create a new file with the said line inside. If we want to put numerical numbers inside, we'll need to use str()
## With the 'a' append mode, we can add more lines to the file without erasing the pre-existing data:
with open(filename, 'a') as file_object:
file_object.write("This shows that I can append to what was written before.")
gameName = 'valorant.txt'
with open(gameName, 'w') as file_object:
file_object.write('Valorant is a shit game.')
## Exercises
print()
active = True
with open('guest.txt', 'a') as file_object:
while active:
print("Type in 'q' at anytime to quit the program")
name = input("Please write your name into the guestbook: ")
if name == 'q':
active = False
else:
file_object.write(name.title() + "\n")
active2 = True
with open('reasons.txt', 'a') as file_object:
while active2:
reason = input("Write a favorite reason why you do programming: ")
if reason == 'quit':
active2 = False
else:
file_object.write(reason + '\n')
| true |
456d3ff0b114ec6d98f6e3a3628d786a2b36a17e | Eric-Xie98/CrashCoursePython | /CrashCoursePython/Chapter 4/Looping.py | 1,525 | 4.59375 | 5 | ## Rather than individually index each element in a list, we can utilize a for loop:
numbers = ["1", '2', '3', '4']
for number in numbers:
print("I'm on number " + number)
print("\n")
names = ['Eric', 'Max', 'Bryan', 'Allinn', 'Nate', 'Edwin']
for i in range(0, 3):
print("Wow, " + names[i] + " that was a great trick!")
print("The index is: " + str(i))
print("Thanks for coming to our dogshit magic show!")
## Because Python uses indentation to determine whether something is part of a loop, it's imperative to write neatly formatted code
## that is easy to read An indentation error can occur when we don't indent after creating a for loop.
## Furthermore, forgetting to indent additional lines in a for loop can result in a logic error, where the code will compile and run,
## but it won't do what you wanted to. In this case, a line that should run each iteration of the loop will only run once after the loop finishes.
## It's also possible to add unnecessary indentations, which cause an unexpected indentation error.
print("\n")
for i in range(0, 1):
print("The colon after the for loop tells the compiler to read the next line as part of the loop.")
## Exercises
print("\n")
pizzas = ['cheese', 'bacon', 'extra cheesy']
for pizza in pizzas:
print("I really like " + pizza + " pizza!")
print("Pizza is delicious!")
print("")
pets = ['dog', 'cat', 'hamster']
for pet in pets:
print("A " + pet + " would make a great pet!")
print("All of these animals would make great pets.")
| true |
e480d9ce1b35de66f0393131ef8befc18dc99dc9 | Eric-Xie98/CrashCoursePython | /CrashCoursePython/Chapter 7/whileLists.py | 2,851 | 4.46875 | 4 | ## While loops can be used with lists and dictionaries and allows for modification while traversing them
## We can move items in one list to another using a while loop:
unconfirmed_users = ['eric', 'max', 'allinn']
confirmed_users = []
while unconfirmed_users:
current = unconfirmed_users.pop()
print("Verifying unconfirmed user: " + current.title())
confirmed_users.append(current)
print(confirmed_users)
print(unconfirmed_users) ## should be empty now
## As you can see, the .pop() lets us remove elements from a list starting with the last item. As a result, the confirmed_users list
## is now the reverse of the original list and uncofirmed_users should be empty
## What do we do when we want to remove every instance of an element in a list?
shopping_list = ['milk', 'eggs', 'bacon', 'eggs', 'chips', 'water', 'eggs']
while 'eggs' in shopping_list:
shopping_list.remove('eggs')
## The while loop checks whether or not 'eggs' is in the list, and if there is an instance, it removes it.
## Otherwise, the loop will stop when there are no more instances left
print(shopping_list) # should have no 'eggs' left
## We can also use input() to fill in a dictionary in conjunction with a flag and a while loop:
responses = {}
active = True ## flag
while active:
name = input('What is your name? ')
place = input('Please input what your favorite place is: ')
responses[name] = place
rerun = input('Does anyone else want to take the poll? (Y/N) ')
if rerun.lower() == 'n':
active = False ## set flag to false when no one else to take poll
## now that the poll is done, print results:
print("\n-- Poll Results -- ")
for name, place in responses.items():
print(name.title() + "'s favorite place is " + place.title())
## Exercises
print()
request = ['pastrami', 'panini', 'ham and cheese', 'meatball sub']
finished = []
while request:
done = request.pop()
print("One " + done + " sandwich coming right up!")
finished.append(done)
print(finished)
print()
sandwich_orders = ['pastrami', 'panini', 'ham and cheese', 'meatball sub']
sandwich_orders.append('pastrami')
sandwich_orders.append('velveeta')
sandwich_orders.append('pastrami')
print("The deli has run out of pastrami")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
print()
polled = {}
pollingActive = True
while pollingActive:
user = input("What's your name? ")
food = input("What's your favorite food? ")
polled[user] = food
extra = input("Want to run the program again? (Y/N): ")
if extra.lower() == 'n':
print("Exiting program...")
pollingActive = False
print("\n-- Poll Results -- ")
for user, food in polled.items():
print(user.title() + "'s favorite food is " + food.title())
| true |
36b74c1fc61414c30e9d401c3c5dfb90f6c103de | crenault73/training | /python/tutograven/src/04_list/cre_split.py | 282 | 4.125 | 4 | # Exemple: Liste à partir de split
# Récuppération d'une liste à partir d'une chaine de la forme: email-pseudo-motdepasse
text = input("Entrer une chaine de la forme: email-pseudo-motdepasse ").split("-")
print(text)
print("Salut {}, ton e-mail est {}".format(text[1],text[0]))
| false |
66744cf2fbb266be280279cce690d21209609fed | VladShokun/lazy_python | /lazypython09.py | 1,214 | 4.4375 | 4 | """
Метод срок
string.isalpha() - все символы алфавитные
string.isalnum() - и алфавитные и цефровые символы
string.isdigit() - все символы в строке евляються цифрами
string.islower() - все символы из нижнего регистра
string.isupper() - все символы из верхнего регистра
string.istitle() - проверка на то что каждое слово начинается с буквы верхнего регистра
string.isspace() - проверка на наличие пробела
"""
string = "AAaa"
print(string.isalpha())
string = "AAaa001"
print(string.isalnum())
string = "02354"
print(string.isdigit())
string = "oerirnvpwin2"
print(string.islower())
string = "NEIFNIEVNEWS11"
print(string.isupper())
string = "A Table Is Round"
print(string.istitle())
string = " "
print(string.isspace())
name = input("Hello this is a string validator. What is your name?: ")
a = input(name + ", type some symbols and hit Enter please: ")
if a.isdigit():
print("You enter only digits.")
else:
print("You entered one or more non-digits or not only digits.") | false |
cacecdc7e6b9ccb7efe90f953200e0cb59ec2d8e | csumithra/pythonUtils | /03_generate_dict.py | 457 | 4.21875 | 4 | #With a given integral number n, write a program to generate a dictionary that contains (i, i x i) such that is an integral number
# between 1 and n (both included). and then the program should print the dictionary.
# Suppose the following input is supplied to the program: 8
#Then, the output should be:
#{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
num = int(input("Enter a number: "))
my_dict = {i: i*i for i in range(1, num)}
print(my_dict) | true |
ee945e5b0086fee77ce3b3d30443758ddd06c3e3 | csumithra/pythonUtils | /23_24_sqaure_number.py | 246 | 4.15625 | 4 | #Write a method which can calculate square value of number
def square_num(num):
'''
Returns the square value of the input number.
'''
return num ** 2
print(square_num.__doc__)
print(square_num(int(input('Enter a number: '))))
| true |
65640293c12bcfc29e9286d84e48502afaf8a9d8 | csumithra/pythonUtils | /18_CheckPassword_validity.py | 1,091 | 4.1875 | 4 | # Following are the criteria for checking the password:
# At least 1 letter between [a-z]
# At least 1 number between [0-9]
# At least 1 letter between [A-Z]
# At least 1 character from [$#@]
# Minimum length of transaction password: 6
# Maximum length of transaction password: 12
# Your program should accept a sequence of comma separated passwords and will check them according to the above criteria.
# Passwords that match the criteria are to be printed, each separated by a comma.
# Example
## If the following passwords are given as input to the program:
# ABd1234@1,a F1#,2w3E*,2We3345
# Then, the output of the program should be: ABd1234@1
import re
passwords = input("Enter few passwords: ").split(',')
print(passwords)
for pwd in passwords:
if not re.search('[a-z]', pwd):
continue
if not re.search('[A-Z]', pwd):
continue
if not re.search('[0-9]', pwd):
print("No numbers present", pwd)
continue
if not re.search('[$#@]', pwd):
continue
if (not len(pwd) > 6) or (not len(pwd) < 12):
continue
print(pwd)
| true |
cfe9703339f8e79ca07db80d9cb713aff1def06d | enzosison/lab0.1 | /lab-0-enzosison-master/planets.py | 439 | 4.1875 | 4 | # float string -> float
# Given earth weight and planet, returns weight on provided planet
def weight_on_planets(pounds, planet):
# write your code here
return 0.0
if __name__ == '__main__':
pounds = float(input("What do you weigh on earth? "))
print("\nOn Mars you would weigh", weight_on_planets(pounds, 'Mars'), "pounds.\n" +
"On Jupiter you would weigh", weight_on_planets(pounds, 'Jupiter'), "pounds.") | true |
c1b8c156121f86fdf828f400df08ae45d3e8dd56 | nelliher/IS51Test2 | /test_2.py | 1,466 | 4.15625 | 4 |
"""
This program will display the class exam averages based on the total number of grades. The first calculation will display the number of grades.
The second calculation will display the average of the total grades. The third calculation will display the total percentage of the grades abover average.
There will be three functions. The first function will initialize the apllication. The second function will calcualte the total percentage above average.
The third function will calculate the percentage of total grades above average.
Function 1 will initialize the application.
Function 2 will sum all the total number of grades.
Function 3 will multiply all of the grades by 100 and divide it by the total number of grades.
It will output the percentage above average. And after the code has ran, it will output the percentage of the total grades above average.
"""
"""
# funtion1
add total number of grades
# function2
add sum of all grades / total number of grades
# function3
n*100 / len(grades)
main
"""
infile = open("Final.txt" , 'r')
grades = [line.rstrip() for line in infile]
infile.close()
for i in range(len(grades)):
grades[i] = int(grades[i])
average = sum(grades) / len(grades)
num = 0
for grade in grades:
if grade > average:
num += 1
print("Number of grades:" , len(grades))
print("Average grade:" , average)
print("Percentage of grades above average: {0:.2f}%"
.format(100 * num / len(grades)))
| true |
96ec75d796df27044f683ff8b16a0d53b86c74b5 | hkmangla/ML_mini_projects | /quiz.py | 908 | 4.25 | 4 | """Count words."""
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# TODO: Count the number of occurences of each word in s
l = s.split();
occurrenceList = {}
for i in l:
if i in occurrenceList.keys():
occurrenceList[i] += 1
else:
occurrenceList[i] = 1
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
top_n = occurrenceList.items()
top_n.sort(key=lambda score: (-score[1],score[0]))
# top_n.sort()
# print top_n[:n]
# TODO: Return the top n words as a list of tuples (<word>, <count>)
return top_n[:n]
def test_run():
"""Test count_words() with some inputs."""
print count_words("cat bat mat cat bat cat", 3)
print count_words("betty bought a bit of butter but the butter was bitter", 3)
if __name__ == '__main__':
test_run()
| true |
98bbbc24bcb57f9ccfe76b1532cec9ea83e35558 | MalAnna/geekbrains-homework | /algorithms python/lesson2/task8.py | 872 | 4.1875 | 4 | # 8.Посчитать, сколько раз встречается определенная цифра в введенной
# последовательности чисел. Количество вводимых чисел и цифра, которую
# необходимо посчитать, задаются вводом с клавиатуры.
digit_count = 0
print('Сколько чисел хотите вводить?')
count = int(input('count = '))
print('Какую цифру хотите найти?')
digit = int(input('digit = '))
for i in range(1, count+1):
print(f'Введите {i} число')
num = int(input())
while num // 10 != 0:
if num % 10 == digit:
digit_count += 1
num = num // 10
if num == digit:
digit_count += 1
print(f'Цифра {digit} найдена {digit_count} раз(а)') | false |
9f94c8ea9a5278d3b57bc8e9eebf413e370dd6cf | 233-wang-233/python | /day6/face_object.py | 1,249 | 4.25 | 4 | class Student(object):
# __init__是一个特殊方法用于在创建对象时进行初始化操作
# 通过这个方法我们可以为学生对象绑定name和age两个属性
def __init__(self,name,age):
self.name=name
self.age=age
def study(self,course_name):
print('%s正在学习%s.'%(self.name,course_name))
# PEP 8要求标识符的名字用全小写多个单词用下划线连接
# 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识)
def watch_movie(self):
if self.age<18:
print('%s只能观看《熊出没》.'%self.name)
else:
print('%s只能观看《战机》.' % self.name)
def main():
stu1=Student('233-wang-233',23)
stu1.study('python')
stu1.watch_movie()
if __name__=="__main__":
main()
'''
访问可见性问题
希望属性是私有的,在给属性命名时可以用两个下划线作为开头
'''
class Test:
def __init__(self,foo):
self.__foo=foo
def __bar(self):
print(self.__foo)
print('__bar')
def main():
test =Test('hello')
test._Test__bar()
print(test._Test__foo)
if __name__=='__main__':
main() | false |
01e06eb1c3001bddefaa09ced8952b3bb17c6b8d | SCollinA/python104 | /square2.py | 901 | 4.34375 | 4 | # Ask user for length of square. Print square using one * character per unit length of square.
BAD_INPUT = True # set flag for asking for user input
ERROR_MESSAGE = "Bad user input." # message if bad input received
while BAD_INPUT: # continue to ask for input until is is int
try: # prompt user for size of square
square_length = int(input("How big is the square? "))
BAD_INPUT = False # good input received, change flag, except loop
except:
print(ERROR_MESSAGE) # inform user of bad input
side1 = square_length # first side of square, rows
while side1 > 0: # until all rows printed
side2 = square_length # second side of square, cols
while side2 > 0: # until all cols printed
print('*', end='') # print each * without starting new line
side2 -= 1 # decrement cols counter
print() # start new line
side1 -= 1 # decrement rows counter | true |
53266a0ba7e13ea1c9ffe3cb4af43cec27cb8be5 | SCollinA/python104 | /square.py | 416 | 4.15625 | 4 | # Print a 5x5 square of * characters
row_counter = 5 # number of rows
while row_counter > 0: # loop through all rows
col_counter = 5 # number of columns
while col_counter > 0: # loop through all cols
print('*', end='') # print one * per col without starting new line
col_counter -= 1 # decrement cols remaining
print() # move to new line
row_counter -= 1 # decrement rows remaining
| true |
5850c4b0d8dfc977e0b94d88313474deafaa4241 | chigginss/HackerRank | /cracking_the_coding_interview/python_solutions.py | 490 | 4.3125 | 4 |
# Cracking the Coding Interview Problems from HackerRank
""" 1) Array Left Rotation
A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5]
then the array would become [3,4,5,1,2].
Given an array a of n integers and a number, d, perform d left rotations on the array.
Return the updated array to be printed as a single line of space-separated integers."""
def rotate_array(): | true |
b910a79338e52c34ca9f005ca5a8c9b0894edbf9 | gozeberke/python_temel_projeler | /loop-method.py | 741 | 4.28125 | 4 | #range
#1 den başla 10a kadar git
'''
for item in range(1,10):
print(item)
'''
#2 den başla 2 şer 2 şer artarak 20 ye kadar git
for m in range(2,20,2):
print(m)
#döngünün dışında da kullanılabilir
#1 den başlayıp 10 a kadar 2 şer 2 şer artar bunun list çevririr ve ekrana yazdırır.
print(list(range(1,20,2)))
#enumerate
greeting=('HELLO')
index=0
for letter in greeting:
print(f'index: {index} letter: {letter}')
index +=1
greeting=('HELLO')
for index,letter in enumerate(greeting):
print(f'index: {index} letter: {letter}')
greeting=('HELLO')
for item in enumerate(greeting):
print(item)
#zip
list1=[1,2,3,4,5]
list2=['a','b','c','d','e']
print(list(zip(list1,list2))) | false |
da2733853971436ec9f3d09c8bb0b34d930186b4 | sourcery-ai-bot/Python-Curso-em-Video | /python_exercicios/desafio041.py | 926 | 4.15625 | 4 | # A Confederação Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade:
# - Até 9 anos: MIRIM
# - Até 14 anos: INFANTIL
# - Até 19 anos: JÚNIOR
# - Até 25 anos: SÊNIOR
# - Acima de 25 anos: MASTER
from datetime import date
anonasc = int(input('Informe o ano de nascimento do atleta: '))
anoatual = date.today().year
idade = anoatual-anonasc
if idade <= 9:
print('A idade do atleta é {} anos e sua categoria é a MIRIM.'.format(idade))
elif idade <= 14:
print('A idade do atleta é {} anos e sua categoria é INFANTIL.'.format(idade))
elif idade <= 19:
print('A idade do atleta é {} anos e sua categoria é JÚNIOR.'.format(idade))
elif idade <= 25:
print('A idade do atleta é {} anos e sua categoria é SÊNIOR.'.format(idade))
else:
print('A idade do atleta é {} anos e sua categoria é MASTER.'.format(idade))
| false |
0af7622fa9152a670732e2e36931070ec8640447 | Bichwaa/xtractor | /xtractor/xtractor/extractor.py | 1,032 | 4.125 | 4 | '''
This module contains functions which get the text content of an xml file, strips it of its xml tags and returns what is left.
the get_text function can also parse text from ordinary text files (format txt) and html files.
'''
import re, fire
def get_text(enc='utf-8', filepath=None):
"""returns text from a file"""
if filepath == None:
file = input("Provide path to the file to be extracted: \n")
else:
file = filepath
f = open(file,'r',encoding = enc)
return f.read()
def strip_tags(text):
'''Goes through text and removes all xml tags from it'''
pattern = re.compile(r"<.*?>")
return pattern.sub('',text)
def extract(path_to_xml, destination=""):
t = get_text(filepath = path_to_xml)
stripped = strip_tags(t)
print(stripped)
if destination != "": #if a destination for extracted text file is provided
f = open(destination+"\\recovered.txt", "a")
f.write(stripped)
f.close()
return stripped
| true |
90c3f5756220e27d6ed387d351a987a7de3d006a | vvveracruz/ossu | /mit-intro-to-cs/ps0/ps0.py | 434 | 4.21875 | 4 | # Write a program that does the following in order:
# 1. Asks the user to enter a number “x”
# 2. Asks the user to enter a number “y”
# 3. Prints out number “x”, raised to the power “y”.
# 4. Prints out the log (base 2) of “x”.
import numpy as np
x = float( input( ' Enter a number x: ' ) )
y = float( input( ' Enter a number y: ' ) )
print( ' x**y = ' + str(x**y) )
print( ' log(x) = ' + str(np.log2(x) ))
| true |
a407b5c53068955c7b60a03899b001fb4804777c | 600000rpmaker/funutils | /keybyvalue.py | 717 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
def get_key_by_value(dict, value):
for k, v in dict.items():
if v == value:
print "Found key: \"" + str(k) + "\" with type: " + str(type(k)) + " for the specified value: \"" + str(value)+"\"" + " in the dict: " + str(dict)
return k
else:
print "Searched key for the value: \"" + str(value) + "\" not found in the dict: " + str(dict)
# Testing
dictionary = {1: '1', 2: '2', 3: '3'}
get_key_by_value(dictionary, '1')
#get_key_by_value(dictionary, '2')
#get_key_by_value(dictionary, '3')
#get_key_by_value(dictionary, 4)
#get_key_by_value(dictionary, '3')
#get_key_by_value(dictionary, '2')
#get_key_by_value(dictionary, '1') | false |
c9f3079ae8a217c5a860e446bae77d285b09f343 | sohailshaikh1432/BasicPrograms | /FactorialFind.py | 342 | 4.21875 | 4 | def main():
# declaring vairiables
input = userInput
fact = 1
#!For loop to find factorial of given input
for i in range(1, input+1):
fact= fact*i
print("Factorial of ", input ," is :", fact)
if __name__ == "__main__":
# Taking input from the user
userInput = int(input("Enter number : "))
main() | true |
636dc6d3956a31975061555eb94baf2380c0bf50 | Matvey2009/HardChildhood | /Python/Lessons/Lesson0.7 - операторы .py | 1,529 | 4.15625 | 4 | # Операторы
x = 5 #input("Ввод в консоль - ")
print("Конвертация в число - ", int(x))
print("Конвертация в дробное число - ", float(x))
print("")
x = "Hello Word"
print("Длина строки - ", len(x))
print("Конвертация в строку - ", str(len(x)) + " - Штук")
print("Транформация в список - ", list(x))
print("Транформация в картеж - ", tuple(x))
print("")
colors = [("Красный", 2), ("Зелёный", 1), ("Синий", 3), ("фиолетовый", 5)]
print("Cписок картежей", colors)
print("Транформация", colors)
colors = dict(colors)
print("")
x = [11, 201, 201, 440, 5, 6, 702, 8, 9, 201]
print("Список", x)
print("Минимальное значение", min (x))
print("Максимальное значение", max(x))
print("Сортировка списка", sorted(x))
print("Обратная сортировка списка", sorted(x, reverse = True))
print("Сумма списка", sum(x))
print("Сумма цифр", sum([1, 2 ,3 ,4 ,5 ,6]))
print("Сумма цикла списка", sum(i ** 2 for i in x))
print("")
print("Набор", set(x))
print("фиксированый набор", frozenset(x))
print("")
print("Bool любого числа", bool(-125))
print("Bool числа 0", bool(0))
print("Bool любого симвала", bool("-125"))
print("Bool пустоты", bool(""))
print("")
help(str.split)
input() | false |
3826627ba652855ef9b4266e245487d6bbfae012 | 97joseph/Digital-Intelligence-2 | /hw2problem2.py | 2,813 | 4.1875 | 4 | # PUT YOUR NAME HERE
# PUT YOUR SBU ID NUMBER HERE
# PUT YOUR NETID (BLACKBOARD USERNAME) HERE
#
# IAE 101 (Fall 2021)
# HW 2, Problem 2
def frequency(c, s):
# ADD YOUR CODE HERE
return -1 # CHANGE OR REMOVE THIS LINE
# 1. First, count the number of times that c appears in s.
c_occ = 0
for ch in s:
if ch==c:
c_occ += 1
# 2. Second, compute the total number of characters in s.
length_s = len(s)
# 3. Third, divide the result of the step 1 by the result of step 2
freq = c_occ/length_s
# 4. Fourth, multiply the result of step 3 by 100.
freq_perc = freq*100
# 5. Fifth, round the result to two decimal places
freq_perc = round(freq_perc, 2)
# Return the final value as the result of the function
return freq_perc
result = frequency("i", "Mississippi")
print("The relative frequency is "+str(result)+"%.")
# DO NOT DELETE THE FOLLOWING LINES OF CODE! YOU MAY
# CHANGE THE FUNCTION CALLS TO TEST YOUR WORK WITH
# DIFFERENT INPUT VALUES.
if __name__ == "__main__":
s1 = "supercalifragilisticexpialidocious"
test1 = frequency("a", s1)
print("s1:", s1)
print("frequency(\"a\", s1) is:", test1)
print()
s2 = "antidisestablishmentarianism"
test2 = frequency("i", s2)
print("s2:", s2)
print("frequency(\"i\", s2) is:", test2)
print()
s3 = "mississippi"
test3 = frequency("i", s3)
print("s3:", s3)
print("frequency(\"i\", s3) is:", test3)
print()
s4 = "I could have become a mass murderer after I hacked my governor\
module, but then I realized I could access the combined feed of entertainment\
channels carried on the company satellites. It had been well over 35000\
hours or so since then, with still not much murdering, but probably, I\
don't know, a little under 35000 hours of movies, serials, books, plays,\
and music consumed. As a heartless killing machine, I was a terrible failure."
test4 = frequency("e", s4)
print("s4:", s4)
print("frequency(\"e\", s4) is:", test4)
print()
s5 = "It was the best of times, it was the worst of times, it was the age of \
wisdom, it was the age of foolishness, it was the epoch of belief, it was the \
epoch of incredulity, it was the season of Light, it was the season of \
Darkness, it was the spring of hope, it was the winter of despair, we had \
everything before us, we had nothing before us, we were all going direct to \
Heaven, we were all going direct the other way – in short, the period was so \
far like the present period, that some of its noisiest authorities insisted \
on its being received, for good or for evil, in the superlative degree of \
comparison only."
test5 = frequency('t', s5)
print("s5:", s5)
print("frequency(\"t\", s5) is:", test5)
print()
| true |
2ab29e82d6febd71753b2cf4920f1f85760374e5 | sm-sarkar/Python-28June | /day3.py | 632 | 4.34375 | 4 | #CALCULATOR TO PERFORM ALL ARITHMETIC OPERATIONS
'''USER INPUT'''
print("Welcome To Python Calculator")
a = int(input("Enter First Number"))
b = int(input("Enter Second Number"))
'''ADDITION'''
s = a+b
print( f"The sum of {a} and {b} is {s}")
'''SUBTRACTION'''
m = a-b
print( f"The difference of {a} and {b} is {m}")
'''MULTIPLICATION'''
p = a*b
print( f"The product of {a} and {b} is {p}")
'''DIVISION'''
q = a/b
print( f"The quotient of {a} and {b} is {q}")
'''MODULUS'''
r = a%b
print( f"The remainder of {a} and {b} is {r}")
'''EXPONENT'''
e = a**b
print( f"{a} to the power of {b} is {e}")
| false |
ea490952881942ccb298d4703bc51089fb4368c8 | deminovamv/lesson1 | /list.py | 683 | 4.1875 | 4 | #Задание
# Создайте список из чисел 3, 5, 7, 9 и 10.5
# Выведите содержимое списка на экран
# Добавьте в конец списка строку "Python"
# Выведите длину списка на экран#
phones = [3, 5, 7, 9 , 10.5]
print(phones)
phones.append("Python")
print(phones)
print(len(phones))
print(f'Начальный элемент списка: {phones[0]}')
print(f'последний элемент списка: {phones[-1]}')
print(f'элементы списка со второго по четвертый включительно: {phones[1:4]}')
phones.remove("Python")
print(phones) | false |
78368a525bcf610efa7f1d09ddf571bc89074fa1 | Shwetapatil05/new-python | /control_flow_statements/for_loop.py | 1,198 | 4.21875 | 4 | #-------------------------------------------------------
#Description : for loop
#syntax :
# for item in items:
# statements;
#About : Iterates over single character of a string
#-------------------------------------------------------
player = 'sudeep';
print("------------Iterating over a String----------------");
for i in player:
print(i);
#-------------------------------------------------------
#Description : for loop
#syntax :
# for item in items:
# statements;
#About : iterates over a list
#-------------------------------------------------------
teams = ['RCB','MI','KXIP','RR','CSK'];
print("--------------Iterating over a list----------------");
for team in teams:
print(team);
#-------------------------------------------------------
#Description : for loop
#syntax :
# for key,value in parameters.items():
# statements;
#About : Iterates over a associative array
#-------------------------------------------------------
players = {'RCB':'Virat Kohli','CSK':'MSD','Rahul':'Punjab'};
print("----------Iterating over a associate array---------------");
for team,player in players.items():
print(team,"->",player);
| true |
ad7ade34ea80f05b2d687e3eebd3200ddef14af4 | noy20-meet/meet2018y1lab7 | /fun2.py | 1,471 | 4.1875 | 4 |
import turtle
turtle.goto(0,0)
UP = 0
DOWN= 1
LEFT= 2
RIGHT= 3
SPACE= 4
direction = None
pen_is_up = False
def up():
global direction
direction= UP
print("You pressed the up key.")
on_move(10, 20)
def down():
global direction
direction= DOWN
print("You pressed the down key.")
on_move(10, 20)
def left():
global direction
direction= LEFT
print("You pressed the left key.")
on_move(10, 20)
def right():
global direction
direction= RIGHT
print("You pressed the right key.")
on_move(10, 20)
def space():
global direction
direction= SPACE
print("You pressed the space key.")
on_move(10, 20)
turtle.onkey(up, "Up")
turtle.onkey(down, "Down")
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.onkey(space, "space")
turtle.listen()
def on_move(x, y):
global pen_is_up
turtlepos =turtle.position()
turtlexpos = turtlepos[0]
turtleypos = turtlepos[1]
if direction==UP:
turtle.goto(turtlexpos, turtleypos+y)
if direction==DOWN:
turtle.goto(turtlexpos, turtleypos-y)
if direction==LEFT:
turtle.goto(turtlexpos-x, turtleypos)
if direction==RIGHT:
turtle.goto(turtlexpos+x, turtleypos)
if direction==SPACE:
if pen_is_up:
turtle.pendown()
pen_is_up= False
else:
turtle.penup()
pen_is_up= True
turtle.mainloop()
| false |
b45b49e7fa5d900b3bd741393e6cd48cc6f05813 | countvajhula/composer | /composer/timeperiod/utils.py | 710 | 4.21875 | 4 | from datetime import timedelta
def get_next_day(date):
"""Given a date, return the next day by consulting
the python date module
:param :class:`datetime.date` date: The date to increment
:returns :class:`datetime.date`: The next date
"""
next_day = date + timedelta(days=1)
return next_day
def get_next_month(date):
"""Given a date, return the start of the next month by consulting
the python date module
:param :class:`datetime.date` date: The date to increment
:returns :class:`datetime.date`: The start of the next month
"""
original_month = date.month
while date.month == original_month:
date = date + timedelta(days=1)
return date
| true |
8e47468aeab29400f67729f5d8908eb4c23e22f7 | Itz-Cook1e/College-Mailbox-File | /main.py | 1,036 | 4.25 | 4 | # Assignment:
# Write a program to prompt the user to provide a file name
# (use the file that is provided, mbox-short.txt) read through the file, and print the first 50 characters of each line that begins with 'Subject'
# (line by line). Lastly, provide a count of the number of these lines.
# Your program should include error handling in case the file is not found.
# Get file name
file_name = input('Enter the file name: ')
# Make sure file can be opened
try:
file_opened = open(file_name)
# Let user know file couldnt be opened
except FileNotFoundError:
print(f"File '{file_name}' cannot be opened!")
raise SystemExit
# Line number starter
n = 0
# For loop to print lines starting with 'Subject' and only the first 50 characters of said line
for line in file_opened:
if line.startswith("Subject"):
n = n + 1
print(f'{line[0:49]}')
# Print the ammount of lines that started with 'Subject'
print(f"Lines begin with 'Subject' {n} times.")
# Comment with name, date, and assignment name redacted
| true |
55982d0837bb9a8288fb9261c5ea7f00690f1327 | PROxZIMA/Python-Projects | /User_Packages/amult.py | 236 | 4.125 | 4 | def mult():
L=[]
b=1
num=int(input("Enter how many numbers you are multiplying : "))
for i in range(num):
n=float(input("Enter the numbers : "))
L.append(n)
b=b*n
print('Multiplication of the numbers is =',b) | true |
ce3d1049e7150520a9695f3343e19ff00918d3ec | vinhlee95/oop-python | /instance_class_static_methods/main.py | 1,663 | 4.375 | 4 | from typing import List
class MyClass:
foo = "bar"
def method(self):
"""
Instance method could be invoked only from a class instance
It could modify the instance's propery, but not the class itself
"""
return f"instance method called. foo is {self.foo}"
@classmethod
def classmethod(cls):
"""
Class method points to the class, not the object instance when this method is called
It thus could be invoke from the class itself without creating a new instance
Class method can modify the class
"""
old_foo = cls.foo
cls.foo = "foo"
return f"class method called. foo changed from {old_foo} to {cls.foo}"
@staticmethod
def staticmethod():
"""
Staticmethod does not modify class or instance state
and it is independent from everything else
-> Because of ˆ, this method is also easy to test
"""
return 'static method called'
def print_my_class():
print(MyClass().method()) # need to create a new object instance to call instance method
# No need to create new instance to invoke classmethod() and static method()
print(MyClass.classmethod())
print(f"New class instance. foo is now {MyClass().foo}")
print(MyClass.staticmethod())
# print_my_class()
"""
Factory functions
Used to create interfaces for variations of a data class
"""
class Pizza:
mozzarella = "mozzarella"
tomatoes = "tomatoes"
def __init__(self, ingredients: List[str]) -> None:
self.ingredients = ingredients
def __repr__(self) -> str:
return f"Pizza {self.ingredients}"
@classmethod
def margherita(cls):
return cls([cls.mozzarella, cls.tomatoes])
def print_pizza():
print(f"I want to have {Pizza.margherita()}")
# print_pizza()
| true |
df816e3e75ebdaf4d9a723b4f95586363fae2151 | StoopDJ/Second_Year_College | /Python/Overloading.py | 2,021 | 4.46875 | 4 | # Function:
# 1. Write a class to represent an Item - each item has name, price and quantity.
# Include a method to calculate total price. Test your class by creating few Item objects.
# 2. Write a class to represent a complex number.
# Complex numbers can be written in the form of a+bi where a and b are real numbers and i is the solution of i^2=-1
#
# Add methods to add and subtract complex numbers - to add/subtract complex numbers you add/subtract
# the corresponding real and imaginary parts.
#
# For example, adding 1+2i and 2+3i will result in 3+5i
# Compiler used: PyCharm
# Functions/Classes
class Items:
def __init__(self, name, price, quantity): # Initialise the variables.
self.name = name
self.price = price
self.quantity = quantity
def __info__(self):
return self.name, self.price, self.quantity,
def Stock(new_cart): # Function to add an item to the parameters defined in the class.
# This way the user can add their own items during run-time
name_ = input("Please enter the item name.\n")
price_ = input("Please enter the item price.\n")
quantity_ = input("Please enter the item quantity.\n")
new_item = Items(name_, price_, quantity_)
print(new_item.name, "Has been added to your basket.\n")
quantity_ = int(quantity_)
price_ = int(price_)
cart = price_ * quantity_
new_cart = (new_cart + cart)
print("Your basket is: €", new_cart)
# Main function
def main():
new_cart = 0
# Menu to choice which function you want
print("1. Add items to the class.\n")
print("2. View you cart.\n")
while 1:
choice = input("\nPlease enter the number that corresponds to what option you want:\n")
choice = int(choice) # making the variable an int
if choice == 1:
# Call function
Stock(new_cart)
# elif choice == 2:
else:
print("Invalid input\n")
main()
| true |
63f15acc67fd66d8f80a31b9c49eca272589424c | tingyu-ui/test | /demo_class.py | 1,876 | 4.25 | 4 | #通过class关键字,定义了一个类
#创建一个人类
class Person:
#类变量
name = "default"
age = 0
gender = 'male'
weight = 0
#构造方法,在类实例化的时候被调用
def __init__(self,name,age,gender,weight):
self.name = name
self.age = age
self.gender = gender
self.weight = weight
# print("init function")
# def set_param(self,name,age,gender,weight):
# self.name = name
# self.age = age
# self.gender = gender
# self.weight = weight
# def set_age(self,age):
# self.age = age
#装饰器
@classmethod
def eat(self):
print(f"{self.name} eating")
print("xxxx")
# print("eating")
def play(self):
print("playing")
def jump(self):
print("jump")
#类方法是不能访问实例方法
#前面加了@classmethod才可以
Person.eat()
# zs = Person ('zhangsan',20,'男',120)
# zs.eat()
#类变量和实例变量区别
#类变量是需要类来访问的,实例变量是需要实例来访问
# print(Person.name)
# Person.name = 'tom'
# print(Person.name)
#
# zs = Person('zhangsan',20,'男',120)
# print(zs.name)
# zs.name = 'lili'
#类的实例化,创建了一个实例
# zs = Person()
# print(zs.name)
# zs = Person('zhangsan',20,'男',120)
# zs.eat()
# zs.set_param('zhangsan')
# zs.set_age(20)
# print(f"zhangsan 的姓名是:{zs.name},zhangsan的年龄是:{zs.age}")
# print(f"zhangsan 的性别是:{zs.gender},zhangsan的体重是:{zs.weight}")
#
# ls = Person('lisi',30,'男',150)
# # zs.set_param('zhangsan')
# # zs.set_age(20)
# ls.jump()
# print(f" 李四的姓名是:{ls.name},李四的年龄是:{ls.age}")
# print(f"李四 的性别是:{ls.gender},李四的体重是:{ls.weight}") | false |
d4f5c2c432b228ea23e98c35b684d8da3d14514f | RUCKUSJERRY/Python_Practice | /Python01/com/test03/test.py | 684 | 4.125 | 4 | # 1번 문제
x = input('숫자 입력 : ')
a, b = 0, 1
while a < int(x):
print(a, end=" ")
a, b = b, a+b
print()
# 2번 문제
def fibo1(x):
a, b = 0, 1
while a < int(x):
print(a, end=" ")
a, b = b, a+b
print()
# 3번 문제
x = input('숫자 입력 : ')
res = []
a, b = 0, 1
while a < int(x):
res.append(a)
a, b = b, a+b
print(res)
print()
# 4번 문제
def fibo2(x):
res = []
a, b = 0, 1
while a < int(x):
res.append(a)
a, b = b, a+b
print(res)
print()
# 5번 문제
if __name__ == '__main__':
x = input('level 입력 : ')
fibo1(x)
x = input('level 입력 : ')
fibo2(x) | false |
171955d3878d5b80117e1ad0e116814933795550 | ssarber/PythonClass | /algorithms/reverse_array.py | 856 | 4.3125 | 4 | # Task
# Given an array, A , of N integers, print A's elements in reverse order as a single line of space-separated numbers.
# Input Format
# The first line contains an integer, N (the size of our array).
# The second line contains space-separated integers describing array A's elements.
# Output Format
# Print the elements of array in reverse order as a single line of space-separated numbers.
def reverse_arr(arr, n):
index = n - 1
new_arr = []
for i in range(n):
new_arr.append(arr[index])
index -= 1
return ' '.join(map(str, new_arr))
arr = [1, 4, 3, 2]
print(reverse_arr(arr, 4))
def total(pretax, tip_percent, tax_percent):
total = pretax + pretax * tip_percent + pretax * tax_percent
return int(round(total))
print("The total meal cost is {} dollars.".format(total(12, 0.2, 0.08))) | true |
eff3d354e94012123d2469011b63875e44065fbd | ssarber/PythonClass | /fibonacci.py | 765 | 4.21875 | 4 |
# def fibonacci(n):
# if n == 1 return 1
# elif n == 0 return 0
# y = 1
# x = 2
# for x in range (0, n):
# x = 0 + 1
def factorial(num):
# product = 1
# for i in range(num):
# product *= (i+1)
# return product
if num <= 1:
return 1
return num * factorial(num - 1)
# print(factorial(5))
# def fibonacci(term):
# if term == 0
# return 0
# elif term == 1
# return 1
# number = number + fibonacci(number - 1)
# Iterative: recreate a list of Fibonacci sequence
def fibonacci(n):
terms = [0, 1]
i = 2
while i <= n:
terms.append(terms[i-1] + terms[i-2])
i = i + 1
return terms[n]
def fibonacci_rec(n):
if (n == 0): return 0
if (n == 1): return 1
return fibonacci_rec(n-1) + fibonacci_rec(n-2)
print(fibonacci_rec(5)) | false |
c0e7f85663ca77ab696771f4f1baa11e9e7be9f0 | BernardoLpz/python_tutorial_ptbr | /05_es_tela_formato/04_entrada_dados_tela.py | 722 | 4.34375 | 4 | #
# Autor : LF Silva
# Data : 13/04/2020
#
# Formato da entrada de dados em tela
# A entrada de dados, por padrão, é para variáveis do tipo string. Portanto, é
# necessário SEMPRE converter a variável para o tipo desejado.
#
# Comando input para entrar com informação em tela
idade = input("Entre com sua idade: ")
# print(f"Você tem {idade:3d} anos")
print(f"O tipo da variável é {type(idade)}")
# Mas e como converter a entrada para determinado tipo?
# Convertendo para variável inteira
age = int(input("Mais uma vez, entre com a sua idade: "))
print(f"Você tem {age:3d} anos.")
# Convertendo para ponto flutuante
weight = float(input("Entre com o seu peso (kg): "))
print(f"Você tem {weight:3.2f} kg.") | false |
97c17d27cc0767e5952b5102cee24c3f58b22f84 | BernardoLpz/python_tutorial_ptbr | /04_modulos_basico/02_module_numpy_basic.py | 1,975 | 4.34375 | 4 | #
# Autor : LF Silva
# Data : 01/05/2018
#
# Usando módulo Numpy
import numpy as np
# O principal objetivo do módulo NumPy é o tratamento de arrays (listas)
# homogêneas (de apenas um tipo de variável) e multidimensionais (vetores,
# matrizes etc). O array é tratado como uma tabela de elementos (usualmente
# números), todos do mesmo tipo, indexados por uma tupla de inteiros positivos.
# Em NumPy, as dimensões são chamadas de eixos.
# Comando para criar arrays
a = np.array( [1, 2, 3, 4] )
print("a = ", a)
# Podemos acessar os elementos como se fosse uma lista
print(a[0], a[2])
a[1] = 8
print("a novo = ", a)
# Outras propriedades do array também podem ser obtidas
print(a.ndim) # dimensão do array
print(a.size) # no. de elementos no array
print(type(a)) # tipo de variável no array
# Podemos criar um array de zeros e especificar o tipo de variável
b = np.zeros(10, dtype=np.float64)
print("b = ", b)
# Ou de unitários
c = np.ones(10)
print("c = ", c)
# Ainda podemos montar um array cujos elementos são igualmente espaçados
# entre si.
d = np.linspace(0.0, 1.0, 11) # start = 0.0, end = 1.0,
# number of intervals = 11
print("d = ", d)
# Por fim, podemos criar um array, definindo o espaçamento entre os pontos
e = np.arange(0.0, 1.0, 0.1) # start = 0.0, end = 1.0,
# intervals value = 0.1
print("e = ", e)
# Com arange, não é possível prever o número de elementos final devido ao
# acúmulo de erros de ponto flutuante. Portanto, linspace é mais indicado.
## Operações matemáticas
print("(b + 2c)**3 = ", (b + 2*c)**3)
b = b + 1.5
print("b*e = ", b*e)
# A maioria das funções matemáticas do modulo math estão disponíveis no NumPy
print("sin(e) = ", np.sin(e))
# O NumPy possui vários outros atributos e possibilidades. Para uma visão
# mais ampla, verifique a documentação em:
#
# https://docs.scipy.org/doc/numpy/user/quickstart.html
| false |
da5c62c91ad02ba3de961f43a0f0c4d8ea072622 | BernardoLpz/python_tutorial_ptbr | /11_numpy/04_copia_arrays.py | 2,692 | 4.40625 | 4 | #
# Autor: LF Silva
# Data : 23/11/2020
#
# Introdução ao uso de Numpy - Cópia de arrays
# O problema de shallow e deep copy
import numpy as np
# Python é bem espertinho ao alocar a memória para suas variáveis.
# Mas isso pode gerar algumas situações complicadas com o
# compartilhamento de informações na memória.
x = 10
y = x
print("ID x = ", id(x))
print("ID y = ", id(y))
print("Local de memoria compartilhado (x,y) : ", x is y)
y = 11
print(x, y)
print("ID x = ", id(x))
print("ID y = ", id(y))
print("Local de memoria compartilhado (x,y) : ", x is y)
# A situação pode ser mais complexa ao alocar o endereço para
# um array (sua base) e seus elementos.
# criação de array
arr1 = np.array([3, 4, 5, 7, 10, 21], dtype='float')
print("arr1 = ", arr1)
print("ID arr1 = ", id(arr1))
print("ID arr1[3] = ", id(arr1[3]))
# Operações de atribuição em Python não copiam objetos. Se criam conexões entre
# o objeto original e o alvo diretamente na memória (chamada de referência).
# Ou seja, ao manipular as variáveis alocadas na memória, tanto o objeto
# original quanto o alvo são alterados. arr1 = objeto original; arr2 = alvo;
print("Análise por atribuição: ")
arr2 = arr1
arr2[1] = 3.0
print("arr1 = ", arr1)
print("arr2 = ", arr2)
print("ID arr1 == ID arr2 : ", arr1 is arr2)
arr1[4] = 3.0
print("arr1 = ", arr1)
print("arr2 = ", arr2)
# Ou seja, usar o operador de atribuição pode levar a erros de lógica na
# execução do script (afinal, a sintaxe está correta)!
# Mas e como contornar isso em arrays Numpy?
# O método view() cria o que chamamos de shallow copy em que se cria um
# novo array, mas a referência entre os elementos são compartilhadas.
print("Análise por shallow copy: ")
brr1 = np.array([3, 6, 9, 12], dtype='float')
brr2 = brr1.view()
print("brr1 = ", brr1)
print("brr2 = ", brr2)
print("ID brr1 == ID brr2 : ", brr1 is brr2)
# e se alterar os elementos?
brr2[1] = 8
print("novo brr1 = ", brr1)
print("novo brr2 = ", brr2)
# Isso não resolve o problema. Usando Numpy, é possível usar o método
# copy(). O comando cria uma nova variável (alvo) e copia o conteúdo
# do objeto original para o alvo. brr1 = objeto original; brr3 = alvo;
# Para arrays (int, floats e strings), isso contorna o problema.
print("Análise por deep copy: ")
brr3 = np.copy(brr1)
print("brr1 = ", brr1)
print("brr3 = ", brr3)
print("ID brr1 == ID brr3 : ", brr1 is brr3)
# e se alterar os elementos?
brr3[1] = 33
print("novo brr1 = ", brr1)
print("novo brr3 = ", brr3)
# Cuidados a serem tomados!
# - Comando copy com objetos imutáveis e mutáveis
# - Eficiência computacional
# - Módulo copy
# - Busque mais detalhes com o amigo Google
| false |
36a8a44107be97f1470f0d15dfc0dd886b1b3379 | gladystyn/MCQ_biology_revision_program | /app.py | 2,740 | 4.25 | 4 | print("Title of program: MCQ biology revision program")
print()
counter = 0
score = 0
total_num_of_qn = 3
counter +=1
tracker = 0
while tracker !=1:
print("Q"+str(counter)+") "+ "What does the liver produce?")
print(" a) Salivary amylase")
print(" b) Pancreatic amylase")
print(" c) Bile")
print(" d) Pepsin")
answer = input("Your answer: ")
answer = answer.lower()
if answer == "a":
output = "Wrong. This is produced by the mouth."
score -=1
elif answer == "b":
output = "Wrong. This is produced by the pancreas."
score -=1
elif answer == "c":
output = "Yes, that's right!"
tracker =1
score +=1
elif answer == "d":
output = "Wrong. This is produced by the stomach."
score -=1
else:
output = "Please choose a, b, c or d only."
print()
print(output)
print()
print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" )
print()
print()
counter +=1
tracker = 0
while tracker !=1:
print("Q"+str(counter)+") "+ "Which one belongs to the human circulatory system?")
print(" a) Heart")
print(" b) Lungs")
print(" c) Urethra")
print(" d) Oesophagus")
answer = input("Your answer: ")
answer = answer.lower()
if answer == "a":
output = "Yes, that's right!"
tracker =1
score +=1
elif answer == "b":
output = "Wrong. This belongs to the respiratory system."
score -=1
elif answer == "c":
output = "Wrong. This belongs to the reproductive system."
score -=1
elif answer == "d":
output = "Wrong. This belongs to the digestive system."
score -=1
else:
output = "Please choose a, b, c or d only."
print()
print(output)
print()
print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" )
print()
print()
counter +=1
tracker = 0
while tracker !=1:
print("Q"+str(counter)+") "+ "What is protein made up of?")
print(" a) 1 glycerol molecule and 3 fatty acids")
print(" b) fibre")
print(" c) monosaccharide")
print(" d) chains of amino acids")
answer = input("Your answer: ")
answer = answer.lower()
if answer == "a":
output = "Wrong. This makes up lipids."
score -=1
elif answer == "b":
output = "Wrong. This is found in some carbohydrates."
score -=1
elif answer == "c":
output = "Wrong. This is found in carbohydrates."
score -=1
elif answer == "d":
output = "Yes, that's right!"
tracker =1
score +=1
else:
output = "Please choose a, b, c or d only."
print()
print(output.lower())
print()
print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" )
print()
print()
print("End of quiz!")
| true |
05de78717af1e3c22bf978c5593410db9850883c | pujalb/100-days-of-python | /Day-08-Function-Parameters-&-Caesar-Cipher/Interactive Coding Exercise - Day 8.2 Prime Number Checker/main.py | 726 | 4.21875 | 4 | #Write your code below this line 👇
from math import sqrt, ceil
def prime_checker(number):
# Ceck if number is greater than 1
if number < 2:
print("It's not a prime number.")
return
# Instead of checking all numbers from 0 to number, just check from 0 to square root of the number
last_num = ceil(sqrt(number))
is_prime = True
for num in range(2, last_num):
if number % num == 0:
is_prime = False
if is_prime:
print("It's a prime number.")
else:
print("It's not a prime number.")
#Write your code above this line 👆
#Do NOT change any of the code below👇
n = int(input("Check this number: "))
prime_checker(number=n)
| true |
5d9f5f14d35c6ea272b6df47ccbab10b72a9a3c5 | sharder996/hacker-hell | /leetcode/python3/[208]_implement-trie-prefix-tree.py | 1,640 | 4.1875 | 4 | #
# @lc app=leetcode id=208 lang=python3
#
# [208] Implement Trie (Prefix Tree)
#
# @lc code=start
class TrieNode:
def __init__(self, val: set, next):
self.val = val
self.next = next
self.terminal = False
class Trie:
'''
Accepted
15/15 cases passed (176 ms)
Your runtime beats 65.22 % of python3 submissions
Your memory usage beats 41.98 % of python3 submissions (31.7 MB)
Insertion:
Time complexity : O(m) where m is the length of the string
Search:
Time complexity : O(m) where m is the length of the string
'''
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode(None, {})
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
curr = self.root
for c in word:
if c in curr.next:
curr = curr.next[c]
else:
curr.next[c] = TrieNode(c, {})
curr = curr.next[c]
curr.terminal = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
curr = self.root
for c in word:
if c not in curr.next:
return False
curr = curr.next[c]
return curr.terminal
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
curr = self.root
for c in prefix:
if c not in curr.next:
return False
curr = curr.next[c]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
# @lc code=end
| true |
7d9917a5b0e25d38d509e0f8fda62700203cefad | gmolinsm/PythonP2 | /Exceptions/main.py | 438 | 4.21875 | 4 | # A simple example in how to catch exceptions
try:
num = input("Give me a number: ")
num = int(num)
num2 = input("Give me another number: ")
num2 = int(num2)
result = num / num2
except ValueError:
print("Please give me a proper number")
except ZeroDivisionError:
print("The second number can not be 0")
except:
print("Something else i did not expect went wrong")
else:
print("The division is", result) | true |
fffa83c7ff04e72062d67214030c71801be66501 | DikranHachikyan/CPYT210713 | /ex66.py | 1,197 | 4.25 | 4 | # 1.дефиниция на класа
class Point():
def __init__(self, x = 0, y = 0, *args, **kwargs):
print('Point Ctor')
# данни на обекта
self.x = x
self.y = y
# методи на обекта
def draw(self):
print(f'draw point at ({self.x}, {self.y})')
def move_to(self, dx, dy):
self.x += dx
self.y += dy
# getter
@property
def x(self):
return self.__x
# setter
@x.setter
def x(self,x):
assert type(x) is int and x >= 0, 'x must be positive number'
self.__x = x
@property
def y(self):
return self.__y
@y.setter
def y(self, y):
assert type(y) is int and y >= 0, 'y must be positive number'
self.__y = y
# специални методи
if __name__ == '__main__':
# 2. променлива (обект) от тип Point
# клас - типа (Point), обект - представител на класа т.е. променливата
p1 = Point()
p2 = Point(12,20)
print(f'point ({p1.x}, {p1.y}) (getters)')
p1.x = 14
p1.y = 32
p1.draw()
print('---') | false |
91b3eb9a9d705d92178bf2a8e465c1a9cfd0cead | VladyslavHnatchenko/theory_python | /function.py | 1,231 | 4.125 | 4 | """Function Parameters and Arguments."""
def cylinder(h, r=1):
side = 2 * 3.14 * r * h
circle = 3.14 * r ** 2
full = side + 2 * circle
return full
figure1 = cylinder(4, 44)
figure2 = cylinder(232)
print(figure1)
print(figure2)
"""Programming Functions."""
# def rectangle():
# a = float(input("Width: "))
# b = float(input("Height: "))
# print("Square: %.2f" % (a*b))
#
#
# def triangle():
# a = float(input("Base: "))
# h = float(input("Height: "))
# print("Square: %.2f" % (0.5*a*h))
#
#
# def circle():
# r = float(input("Radius: "))
# print("Square: %.2f" % (3.14 * r**2))
#
#
# figure = input("1-rectangle, 2-triangle, 3-circle: ")
#
# if figure == "1":
# rectangle()
# elif figure == "2":
# triangle()
# elif figure == "3":
# circle()
# else:
# print("Input Error")
###########################################################
# def count_food():
# a = int(input())
# b = int(input())
# print("Total", a+b, "pieces.")
#
#
# print("How many bananas and pineapples are there for monkeys?")
# count_food()
#
# print("How many bugs and worms for hedgehogs?")
# count_food()
#
# print("How many fish and shellfish are for otters?")
# count_food()
| false |
92d7ce74f89e34e9e906ee3917e63fc26782c7ae | polivares/FullStackPython2021-1 | /Clase3/multipleargs.py | 896 | 4.28125 | 4 | # Puedes agregar múltiples argumentos a las funciones y de distintas maneras
def f1(a,b,c):
print(a,b,c)
f1(1,2,3)
f1(b=1,c=2,a=3)
# Formas de indicar argumentos de entrada
def f2(a, b,*args):
print(a,b)
for i in args:
print(i)
print("Función llamada con dos argumentos")
f2(1,2) # Esto muestra los dos primeros parámetros solamente
print("Función llamada con cuatro argumentos")
f2(1,2,3,4)
print("Función llamada con ocho argumentos")
f2(1,2,3,4,5,6,7,8)
# ¿Qué ocurre si necesito agregar parámetros asociados a un elemento en particular?
def f3(**kwargs):
print(kwargs["a"])
for i in kwargs.items():
print(i[0], i[1])
print("Llamando función con 3 parámetros de entrada como diccionarios de valores")
f3(a=1, b=2, c=3)
print("Llamando función con 2 parámetros de entrada como diccionarios de valores")
f3(primero=1, segundo=2)
| false |
b5d5d914b2cd271d0a401646d4eb7298eca3234a | rybakovas/Python | /Python/basic/calculator_full.py | 415 | 4.125 | 4 | from math import *
num1 = float(input("Enter first number: "))
op = input("Enter you operator: ")
num2 = float(input("Enter second number: "))
if op == "+":
result = num1 + num2
elif op == "-":
result = num1 - num2
elif op == "/":
result = num1 / num2
elif op == "*":
result = num1 * num2
else:
result = "Enter a valid operator"
print(result)
# By Victor Rybakovas Sep 2019 - http://bit.ly/linkedin-victor | false |
a6c3fae7387c6ebe7a2593a0f5a55f6b445df0ca | rybakovas/Python | /Python/basic/if_statement_comparison.py | 390 | 4.125 | 4 |
def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
print("Number " + str(num1) + " is the bigger")
elif num2 >= num1 and num2 >= num3:
print("Number " + str(num2) + " is the bigger")
else:
print("Number " + str(num3) + " is the bigger")
max_num(300, 400, 5)
# == equal
# != not equal
# By Victor Rybakovas Sep 2019 - http://bit.ly/linkedin-victor | true |
0834c5ba0b3caa6836d6ad1e26eb9da989fac8bc | santokalayil/my_python_programs | /name_age_turning_100.py | 1,356 | 4.15625 | 4 |
# Creator : Santo K. Thomas
'''Program that asks the user to enter their name and their age. Print out a message addressed to
them that tells them the year that they will turn 100 years old.'''
import datetime
now = datetime.datetime.now()
this_year = now.year
name = str(input('Enter Your Name?'))
while True:
try:
age = int(input('Enter Your Age'))
break
except ValueError:
print('\n\nSorry, I did not get your age! Please try again')
continue
if age > 0:
if age < 100:
year = int(this_year+(100-age))
print('\n\nYour Name is {} \nYour Age is {} \nYou will be turning 100 in the year {}'.format(name.title(), age, year))
elif (age > 100) and (age <= 120):
print('\n\nYour Name is {} \nYour Age is {} \nYour are have turned 100 in the year {}'.format(name.title(), age, this_year - (age-100)))
elif age == 100:
print('\n\nYou are now 100 years old')
elif (age > 120) and (age <= 160):
print('\n\nMy God! I think "You are older than oldest person living now"\nYour Name is {} \nYour Age is {} \nYour are have turned 100 in the year {}'.format(name.title(), age, this_year - (age-100)))
else:
print('\n\nI don"t think that you are human to have this lifespan')
else:
print('\n\nNegative number in age! Please know that you cannot trick me')
| true |
0e16eeb99d2583a8bc229813196f9d976b674ac9 | michaelwise12/cmpt120wise | /bankaccount.py | 1,310 | 4.15625 | 4 | # bankaccount.py
class BankAccount:
"""Bank Account protected by a pin number."""
def __init__(self, pin):
"""Initial account balance is 0 and pin is 'pin'."""
self.balance = 0
print("Welcome to your bank account!")
self.pin = pin
def deposit(self, pin, amount):
"""Increment account balance by amount and return new balance."""
if pin == self.pin:
self.balance += amount
return self.balance
else:
print("Invalid pin number.")
def withdraw(self, pin, amount):
"""Decrement account balance by amount and return amount withdrawn."""
if pin == self.pin:
self.balance -= amount
return amount
else:
print("Invalid pin number.")
def get_balance(self, pin):
"""Return account balance."""
if pin == self.pin:
return self.balance
else:
print("Invalid pin number.")
def change_pin(self, oldpin, newpin):
"""Change pin from oldpin to newpin."""
if oldpin == self.pin:
self.pin = newpin
print("Changed pin number.")
else:
print("You failed to provide your old pin number correctly!")
| true |
7249e01fd01776deca989d0ac449bc9021f147b7 | Amarmuddana/python-training | /Day9/day9.py | 1,236 | 4.25 | 4 | #How to create a dictionary
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'text1', 2: 'text2'}
# dictionary with mixed keys
my_dict = {'name': 'ram', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
#access elements from a dictionary
my_dict = {'name':'ravi', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
output:
ravi 26
#change or add elements in a dictionary
my_dict = {'name':'ravi', 'age': 26}
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
output:
{'name': 'ravi', 'age': 27, 'address': 'Downtown'}
#Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
#delete or remove elements from a dictionary
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# remove a particular item
print(squares.pop(4))
print(squares)
# remove all items
print(squares.clear())
print(squares)
# delete the dictionary itself
print(del squares)
print(squares)
#output
16
{} | true |
15ebb008327450bfe50afb4f0928fc099f1863cb | Amarmuddana/python-training | /Day7/day7.py | 791 | 4.59375 | 5 | Formatters
# .formats in strings
print("ravi has {} balloons.".format(5))
string = "ravi loves {}."
print(string.format("python"))
string = "ravi loves {} {}."
print(string.format("open-source", "software"))
string = "ravi loves {} {}, and has {} {}."
print(string.format("open-source", "software", 5, "balloons"))
print("ravi the {} has a pet {}!".format("boy", " bull dog"))
print("ravi the {0} has a pet {1}!".format("boy", "bull dog"))
#f strings
name = "Ravi"
age = 24
print (f"Hello, {name} You are {age}.")
#f and using string lower case
name = "RAVI"
age = 24
print (f"{name.lower()} you are {age}.")
#f and using string Upper case
name = "ravi"
age = 24
print (f"{name.upper()} you are {age}.") | false |
242954fda3a7a3e112413a3dac56c9e42534867f | Ronak912/Programming_Fun | /Array/LargetSumContiguousSubArray.py | 634 | 4.15625 | 4 | # https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
# Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers
# which has the largest sum.
# ex: lst = [-2, -3, 4, -1, -2, 1, 5, -3]
# Answer: Maximum sum is for subarray [4, -1, -2, 1, 5] = 7
def getMaxSubArraySum(lst):
maxsofar, currsum = lst[0], lst[0]
for val in lst[1:]:
currsum = max(val, currsum+val)
maxsofar = max(maxsofar, currsum)
return "Max sum of subarray is {}".format(maxsofar)
if __name__ == "__main__":
print(getMaxSubArraySum([-2, -3, 4, -1, -2, 1, 5, -3]))
| true |
45291fb16c1e03a09bdba50879e6df0cc4ee93a4 | Ronak912/Programming_Fun | /String/GroupWordsWithSameSetChar.py | 1,454 | 4.40625 | 4 | # http://www.geeksforgeeks.org/print-words-together-set-characters/
"""Group words with same set of characters
Given a list of words with lower cases. Implement a function to find all Words that have the same unique character set .
Example:
Input: words[] = { "may", "student", "students", "dog",
"studentssess", "god", "cat", "act",
"tab", "bat", "flow", "wolf", "lambs",
"amy", "yam", "balms", "looped",
"poodle"};
Output :
looped, poodle,
lambs, balms,
flow, wolf,
tab, bat,
may, amy, yam,
student, students, studentssess,
dog, god,
cat, act,
All words with same set of characters are printed
together in a line."""
def getKey(word):
uniquechars= set([char for char in word])
return ''.join(sorted(uniquechars))
def wordsWithSameCharSet(words, n):
haspmap = {}
for idx, word in enumerate(words):
key = getKey(word)
if key not in haspmap:
haspmap[key] = [idx]
else:
haspmap[key].append(idx)
for key in haspmap:
similarwords = haspmap[key]
if len(similarwords) > 1:
print ', '.join(words[i] for i in similarwords)
if __name__ == "__main__":
words = ["may", "student", "students", "dog", "studentssess", "god", "cat", "act", "tab",
"bat", "flow", "wolf", "lambs", "amy", "yam", "balms", "looped", "poodle"]
n = len(words)
wordsWithSameCharSet(words, n) | true |
f0c815fa098139a73e9f53b7f7e1c57d407d0e05 | Ronak912/Programming_Fun | /String/LongestSubsequenceWithAtleastKTimes.py | 1,022 | 4.15625 | 4 | # https://www.geeksforgeeks.org/longest-subsequence-where-every-character-appears-at-least-k-times/
'''
Method 1 (Brute force)
We generate all subsequences (check file GetAllSubString.py).
For every subsequence count distinct characters in it and find the longest subsequence where every character
appears at-least k times.
Method 2 (Efficient way)
1. Find the frequency of the string and store it in an integer array of size 26 representing the alphabets.
2. After finding the frequency iterate the string character by character and if the frequency of that character
is greater than or equal to the required number of repetitions then print that character then and there only.
'''
import collections
def longestSubseqWithK(instr, k):
map = collections.defaultdict(int)
for char in instr:
map[char] += 1
outputstr = ''
for char in instr:
if map[char] >= k:
outputstr += char
print(outputstr)
if __name__ == "__main__":
longestSubseqWithK("ronakronaktest", 2) | true |
454d52168a772d064bde8aea9ea92381c30cb877 | Ronak912/Programming_Fun | /hashmap/FindItinerary.py | 1,135 | 4.46875 | 4 | # http://www.geeksforgeeks.org/find-itinerary-from-a-given-list-of-tickets/
#
# Find Itinerary from a given list of tickets
# Given a list of tickets, find itinerary in order using the given list.
#
# Example:
#
# Input:
# "Chennai" -> "Banglore"
# "Bombay" -> "Delhi"
# "Goa" -> "Chennai"
# "Delhi" -> "Goa"
#
# Output:
# Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore,
def findItinerary(lst):
hashmap = {val[0]: val[1] for val in lst}
# starting point is not val of any key in original map, so we can create revmap and look for country which
# does not exit in keyset
revhashmap = {val[1]: val[0] for val in lst}
fromplace = None
for key, val in hashmap.iteritems():
if not revhashmap.get(key, False):
fromplace = key
break
toplace = hashmap.get(fromplace, None)
while toplace:
print "{}->{}".format(fromplace, toplace)
fromplace = toplace
toplace = hashmap.get(fromplace, None)
if __name__ == "__main__":
lst = [("Chennai", "Banglore"), ("Bombay", "Delhi"), ("Goa", "Chennai"), ("Delhi", "Goa")]
findItinerary(lst) | true |
cd903b6bda471945b827c95f743e0221a18770f7 | Ronak912/Programming_Fun | /LinkedList/printReverseLinkedListUsingRecursive.py | 492 | 4.40625 | 4 | # http://www.geeksforgeeks.org/write-a-recursive-function-to-print-reverse-of-a-linked-list/
# Write a recursive function to print reverse of a Linked List
import LinkedList
def printReverseRecur(node):
if node is None:
return
printReverseRecur(node.next)
print node.data,
if __name__ == "__main__":
ll = LinkedList.LinkedList()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.add_node(6)
ll.add_node(7)
printReverseRecur(ll.cur_node)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.