blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ad5f7bd7652559a42904eee699f9f3b0238689c8 | soniccc/regexp | /regexp2.py | 386 | 4.53125 | 5 | # Example: To verify a string contans a particular word
import re
paragraph = '''
The regular expression isolates the document's namespace value, which is then used to compose findable values for tag names
'''
word = 'namespace'
if re.search(word, paragraph):
print(f"The paragraph contains the word : '{word}'")
else:
print(f"The word '{word}' is not in this paragraph")
| true |
c50996345949e25f2bc5e6ab451e8a22f6a0c5fb | DanielFleming11/Name | /AverageScores.py | 551 | 4.28125 | 4 | #Initialize all variables to 0
numberOfScores = 0
score = 0
total = 0
scoreCount = 0
average = 0.0
#Accept the number of scores to average
numberOfScores = int(input("Please enter the number of scores you want to input: "))
#Add a loop to make this code repeat until scoreCount = numberOfScores
while(scoreCount != numberOfScores):
score = int(input("Please enter a score: "))
total = total + score
scoreCount = scoreCount + 1
average = str(total / numberOfScores)
print("The average for all the scores is: " + average)
| true |
221a661ba52f4393d984a377511f87f7ca1e285d | iwasnevergivenaname/recursion_rocks | /factorial.py | 328 | 4.40625 | 4 | # You will have to figure out what parameters to include
# 🚨 All functions must use recursion 🚨
# This function returns the factorial of a given number.
def factorial(n, result = 1):
# Write code here
result *= n
n -= 1
if n == 1:
return result
return factorial(n, result)
print(factorial(5)) | true |
b2e6d5d485409a42c565292fa84db602445778a4 | eugenesamozdran/lits-homework | /homework8_in_progress.py | 1,178 | 4.3125 | 4 | from collections.abc import Iterable
def bubble_sort(iter_obj, key=None, reverse=False):
# first, we check if argument is iterable
# if yes and if it is not 'list', we convert the argument to a list
if isinstance(iter_obj, Iterable):
# here we check if some function was passed as a key
# and modify our iterable applying the function to all its elements
if key == None:
iter_obj = list(iter_obj)
pass
else:
iter_obj = list(map(key, iter_obj))
# this is the sorting loop itself
for i in range(len(iter_obj)):
for y in range(len(iter_obj)-i-1):
if iter_obj[y] > iter_obj[y+1]:
iter_obj[y], iter_obj[y+1] = iter_obj[y+1], iter_obj[y]
# here we check if the result should be reversed or not
if reverse:
return iter_obj[::-1]
return iter_obj
else:
raise TypeError
a = [{"value": 42}, {"value": 32}, {"value": 40}, {"value": 56}, {"value": 11}]
a = bubble_sort(a, lambda x: x["value"])
print(a)
| true |
7acc25c12d7f688d0b428849de5b3015086c2644 | Diego-18/python-algorithmic-exercises | /1. PROGRAMACION ESTRUCTURADA/NUMEROS/par y primo.py | 704 | 4.125 | 4 | #!/usr/bin/env python
#-*- coding: cp1252 -*-
################################
# Elaborado por: DIEGO CHAVEZ #
################################
#Algoritmo capaz de verificar si un numero es par y primo
lsseguir="s"
licont=0
while lsseguir=="s" or lsseguir=="S":
linumero=int(raw_input("Introduzca el numero: "))
licont=0
if (linumero%2==0):
print "El numero es par"
elif (linumero%2!=0):
print "El numero no es par"
for liN in range (1,linumero+1):
if (linumero%liN==0):
licont=licont+1
if licont==2:
print "El numero es primo"
else:
print "El numero no es primo"
lsseguir=raw_input("Desea seguir?: (S/N) ")
#UPTP S1-T1 | false |
12ca3949ce6f3d218ed13f58ee0ab0a0e06f4ab4 | geyunxiang/mmdps | /mmdps/util/clock.py | 1,760 | 4.34375 | 4 | """
Clock and time related utils.
"""
import datetime
from datetime import date
def add_years(d, years):
"""
Return a date that's `years` years after the date (or datetime)
object `d`. Return the same calendar date (month and day) in the
destination year, if it exists, otherwise use the following day
(thus changing February 29 to March 1).
"""
try:
return d.replace(year = d.year + years)
except ValueError:
return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))
def now():
"""
Time string represents now().
No ':' in the string, can be used in filename.
The iso time string cannot be used in filename.
"""
return datetime.datetime.now().strftime('%Y-%m-%dT%H-%M-%S.%f')
def now_str():
"""A more reader-friendly format"""
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def isofmt():
"""ISO time fmt."""
return '%Y-%m-%dT%H:%M:%S'
def simplefmt():
"""Simple time fmt."""
return '%Y%m%d'
def iso_to_time(isostr):
"""ISO time string to time object."""
return datetime.datetime.strptime(isostr, isofmt())
def time_to_iso(t):
"""Time object to iso time string."""
return datetime.datetime.strftime(t, isofmt())
def iso_to_simple(isostr):
"""ISO time string to simple time string."""
t = iso_to_time(isostr)
return datetime.datetime.strftime(t, simplefmt())
def simple_to_time(simplestr):
"""Simple time string to time object."""
return datetime.datetime.strptime(simplestr, simplefmt())
def eeg_time(t):
year, month, day, hour, minute, second = t.replace('T','-').replace(':','-').split('-')
return datetime.datetime(int(year),int(month),int(day),int(hour),int(minute),int(second))
| true |
522bc730e6d05cc957a853f5d667e553229474ff | Bigbys-Hand/crash_course_git | /functions.py | 2,909 | 4.4375 | 4 | def greet_nerds():
"""Display a simple greeting"""
print("Live long and prosper")
def better_greeting(username):
"""Display a simple greeting, pass name to function"""
print(f"Live long and prosper, {username.title()}!")
#This function is similar to the first one, but we created the PARAMETER 'username' so we could pass a name value to it as an ARGUMENT.
#The PARAMETER is 'username', the ARGUMENT could be any name - samuel, rebeka, etc.
def display_message():
"""Prints a formatted block of text summarizing what I've learned from chapter 8."""
print("This function is similar to the first one, but we created the PARAMETER 'username' so we could pass a name value to it as an ARGUMENT. \nThe PARAMETER is 'username', the ARGUMENT could be any name - samuel, rebeka, etc.")
def favorite_book(book_title):
"""Accepts one parameter, 'book_title'. Prints a message declaring the argument to be your favorite book."""
print(f"{book_title.title()} is my favorite book!")
#You can pass arguments to parameters in a number of way.
#A function definition may have multiple parameters, so a function call may need multiple arguments.
#POSITIONAL ARGUMENTS: Match each argument to parameter by the order in which the arguments are provided.
def describe_kitty(kitty_name, kitty_size, kitty_color):
"""Displays information about a pet cat. Name, size, color."""
print(f"\nI have a cat named {kitty_name.title()}.")
print(f"This is a {kitty_size} cat. Fur color is {kitty_color}.")
describe_kitty('snow','small','ashy brown and white')
#You can work with as many positional arguments as you like! Just don't forget their order.
#KEYWORD ARGUMENTS: Name-value pair you pass to a function. Name and value are associated within the argument.
#Thus you can't put arguments in the wrong order.
#The function is written the same! You just name each parameter explicitly when passing your arguments:
describe_kitty(kitty_name='snow',kitty_color='ashy gray with white coat',kitty_size='small')
#DEFAULT VALUES: An argumment for a parameter provided in the function call.
#Note that order still matters, and you can overwrite a default argument by entering that argument with a new value when you call the function.
#Order is important, default parameters should always be last so you can enter new values for them only when needed.
def describe_doggo(doggo_name, doggo_breed, doggo_good='GOOD BOY'):
"""Display factual and unbiased information about a dog."""
print(f"My dog's name is {doggo_name.title()}")
print(f"This dog is a {doggo_breed.title()} and a very {doggo_good}!")
describe_doggo('Obby','bird dog mutt')
describe_doggo('Obby','bird dog mutt','okay boy')
#If you specify name-value parts when calling a function, you can enter them in any order.
describe_doggo(doggo_breed='corgi',doggo_good='VERY GOOD BOY',doggo_name='Zeke')
| true |
48f0d4132919cdae29fe3591b01b235869c65af6 | HenrikSamuelsson/python-crash-course | /exercises/chapter_03/exercise_03_07/exercise_03_07.py | 2,758 | 4.21875 | 4 | # 3-7 Guest List
guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"]
message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[2] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[3] + " you are invited to dinner at 7 on saturday."
print(message)
cancelation_message = guest_list[1] + " can not attend the dinner."
print(cancelation_message)
guest_list[1] = "Charles Darwin"
message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[2] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[3] + " you are invited to dinner at 7 on saturday."
print(message)
message = "I have a bigger table now so three more people will be invited."
print(message)
guest_list.insert(0, "Stephen Hawking")
guest_list.insert(2, "Louis Pasteur")
guest_list.append("Nicolaus Copernicus")
message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[2] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[3] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[4] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[5] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[6] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Change of plans only two people can come to dinner this time."
print(message)
uninvited = guest_list.pop()
message = "Sorry " + uninvited + " you will have to come another time."
print(message)
uninvited = guest_list.pop()
message = "Sorry " + uninvited + " you will have to come another time."
print(message)
uninvited = guest_list.pop()
message = "Sorry " + uninvited + " you will have to come another time."
print(message)
uninvited = guest_list.pop()
message = "Sorry " + uninvited + " you will have to come another time."
print(message)
uninvited = guest_list.pop()
message = "Sorry " + uninvited + " you will have to come another time."
print(message)
message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)
del guest_list[1]
del guest_list[0]
print(guest_list)
| false |
b06fe113e6b7c496cca988987f4f4c56f8931766 | ovnny/HarvardCS50-Intr2CS | /6python/exercicios/teste.py | 312 | 4.21875 | 4 | x = int(input("x: "), 2) #Tipagem como função int()
y = int(input("y: "), 8) #Escolha do modelo de base
z = int(input("z: "), 16) #numérica no fim da função.
print(f"x is: {x}\ny is: {y}\nz is: {z}\n") #Binário, Octal e Hexadecimal | false |
2c388e95f7a92ac05d468d9d5ce8e927915dce10 | InnocentSuta/PythonChallenges | /04_Leap Year.py | 316 | 4.28125 | 4 |
#Program to check wether a year is a leap year or not.
year = int(input("Please Enter a year : "))
#check if the year is divisible by 4 and 400 and not by 100
if year % 4 == 0 and (year % 400 == 0 or year % 100 != 0):
print(year, "is a leap year ")
else:
print(year, "is not a leap year ")
| false |
5d40801b679cd7469773a11535c56ec1efb8c63e | weixuanteo/cs_foundation | /string_splosion.py | 474 | 4.28125 | 4 | # Given a non-empty string like "Code" return a string like "CCoCodCode".
# Sample input
s = "Code"
def string_splosion(str):
result = ""
# On each iteration, add the substring of the chars
for i in range(len(str)):
print("str[:i+1]: ", str[:i+1])
# [Python slicing] Returns from begining of the string to pos i+1 and concatenate to result.
result = result + str[:i+1]
return result
# Main
result = string_splosion(s)
print(result) | true |
0e9bbd1aef2f920e35ead4e7b969504cb63d04b1 | happyAyun/MSA_TIL | /python_workspace/basic_grammer/13_classv_test.py | 790 | 4.125 | 4 | class ClassTest:
class_v = 10 # 클래스 변수 : 클래스 타입의 모든 instance 공유하는 변수 클래스 이름으로 참조.
def __init__(self,instance_v):
self.instance_v = instance_v
c1 = ClassTest(10)
c2 = ClassTest(10)
c1.instance_v += 1
c2.instance_v += 1
c3 = ClassTest.class_v
c3 += 1
c4 = ClassTest.class_v
c4 += 1
ClassTest.class_v +=1 # 클래스 변수 사용
ClassTest.class_v +=1
c1.class_v += 1
c2.class_v += 1 # 공유되지 않음.
# 클래스 변수는 클래스 이름으로 참조해야 한다! 인스턴스 이름으로 하면 안됨.
print("{0} c1.instance_v , {1} c2.instance_v" .format(c1.instance_v, c2.instance_v))
print("{0} c3.class_v , {1} c4.class_v" .format(c3, c4))
print("{} ClassTest.class_v".format(ClassTest.class_v)) | false |
c72327d594362697ad1b65db7530a19d564b74da | saintsavon/PortfolioProjects | /Interview_Code/Palindrome.py | 1,434 | 4.21875 | 4 | import re
import sys
# Used to get the word list file from command line
# Example command: 'python Palindrome.py test_words.txt'
input_file = sys.argv[1]
def palindrome(word):
"""
Checks if word is a palindrome
:param word:
:return Boolean:
"""
return word == word[::-1]
palindrome_dict = {}
def update(word, palindrome_dict):
"""
Used to update the dictionary when Palindrome is found
:param word:
:param palindrome_dict:
:return updated dict count:
"""
if word not in palindrome_dict:
palindrome_dict[word] = 1
return palindrome_dict
else:
palindrome_dict[word] += 1 # Counts number of times palindrome occurs
return palindrome_dict
# Reads desired .txt file to be searched for Palindromes
with open(input_file, "r") as in_f:
for line in in_f:
for word in line.split():
word = re.sub(r'[^\w]', '', word.lower()) # removes non-word char and capitalization
if palindrome(word) and len(word) > 1:
palindrome_dict = update(word, palindrome_dict)
else:
continue
in_f.close()
# Prints found palindromes to .txt file
with open("found_palindromes.txt", "w") as fp: # fp = found palindrome
for item, val in palindrome_dict.items():
fp.write(" ".join((item, str(val), "\n")))
fp.close()
print("Done! File saved as found_palindromes.txt")
| true |
11a39da4784ff32c31419d5bb891893ec22f810e | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /14. Dictionaries/125. iterating_dict.py | 1,365 | 4.25 | 4 | instructor = {
"name":"Cosmic",
"num_courses":'4',
"favorite_language" :"Python",
"is_hillarious": False,
44 : "is my favorite number"
}
# Accessing all values in a dictionary
# We'll loop through keys, loop through values, loop through both keys and values
# Values Print .values() method call on a dictionary
for value in instructor.values():
print(value)
# Keys print
for key in instructor.keys(): # .keys() method call on a dictionary
print(key)
# .items() is the method we call on the dictionary to print both the key as well as values pair
# Method 1
"""b = instructor.items()
print(b)
"""
# Method 2
"""for item in instructor.items():
print(item)"""
# Method 3
for key,value in instructor.items():
print(f"key is {key} and value is {value}")
# Exercise 126
# Loop over donations, add all the VALUES together and store in a variable called total_donations
donations = dict(sam=25.0, lena=88.99, chuck=13.0, linus=99.5, stan=150.0, lisa=50.25, harrison=10.0)
# Method 1
total_donations = []
# for donation in donations.values():
# total_donations.append(donation)
# print(total_donations)
# print(sum(total_donations))
# Method -2
a = sum(donation for donation in donations.values())
print(a)
# Method-3
b = sum(donations.values())
print(b) | true |
a9b3cedf7ae1dae5eb5ce3246552c15df6bf59eb | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /12. Lists/104. list_methods.py | 1,127 | 4.1875 | 4 | first_list = [1,2,3,4]
first_list.insert(2,'Hi..!')
print(first_list)
items = ["socks", 'mug', "tea pot", "cat food"]
# items.clear()
#Lets the items list to be a list but clears everything within it.
items = ["socks", 'mug', "tea pot", "cat food"]
first_list.pop() # Remove the last element
first_list.pop(1) #Removes the element with the index 1
# While removing it also returns the item that is removed so that we may append or assign it somewhere else as well in case you want to capture and do some operation.
last_item = items.pop()
print(last_item)
# remove - Remove the first item from the list whose value is x.
names = ["Colt","Blue","Arya","Lena","Colt","Selena","Pablo"]
names.remove("Blue")
print(names)
print(names.count("Colt")) #Counts the number of times a particular value or string is present inside a list.
# Using join is commonly done to convert lists to strings
words = ['Coding', 'is', 'fun']
b = ' '.join(words)
print(b)
name = ["Mr", "Steele"]
c= '. '.join(name)
print(c)
friends = ["Colt","Blue","Arya","Lena","Colt","Selena","Pablo"]
d = ", ".join(friends)
print(d) | true |
f4724113c5118d7bd8a03d862cf6010ba588539f | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /08. and 09. ConditionalLogic and RPS/game_of_thrones.py | 1,970 | 4.15625 | 4 | print("Heyy there! Welcome to GOT quotes machine.")
print("What is your name human ?")
user_name = input()
print("\n Select from numbers 1 through 5 and we will give a quote (or two) based on your name. e.g. 1 or Tyrion or TL (case sensitive)\n \n")
# or First Name or Initials
print("What's your character's name?\n 1. Tyrion Lannister \n 2. Cersei Lannister \n 3. Daenerys Targaryen \n 4. Ned Stark \n 5. Ygritte \n ")
name = input("Enter your input here: ")
if name == "1": # or "Tyrion" or "TL":
print("Here are some of the Tyrion Lannister quotes:\n 1. The powerful have always preyed on the powerless. That's how they became powerful in the first place.")
print("2. Let me give you some advice, bastard. Never forget what you are. The rest of the world will not. Wear it like armor, and it can never be used to hurt you.")
print("3. A lion doesn't concern himself with the opinions of a sheep.")
print("4. It's easy to confuse 'what is' with 'what ought to be', especially when 'what is' has worked out in your favor.")
elif name == "2": # or "Cersei" or "CL":
print("1. If you ever call me 'sister' again, I'll have you strangled in your sleep.")
print("2. When you play the game of thrones, you win or you die.")
elif name == "3": # or "Daenerys" or "DT":
print("1. The next time you raise a hand to me will be the last time you have hands.")
elif name == "4": # or "Ned" or "NS":
print("Winter is coming.")
elif name == "5": # or "Ygritte" or "Y":
print("You know Nothing! Jon Snow!")
else:
print("Please read the first line where at the end we give examples about how to enter name to get character quotes.\nProgram will exit now. Re-run if you actually need GOT quotes and are not here for QA testing of my code.")
print(f"You just need to read and feed in right input {user_name}. C'mon {user_name} you can do it! :) ")
# Suggestion for future based on key words in quotes make an alexa function that recognizes who said it . | true |
aaaf8d5decbabeede4a42c2630fc1f31ec387a58 | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /08. and 09. ConditionalLogic and RPS/bouncer.py | 1,367 | 4.375 | 4 | #Psuedo Code: Ask for age
# 18-21 Wristband and No Drinks
# Method1
# age = input("How old are you: ")
# age = int(age)
# if age != "":
# if age >= 18 and age < 21:
# print("You can enter, but need a wristband ! Also no drinks for you ese!")
# # 21+ Normal Entry and Drinks
# elif age >= 21:
# print("Your age is good to enter, and can drink!")
# # else too young, sorry.
# else:
# print("You can't come in little one! :( ")
# else:
# print("You drunk or what mate ? Enter a proper number as your age.")
#Now the problem is if the user hits empty string without an int and hits enter then Python throws an error.
#To solve that problem we sub-class all the statements about age inside a if != "" if not equal to empty string. Else enter valid age.
#For now just focusing on user hitting enter and not giving asljal0923 or something stupid as an input. We'll see about that in other videos.
age = input("How old are you: ")
if age:
age = int(age)
if age >= 21:
print("You age good to enter, and can drink!")
elif age >= 18:
print("You can enter, but need a wristband ! Also no drinks for you ese!")
else:
print("You can't come in little one! :( ")
else:
print("You drunk or what mate ? Enter a proper number as your age.") | true |
f96111974debd6f8a56e9eb3d964bcf2d40517d7 | iroshan/python_practice | /recursive_sum.py | 588 | 4.28125 | 4 | def recursive_sum(n=0):
''' recursively add the input to n and print the total when the input is blank'''
try:
i = input('enter a number: ')
# base case
if not i:
print(f'total = {n}')
# check if a number
elif not i.isnumeric():
print("not a number")
recursive_sum(n)
# add the number and do recursion
else:
recursive_sum(int(i)+n)
except Exception as e:
print(e)
def main():
print("SUM OF NUMBERS")
recursive_sum()
if __name__ == '__main__':
main() | true |
65fb533a490dfcaf5ed1462f217047f7a8ae5f74 | iroshan/python_practice | /guess_the_number.py | 783 | 4.125 | 4 | from random import randint
def guess_num():
''' guess a random number between 0 and 100. while users guess is equal to the number provide clues'''
num = randint(0,100)
while True:
try:
# get the number and check
guess = int(input('enter your guess: '))
if num > guess:
print('too low')
elif num < guess:
print('too high')
else:
print('That is correct. You won')
break
except Exception as e:
print('Did you enter a valid number? The number must be between 0 and 100')
def main():
print("Guessing Game\nCan you guess my number?\nIt's between 0 and 100")
guess_num()
if __name__ == '__main__':
main()
| true |
ebfcfd2080c938b2f842bebf1e0e21a2a75b8cd6 | jayfro/Lab_Python_04 | /Minimum Cost.py | 866 | 4.3125 | 4 | # Question 4 c
groceries = [ 'bananas', 'strawberries', 'apples', 'champagne' ] # sample grocery list
items_to_price_dict = { 'apples': [ 1.1, 1.3, 3.1 ], 'bananas': [ 2.1, 1.4, 1.6, 4.2 ],
'oranges': [ 2.2, 4.3, 1.7, 2.1, 4.2 ],
'pineapples': [ 2.2, 1.95, 2.5 ], 'champagne': [ 6.5, 5.9 ],
'strawberries': [ 0.98, 1.1, 0.67, 0.99 ] } # price of products
def min_cost( grocery_list, item_to_price_list_dict ):
total_min_cost = 0
for item in grocery_list:
if item in item_to_price_list_dict:
total_min_cost = total_min_cost + min(item_to_price_list_dict[item])
print " The minimum cost is: ", total_min_cost # minimum cost
min_cost( groceries, items_to_price_dict ) | true |
a3b6a12ec18d72801bf0ee0bb8a348313ddb62fa | AZSilver/Python | /PycharmProjects/test/Homework 05.py | 2,286 | 4.4375 | 4 | # -------------------------------------------------------------------------------
# Name: Homework 05
# Purpose: Complete Homework 5
# Author: AZSilverman
# Created: 10/21/2014
# Desc: Asks the user for the name of a household item and its estimated value.
# then stores both pieces of data in a text file called HomeInventory.txt
# -------------------------------------------------------------------------------
import json
# 1: Create new manages a "ToDo list." The ToDo file will contain two columns of data, separated by a comma, called:
# Task, Priority. Use a Python Dictionary to work with the data while the program is running.
# Also use Try - Catch blocks to manage user input errors.
toDoFile = "An object that represents a file"
toDoFile = open('ToDo.txt', 'r')
#
# When the program starts, load the any data you have in a text file called ToDo.txt into a python Dictionary.
data = {}
with open("ToDo.txt") as f:
for line in f:
(key, val) = line.split()
data[key] = val
# Display the contents of the file to the user
def displayData():
for key, value in data.items():
print(key, ",", value)
displayData()
#
# .
# Allow the user to Add tasks, Remove, and save the task to a file using numbered choices like this:
# print "1. Add task"
def addTask():
taskName = str(input('What is the name of the task? '))
priorityName = str(input('What is the priority of this task? '))
data.update({taskName, priorityName})
displayData()
#
# print "2. Remove task"
def removeTask():
taskName = str(input('What is the name of the task you would like to delete? '))
try:
del data['taskName']
except KeyError:
pass
# print "3. Save tasks to file"
def saveTask():
with open("ToDo.txt") as f:
f.write(json.dumps(data))
while inputString != 3:
inputString = str(input('Please select from one of the following options'))
print('1. Add task')
print('2. Remove task')
print('3. Save tasks to file (and quit)')
if (inputString == '1'):
addTask()
elif (inputString == '1'):
removeTask()
elif (inputString == '3'):
saveTask()
else:
print('I don\'t understand an option besides 1,2 or 3. Please try again' )
toDoFile.close()
exit()
| true |
6c64f1505db0b69276f2212bc96e8ec89ef81734 | u4ece10128/Problem_Solving | /DataStructures_Algorithms/10_FactorialofAnyNumber.py | 719 | 4.5 | 4 | # Find the factorial of a given number n
def factorial_iterative(n):
"""
Calculates the factorial of a given number
Complexity: O(N)
:param n: <int>
:return: <int>
"""
result = 1
for num in range(2, n+1):
result *= num
return result
def factorial_recursive(n):
"""
Calculates the factorial of a given number using recursive approach
Complexity: O(N)
:param n: <int>
:return: <int>
"""
# base case
# we keep going until we hit th base case
if n == 2:
return 2
if n < 2:
return 1
return n * factorial_recursive(n-1)
if __name__ == "__main__":
print(factorial_iterative(5))
print(factorial_recursive(5))
| true |
de2e1abde37e6fd696a8f50d6143d491d8fb5d05 | if412030/Programming | /Python/HackerRank/Introduction/Division.py | 1,658 | 4.40625 | 4 | """ In Python, there are two kinds of division: integer division and float division.
During the time of Python 2, when you divided one integer by another integer, no matter what, the result would always be an integer.
For example:
>>> 4/3
1
In order to make this a float division, you would need to convert one of the arguments into a float.
For example:
>>> 4/3.0
1.3333333333333333
Since Python doesn't declare data types in advance, you never know when you want to use integers and when you want to use a float. Since floats lose precision, it's not advised to use them in integral calculations.
To solve this problem, future Python modules included a new type of division called integer division given by the operator //.
Now, / performs float division, and // performs integer division.
In Python 2, we will import a feature from the module __future__ called division.
>>> from __future__ import division
>>> print 4/3
1.3333333333333333
>>> print 4//3
1
Note: The __ in __future__ is a double underscore.
Task
Read two integers and print two lines. The first line should contain integer division, aa//bb. The second line should contain float division, aa/bb.
You don't need to perform any rounding or formatting operations.
Input Format
The first line contains the first integer, aa. The second line contains the second integer, bb.
Output Format
Print the two lines as described above.
Sample Input
4
3
sample Output
1
1.3333333333333333
"""
#submissions
# Enter your code here. Read input from STDIN. Print output to STDOUT
from __future__ import division
a = int(raw_input())
b = int(raw_input())
print a // b
print a / b
| true |
0fdb20e59477fd96d05f5c3d2ed9abcbb0201e39 | if412030/Programming | /Python/HackerRank/Introduction/ModDivmod.py | 1,002 | 4.5 | 4 | """ One of the built-in functions of Python is divmod, which takes two arguments aa and bb and returns a tuple containing the quotient of a/ba/b first and then the remainder aa.
For example:
>>> print divmod(177,10)
(17, 7)
Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7.
Task
Read in two integers, aa and bb, and print three lines.
The first line is the integer division a//ba//b (Remember to import division from __future__).
The second line is the result of the modulo operator: a%ba%b.
The third line prints the divmod of aa and bb.
Input Format
The first line contains the first integer, aa, and the second line contains the second integer, bb.
Output Format
Print the result as described above.
Sample Input
177
10
Sample Output
17
7
(17, 7)
"""
#submissions
# Enter your code here. Read input from STDIN. Print output to STDOUT
from __future__ import division
a = int(raw_input())
b = int(raw_input())
print a // b
print a % b
print divmod(a,b)
| true |
762121b1d623ce8b5fc62b6234b333c67187131e | Ro7nak/python | /basics/Encryption_Decryption/module.py | 621 | 4.625 | 5 | # encrypt
user_input = input("Enter string: ")
cipher_text = '' # add all values to string
for char in user_input: # for every character in input
cipher_num = (ord(char)) + 3 % 26 # using ordinal to find the number
# cipher = ''
cipher = chr(cipher_num) # using chr to convert back to a letter
cipher_text = (cipher_text + cipher)
print(cipher_text)
# decrypt
decrypt_text = ''
for char in cipher_text: # for every character in the encrpted text
decrypt_num = (ord(char)) - 3 % 26
# decrypt = ''
decrypt = chr(decrypt_num)
decrypt_text = (decrypt_text + decrypt)
print(decrypt_text)
| true |
d85a139d910c67059507c6c73d49be723f3faa56 | bugmark-trial/funder1 | /Python/sum_of_digits_25001039.py | 349 | 4.25 | 4 | # Question:
# Write a Python program that computes the value of a+aa+aaa+aaaa with a given
# digit as the value of a.
#
# Suppose the following input is supplied to the program:
# 9
# Then, the output should be:
# 11106
#
# Hints:
# In case of input data being supplied to the question, it should be
#
# assumed to be a console input.
#
# Solution:
| true |
e10eae47d7a19efb93d76caeb2f6a2752cdd6666 | dichen001/CodeOn | /HWs/Week 5/S5_valid_anagram.py | 1,626 | 4.125 | 4 | """
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
"""
def isAnagram(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
### Please start your code here###
letterCtr = {}
for sVals in s:
if sVals in letterCtr:
letterCtr[sVals] += 1
if not sVals in letterCtr:
letterCtr[sVals] = 1
for key, val in letterCtr.iteritems():
if not t.count(key) == val:
return False
return True
### End ###
"""
Below are the test cases I created for testing the correctness of your code.
Please don't modify them when you push the file back to GitHub
"""
if __name__ == '__main__':
test0 = ("anagram", "nagaram", True)
test1 = ("rat","tar", True)
test2 = ("sdfd","d987", False)
test3 = ("23ss","ii", False)
test4 = ("rat","rt", False)
tests = [test0, test1, test2, test3, test4]
for i, test in enumerate(tests):
print("------------- Test " +str(i) + " -------------")
print("-Test Input:")
print(test[0], test[1])
print("-Expected Output:")
print(test[2])
print("-Your Output:")
your_ans = isAnagram(test[0], test[1])
print(your_ans)
print(test[2])
assert your_ans == test[2], "Wrong return. Please try again."
print('\n**** Congratulations! You have passed all the tests! ****')
| true |
bd90689da08ce04c428fdf4781e06e935bce3243 | vinaypathak07/codezilla | /Sorting/Merge Sort/Python/merge_sort.py | 1,107 | 4.25 | 4 | def merge_sort(array_list, start, end):
'''Sorts the list from indexe start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(array_list, start, mid)
merge_sort(array_list, mid, end)
merge_list(array_list, start, mid, end)
'''Merges each sorted left list and right list'''
def merge_list(array_list, start, mid, end):
left = array_list[start:mid]
right = array_list[mid:end]
k = start
i = 0
j = 0
while (start + i < mid and mid + j < end):
if (left[i] <= right[j]):
array_list[k] = left[i]
i = i + 1
else:
array_list[k] = right[j]
j = j + 1
k = k + 1
if start + i < mid:
while k < end:
array_list[k] = left[i]
i = i + 1
k = k + 1
else:
while k < end:
array_list[k] = right[j]
j = j + 1
k = k + 1
array_list = [84,29,49,91,17,77,31,10,44,55,20,39]
merge_sort(array_list, 0, len(array_list))
print('Sorted list: ', end='')
print(array_list)
| false |
3e73ef211d9d20808bad316e3d1f8493a386abd7 | joeyyu10/leetcode | /Array/56. Merge Intervals.py | 731 | 4.21875 | 4 | """
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
"""
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
res = []
intervals.sort(key=lambda x: x[0])
for x in intervals:
if res and x[0] <= res[-1][1]:
res[-1][1] = max(res[-1][1], x[1])
else:
res.append(x)
return res
| true |
886bcb3990f524a5495b4254f71d6f6d03986a9f | reemanaqvi/HW06 | /HW06_ex09_06.py | 939 | 4.34375 | 4 | #!/usr/bin/env python
# HW06_ex09_05.py
# (1)
# Write a function called is_abecedarian that returns True if the letters in a
# word appear in alphabetical order (double letters are ok).
# - write is_abecedarian
# (2)
# How many abecedarian words are there?
# - write function(s) to assist you
# - number of abecedarian words:
##############################################################################
# Imports
# Body
def is_abecedarian(word):
if len(word) <= 1:
return True
if word[0] > word[1]:
return False
else:
return is_abecedarian(word[1:])
##############################################################################
def main():
# pass # Call your function(s) here.
counter = 0
fin = open("words.txt", "r")
for word in fin:
if is_abecedarian(word):
counter +=1
fin.close()
print ("The number of abecedarian words is: %d") %(counter)
if __name__ == '__main__':
main()
| true |
3b4ac26a260e4a0118d90637899ee3755c975a97 | aburmd/leetcode | /Regular_Practice/easy/17_371_Sum_of_Two_Integers.py | 1,883 | 4.125 | 4 | """
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
"""
class Solution:
def getPositivesum(self,a,b):
while b!=0:
bitcommon=a&b #Example: 4(100),5(101) bit common(a&b) is 4(100)
a=a^b #Example: 4(100),5(101) bit diff(a^b) is 1(001)
b=bitcommon<<1 #Example: one shift, 4 one shift (4(100)<<1) is 8(1000)
return a
def getNegativesum(self,apos,bneg):
upperbound=0xfffffffff #f-1111 ie 0xf-15 define the max value for calculation
upperbound_plus1=self.getPositivesum(upperbound,1)
b=bneg&0xfffffffff #negative value starts in reverse order from upperbound
#like (-1&0xf->15,-1&0xff->255) here -1&0xfffffffff = -1=68719476735)
a=self.getPositivesum(apos,b)
if a==upperbound:
return -1
elif a>upperbound:
return a%upperbound_plus1
else:
return -1*((-1*a)&0xfffffffff)
def getSum(self,a, b):
if a==(-1)*b:
return 0
elif a>=0 and b>=0:
return self.getPositivesum(a,b)
elif a<=0 and b<=0:
apos=-1*a
bpos=-1*b
return -1*self.getPositivesum(apos,bpos)
else:
if b<0:
return self.getNegativesum(a,b)
else:
return self.getNegativesum(b,a)
"""
SecondCommit:
Runtime: 24 ms, faster than 91.03% of Python3 online submissions for Sum of Two Integers.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Sum of Two Integers..
FirstCommit:
Runtime: 24 ms, faster than 92.83% of Python3 online submissions for Sum of Two Integers.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Sum of Two Integers.
"""
| true |
9eba98a92942adeb3cffc9bab950d03c384e56c0 | MarthaSamuel/simplecodes | /OOPexpt.py | 1,142 | 4.46875 | 4 | #experimenting with Object Orienting Programming
#defining our first class called apple
class Apple:
pass
#we define 2 attributes of the class and initialize as strings
class Apple:
color = ''
flavor = ''
# we define an instance of the apple class(object)
jonagold = Apple()
# attributes of the object
jonagold.color = 'red'
jonagold.flavor = 'sweet'
print(jonagold.color.upper())
# another instance
golden = Apple()
golden.color ='yellow'
golden.flavor = 'soft'
# this prints a poem
class Flower:
pass
rose = Flower()
rose.color = 'red'
violet = Flower()
violet.color= 'blue'
pun = 'This pun is for you'
print('Roses are {}'.format(rose.color))
print('Violets are {}'.format(violet.color))
print(pun)
#sample 3
class Furniture:
color = ''
material = ''
table = Furniture()
table.color = 'brown'
table.material = 'wood'
couch = Furniture()
couch.color = 'red'
couch.material = 'leather'
def describe_furniture(piece):
return ('This piece of furniture is made of {} {}'.format(piece.color, piece.material))
print(describe_furniture(table))
print(describe_furniture(couch))
dir(" ")
help({})
help(Apple)
| true |
4ac5b4a4d773a73aa6768d57afd9e44a3482cb86 | AllenWang314/python-test-scaffolding | /interview.py | 275 | 4.3125 | 4 |
""" returns square of a number x
raises exception if x is not of type int or float """
def square(x):
if type(x) != int and type(x) != float:
raise Exception("Invalid input type: type must be int or float")
print(f"the square is {x**2}")
return x**2
| true |
84ed875a37f483f8acfa592c24bd6c9dd5b4cbf7 | RuchirChawdhry/Python | /all_capital.py | 1,163 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by Ruchir Chawdhry
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
"""
Write a program that accept a sequence of lines* and prints the lines
as input and prints the lines after making all the characters
in the sequence capitalized.
*blank line or CTRL+D to terminate
"""
import sys
def all_caps():
lines = list()
while True:
sequence = input()
if sequence:
lines.append(str(sequence.upper()))
else:
break
return "\n".join(lines)
def all_caps_eof():
print("[CTRL+D] to Save & Generate Output")
lines = list()
while True:
try:
sequence = input()
except EOFError:
break
lines.append(str(sequence.upper()))
return "\n".join(lines)
def all_caps_readlines():
print("[CTRL+D] to Save & Generate Output")
lines = sys.stdin.readlines()
return f"\n\nALL CAPS:\n {' '.join(lines).upper()}"
# use single quotes w/ .join() when using it in fstring
if __name__ == "__main__":
print(all_caps_readlines())
| true |
656ae9779498767407dfbec47689c6aaf15907d3 | RuchirChawdhry/Python | /circle_class.py | 984 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by Ruchir Chawdhry
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
"""
Define a class 'Circle' which can be constructed by either radius or diameter.
The 'Circle' class has a method which can compute the area and perimeter.
"""
import math
class Circle:
def __init__(self, radius=0, diameter=0):
self.radius = radius
self.diameter = diameter
def _area(self):
if self.diameter:
self.radius = self.diameter / 2
return math.pi * (self.radius * self.radius)
def _perimeter(self):
if self.diameter:
self.radius = self.diameter / 2
return 2 * math.pi * self.radius
def compute(self):
return [self._area(), self._perimeter()]
if __name__ == "__main__":
c = Circle(diameter=10)
print(f"Area of Cricle: {c.compute()[0]} \nPerimeter of Circle: {c.compute()[1]}")
| true |
f3c2abbab1697397006113c42c1fc03568d17719 | Sanchi02/Dojo | /LeetCode/Strings/ValidPalindrome.py | 742 | 4.125 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Note: For the purpose of this problem, we define empty string as valid palindrome.
# Example 1:
# Input: "A man, a plan, a canal: Panama"
# Output: true
# Example 2:
# Input: "race a car"
# Output: false
# Constraints:
# s consists only of printable ASCII characters.
class Solution:
def isPalindrome(self, s: str) -> bool:
modified = ''
s = s.lower()
for c in s:
if(c.isalnum()):
modified = modified + c
size = len(modified)
for i in range(size//2):
if(modified[i]!=modified[size-i-1]):
return False
return True | true |
768e42c29a97bcf3c2d6ec5992d33b9458fb56e8 | ujjwalshiva/pythonprograms | /Check whether Alphabet is a Vowel.py | 256 | 4.40625 | 4 | # Check if the alphabet is vowel/consonant
letter=input("Enter any letter from a-z (small-caps): ")
if letter == 'a' or letter =='e' or letter =='i' or letter =='o' or letter =='u':
print(letter, "is a Vowel")
else:
print(letter, "is a Consonant")
| true |
9c8c2d07f6bd60fbcadebf7d533a6e3124fef4ae | davidwang0829/Python | /小甲鱼课后习题/43/习题2.py | 705 | 4.125 | 4 | # 定义一个单词(Word)类继承自字符串,重写比较操作符,当两个Word类对象进行比较时
# 根据单词的长度来进行比较大小(若字符串带空格,则取第一个空格前的单词作为参数)
class Word(str):
def __new__(cls, args):
if ' ' in args:
args = args[:args.index(' ')]
return str.__new__(cls, args) # 将去掉括号的字符串作为新的参数初始化
def __lt__(self, other):
return len(self) < len(other)
def __le__(self, other):
return len(self) <= len(other)
def __gt__(self, other):
return len(self) > len(other)
def __ge__(self, other):
return len(self) <= len(other)
| false |
16e13a2f6042e3deae198df89a2956f6648edfb4 | davidwang0829/Python | /小甲鱼课后习题/34/习题2.py | 1,464 | 4.15625 | 4 | # 使用try…except语句改写第25课习题3
print('''--- Welcome to the address book program ---
--- 1:Query contact information ---
--- 2:Insert a new contact ---
--- 3:Delete existing contacts ---
--- 4:Exit the address book program ---''')
dic = dict()
while 1:
IC = input('\nPlease enter the relevant instruction code:')
if IC == '1':
name = input("Please enter the contact's name:")
try:
print(name + ':' + dic[name])
except KeyError:
print('Sorry,the program failed to find the contact')
if IC == '2':
key = input("Please enter the contact's name:")
try:
print('''The name you entered already exists in the address book
-->> %s:%s''' % (key, dic[key]))
if input('Whether to modify the user information?(y/n)') == 'y':
dic[key] = input('Please enter the new contact number:')
except KeyError:
dic[key] = input('Please enter the user contact number:')
if IC == '3':
key = input("Please enter the contact's name:")
try:
del(dic[key])
print('Address book has been successfully emptied')
except KeyError:
print('Sorry,the program failed to find the contact')
if IC == '4':
break
else:
print('You may entered a wrong instruction code.Please enter the correct instruction code')
print('--- Thanks for using address book program ---')
| true |
e2ff4a0f6df1717d29370cb9ce43fb6741aa9632 | davidwang0829/Python | /小甲鱼课后习题/45/属性访问.py | 775 | 4.1875 | 4 | # 写一个矩形类,默认有宽和高两个属性
# 如果为一个叫square的属性赋值,那么说明这是一个正方形
# 值就是正方形的边长,此时宽和高都应该等于边长
class Rectangle:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
def __setattr__(self, name, value):
if name == 'square':
self.width = self.height = value
else:
self.name = value
r = Rectangle(3, 4)
# 看似正确,实则会导致无限递归
# 因为赋值时会一直调用__setattr__()函数而无法得到返回值
# 解决方案:
# ①else下改为super().__setattr__(name, value) 调用基类方法
# ②else下改为self.__dict__[name] = value 修改实例的字典属性
| false |
be23213891eb1945990bd61cec32c986a29fba49 | matvelius/Selection-Sort | /selection_sort.py | 1,825 | 4.3125 | 4 | # The algorithm divides the input list into two parts:
# the sublist of items already sorted, which is built up from left
# to right at the front (left) of the list, and the sublist of items
# remaining to be sorted that occupy the rest of the list.
# Initially, the sorted sublist is empty and the unsorted sublist is
# the entire input list. The algorithm proceeds by finding the smallest
# (or largest, depending on sorting order) element in the unsorted
# sublist, exchanging (swapping) it with the leftmost unsorted element
# (putting it in sorted order), and moving the sublist boundaries one
# element to the right.
myArray = [7, 3, -1, 0, 9, 2, 4, 6, 5, 8]
def selectionSort(array):
if len(array) <= 1:
print("array length is 1 or less")
return array
unsortedIndex = 0
endOfArrayIndex = len(array)
while unsortedIndex < endOfArrayIndex:
print(f"starting another iteration of the while loop; unsortedIndex: {unsortedIndex}")
# find smallest value in unsorted array
smallestValue = array[unsortedIndex]
smallestValueIndex = unsortedIndex
for index in range(unsortedIndex, endOfArrayIndex):
if array[index] < smallestValue:
smallestValue = array[index]
smallestValueIndex = index
print(f"smallestValue found: {smallestValue} and index: {smallestValueIndex}")
# swap the smallest value with leftmost value
if array[smallestValueIndex] < array[unsortedIndex]:
swap(unsortedIndex, smallestValueIndex, array)
print(f"result so far: {array}")
unsortedIndex += 1
print(array)
return array
# i & j are indices of numbers to swap
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
selectionSort(myArray) | true |
52ae48b48dd9f7c9a60970dab786b3a02a7f76b0 | abhi15sep/Python-Course | /introduction/loops/Loop_Example/exercise.py | 637 | 4.125 | 4 | # Use a for loop to add up every odd number from 10 to 20 (inclusive) and store the result in the variable x.
# Add up all odd numbers between 10 and 20
# Store the result in x:
x = 0
# YOUR CODE GOES HERE:
#Solution Using a Conditional
for n in range(10, 21): #remember range is exclusive, so we have to go up to 21
if n % 2 != 0:
x += n
#Solution using range step
#Instead of looping over every number between 10 and 20, this solution only loops over the odd numbers. Remember, the 3rd argument to range() is the STEP or interval that you want the range to increment by.
x = 0
for i in range(11, 21, 2):
x += i
| true |
684a6a2571adb3bb17ea97230600d5ae76ed6570 | abhi15sep/Python-Course | /collection/Dictionaries/examples/Dictionary.py | 1,581 | 4.5625 | 5 |
"""
A dictionary is very similar to a set, except instead of storing single values like numbers or strings, it associates those values to something else. This is normally a key-value pair.
For example, we could create a dictionary that associates each of our friends' names with a number describing how long ago we last saw them:
"""
my_friends = {
'Jose': 6,
'Rolf': 12,
'Anne': 6
}
"""
The same constraints as sets apply, but only on the keys. You cannot have duplicate keys, and the keys are not ordered. The values can be duplicated as many times as you want.
However, you cannot add or subtract dictionaries like you can do with sets.
"""
## Nested dictionaries
"""
You can have anything as the value for a key.
That includes a using a dictionary as a value!
"""
my_friends = {
'Jose': { 'last_seen': 6 },
'Rolf': { 'surname': 'Smith' },
'Anne': 6
}
"""
Notice how the values are each independent objects. They don't need to have the same keys (although they can).
They don't even all have to be dictionaries! They can be anything you want them to be.
"""
## Lists and dictionaries
players = [
{
'name': 'Rolf',
'numbers': (13, 22, 3, 6, 9)
},
{
'name': 'John',
'numbers': (22, 3, 5, 7, 9)
}
]
# How could we select one of these?
player = players[0]
# How could we add all the numbers of a player?
sum(player['numbers'])
# We have a function that takes in a list—it does not have to be a list of numbers
# of a player. Indeed, we could do something like this:
sum([1, 2, 3, 4, 5])
| true |
52432f6633d264b1f53d9c6e8a9bb834e4532d7b | abhi15sep/Python-Course | /introduction/example/lucky.py | 502 | 4.15625 | 4 | #At the top of the file is some starter code that randomly picks a number between 1 and 10, and saves it to a variable called choice. Don't touch those lines! (please).
#Your job is to write a simple conditional to check if choice is 7, print out "lucky". Otherwise, print out "unlucky".
# NO TOUCHING PLEASE---------------
from random import randint
choice = randint(1, 10)
# NO TOUCHING PLEASE---------------
# YOUR CODE GOES HERE:
if choice == 7:
print("lucky")
else:
print("unlucky") | true |
2eab7e313a1104ca9384d3c73f8e3d3b10ff4491 | abhi15sep/Python-Course | /Functions/examples/exercise4.py | 600 | 4.4375 | 4 | #Implement a function yell which accepts a single string argument. It should return(not print) an uppercased version of the string with an exclamation point aded at the end. For example:
# yell("go away") # "GO AWAY!"
#yell("leave me alone") # "LEAVE ME ALONE!"
#You do not need to call the function to pass the tests.
#Using string concatenation:
def yell(word):
return word.upper() + "!"
#Using the string format() method:
def yell(word):
return "{}!".format(word.upper())
#Using an f-string. But only works in python 3.6 or later.
def yell(word):
return f"{word.upper()}!"
| true |
b8c247b00db447a205409067aad84ea853ad2040 | abhi15sep/Python-Course | /introduction/example/positive_negative_check.py | 970 | 4.46875 | 4 | # In this exercise x and y are two random variables. The code at the top of the file randomly assigns them.
#1) If both are positive numbers, print "both positive".
#2) If both are negative, print "both negative".
#3) Otherwise, tell us which one is positive and which one is negative, e.g. "x is positive and y is negative"
# NO TOUCHING ======================================
from random import randint
x = randint(-100, 100)
while x == 0: # make sure x isn't zero
x = randint(-100, 100)
y = randint(-100, 100)
while y == 0: # make sure y isn't zero
y = randint(-100, 100)
# NO TOUCHING ======================================
# YOUR CODE GOES HERE
if x > 0 and y > 0:
print("both positive")
elif x < 0 and y < 0:
print("both negative")
elif x > 0 and y < 0:
print("x is positive and y is negative")
else:
print("y is positive and x is negative")
print("y is positive and x is negative")
print("y is positive and x is negative") | true |
df9627b825c32214c312f45d1518e7d70c6485e8 | OhOverLord/loft-Python | /Изучение numpy/6.py | 678 | 4.1875 | 4 | """
Считайте 2 числа:
n - размер Numpy вектора
x - координата элемента вектора, который должен быть равен 1. Остальные элементы вектора должны быть равны 0.
Сохраните вектор в переменную Z.
Примечание. В этой задаче не нужно ничего выводить на печать. Только создать вектор Z.
Sample Input:
10
4
Sample Output:
<class 'numpy.ndarray'>
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
"""
import numpy as np
n = int(input())
x = int(input())
Z = np.zeros(n)
Z[x] = 1 | false |
9d18ab098eb2d59fbba6595cbc157dd3b629d87a | yogabull/LPTHW | /ex14.py | 789 | 4.15625 | 4 | # Exercise 14: Prompting and Passing
from sys import argv
script, user_name, last_name, Day = argv
#prompt is a string. Changing the variable here, changes every instance when it is called.
prompt = 'ENTER: '
#the 'f' inside the parenthesis is a function or method to place the argv arguements into the sentence.
print(f'Hi {user_name} {last_name}, I\'m the {script} script.')
print("I'd like to ask you a few questions.")
print(f"Do you like me {user_name}?")
likes = input(prompt)
print(f"Where do you live {user_name}?")
lives = input(prompt)
print("What kind of computer do you have?")
computer = input(prompt)
print(f"""
Alright, so you said {likes} about liking me.
Today is {Day}, and
you live in {lives}. Not sure where that is.
And you have a {computer} computer. Nice
""")
| true |
b7f1467fbb432ee2765720bc0b13744e7783f367 | shangpf1/python_homework | /2019-6-13.py | 919 | 4.1875 | 4 | """
我的练习作业03- python 高级排序-字符长度相同进行排序
"""
# 正序(关于正序排序,首先会按字符的长度排序,如果一样的话,会按字符正序的首字母的ASCII码大小排序)
strs = ['study','happy','thing']
print('s==>',ord('s'),'h===>',ord('h'),'t===>',ord('t'))
strs.sort()
print("正序排序为:",strs)
"""
倒序(关于倒序排序,和上面的正序刚好相反,从字符的末尾的字符大小进行排序,如果末尾字符相同,
会按倒数第二位的字符大小排序,如此类推)
"""
print('g====',ord('g'),'y======',ord('y'),'p===',ord('p'),'d====',ord('d'))
strs.sort(key=len,reverse=True)
print("倒序排序为:",strs)
"""
运行结果如下:
s==> 115 h===> 104 t===> 116
正序排序为: ['happy', 'study', 'thing']
g==== 103 y====== 121 p=== 112 d==== 100
倒序排序为: ['happy', 'study', 'thing']
""" | false |
9b42a6f0b8fe9d7ebca325e29b0f1695c24df199 | mxcat1/Curso_python3 | /Curso Python37 Avanzado/tuplas/tuplas.py | 643 | 4.28125 | 4 | tupla1=("cinco",4,"hola",34)
print(tupla1)
# convertir una tupla en lista
lista1=list(tupla1)
print(lista1)
#convertir una lista en tupla
tupla2=tuple(lista1)
print(tupla2)
#metodo in
print("cinco" in tupla2)
# metodo para saber la cantidad de elementos
print(tupla2.count(4))
# metodo len para saber la logitud de una tupla
print(len(tupla2))
#tupla de un unico elemento
tuplauno=("Pedro",)
print(tuplauno," ",len(tuplauno))
# DESEMPAQUETADO DE TUPLA
tuplades=("Juan",13,1,1995)
nombre,dia,mes,anio=tuplades
print(nombre," ",dia,"/",mes,"/",anio)
#sacar el indice de un elemento de una tupla o una lista
print(tuplades.index(13)) | false |
ef8d22e8ab44d0a3cad96db2c94779ab98c2d11c | Catrinici/Python_OOP | /bike_assignement.py | 1,177 | 4.28125 | 4 | class Bike:
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = abs(0)
def ride(self):
print("Riding!")
self.miles += 10
print(f"Total miles : {self.miles}")
return self
def reverse(self):
print("Reversing!")
self.miles -= 5
print(f"Total miles : {abs(self.miles)}")
return self
def displayInfo(self):
print(
f"The price of this bike is ${ self.price }. The maximum speed is {self.max_speed}.Total riding miles is: {abs(self.miles)} miles")
return self
# Have the first instance ride three times, reverse once and have it displayInfo().
bike1 = Bike(200,"24mph",0)
i = 1
while i <=3:
bike1.ride()
i+=1
bike1.reverse().displayInfo()
# Have the second instance ride twice, reverse twice and have it displayInfo().
bike2 = Bike(150,"20mph",0)
i = 1
while i <=2:
bike2.ride().reverse()
i+=1
bike2.displayInfo()
# Have the third instance reverse three times and displayInfo().
bike3 = Bike(110,"18mph",0)
i = 1
while i <=3:
bike3.reverse()
i+=1
bike3.displayInfo()
| true |
459bbf3c436621c0b769c07740b44261bb84ff3d | Abeilles14/Java_exercises | /6.32_IfThenElseChallenge/IfThenElseChallenge.py | 274 | 4.15625 | 4 | #isabelle andre
#14-07/18
#if challenge
name = input("Enter your name: ")
age = int(input("Enter your age: "))
#if age >= 18 and age <= 30:
if 18 >= age <= 30:
print("Welcome to the 18-30 holiday, {}".format(name))
else:
print ("You are not eligible to enter the holiday") | true |
8d69bd1f68bd1dfe19adb1909d0ed541fdef7b7c | mmsamiei/Learning | /python/dictionary_examples/create_grade_dictionary.py | 532 | 4.1875 | 4 | grades = {}
while(True):
print("Enter a name: (blank to quit):")
name = raw_input()
if name == '':
break
if name in grades:
print(' {grade} is the grade of {name} ').format(grade=grades[name],name=name)
else:
print("we have not the grade of {name}").format(name=name)
print("what is his/her grade?:")
grade = input()
grades[name]=grade
print("Yes we updated database")
for name in grades:
print "{name} : {grade}".format(name=name,grade=grades[name])
| true |
6a07533146042655f2780ff329ecaff3089cedd6 | ziyuanrao11/Leetcode | /Sum of 1d array.py | 2,483 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 14:41:32 2021
@author: rao
"""
'''Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].'''
from typing import List
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
length=len(nums)
nums_new=[]
for i in range(length):
if i==0:
add=nums[i]
nums_new.append(add)
else:
add=nums[i]
for j in range(i):
add=add+nums[j]
nums_new.append(add)
return nums_new
nums=[0,1,2,3,4]
s=Solution()
nums_new=s.runningSum(nums)
print(nums_new)
'''standard answer'''
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
return [sum(nums[:i + 1]) for i in range(len(nums))]
nums=[0,1,2,3,4]
s=Solution()
nums_new=s.runningSum(nums)
print(nums_new)
'''improved answer based on mine'''
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
length=len(nums)
nums_new=[]
for i in range(length):
add=sum(nums[:i+1])
nums_new.append(add)
return nums_new
nums=[0,1,2,3,4]
s=Solution()
nums_new=s.runningSum(nums)
print(nums_new)
'''another'''
class Solution:
def runningSum(self, nums):
temp_sum = 0
for i, num in enumerate(nums):
nums[i] += temp_sum
temp_sum = nums[i]
return nums
'''another'''
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums)):
nums[i] += nums[i-1]
return nums
'''another'''
class Solution:
def runningSum(self, nums):
summ=0
lst=[]
for i in nums:
summ+=i
lst.append(summ)
return lst
'''the best'''
class Solution(object):
def runningSum(self, nums):
for i in range(1, len(nums)):
nums[i] = nums[i-1] + nums[i]
return nums | true |
6b20a2136e8449a61778778b4799211c391e4952 | pandiarajan-src/PyWorks | /Learn/ceaser_ciper.py | 2,026 | 4.1875 | 4 | '''Implement Ceaser Cipher encryption and decryption
https://en.wikipedia.org/wiki/Caesar_cipher.'''
def ceaser_ciper_encryption(input_to_encode, key_length):
"""Ceaser Encryption method"""
enc_output = chech_char = ""
for letter in input_to_encode:
if letter.isalpha():
n_uni_char = ord(letter) + key_length
chech_char = 'Z'
if letter.islower():
chech_char = 'z'
if n_uni_char > ord(chech_char):
n_uni_char -= 26
enc_output += chr(n_uni_char)
else:
enc_output += letter
return enc_output
def ceaser_ciper_decryption(input_to_encode, key_length):
"""Ceaser Encryption method"""
enc_output = chech_char = ""
for letter in input_to_encode:
if letter.isalpha():
n_uni_char = ord(letter) - key_length
chech_char = 'A'
if letter.islower():
chech_char = 'a'
if n_uni_char < ord(chech_char):
n_uni_char += 26
enc_output += chr(n_uni_char)
else:
enc_output += letter
return enc_output
if __name__ == "__main__":
try:
KEY_LENGTH = int(input("Enter Key Length between 1 to 25: "))
if(KEY_LENGTH < 1 or KEY_LENGTH > 25):
print("Key length should be between 1 to 25")
raise ValueError
USER_INPUT = input("Enter a message to encode: ")
USER_ENC_OUTPUT = ceaser_ciper_encryption(USER_INPUT, KEY_LENGTH)
USER_DEC_OUTPUT = ceaser_ciper_decryption(USER_ENC_OUTPUT, KEY_LENGTH)
print("User Input : {0} \nEncoded Output : {1} \nDecoded Output : {2}"\
.format(USER_INPUT, USER_ENC_OUTPUT, USER_DEC_OUTPUT))
except ValueError:
print("input value error, please ensure that it is proper")
except Exception as ex_val: #pylint: disable=broad-except
print("Unknow error happend on main : {0}".format(ex_val.__str__))
else:
print("***Thanks***")
| false |
ee1fdb8b1af9f44ce15f191c158abebf1e4a2fbd | pandiarajan-src/PyWorks | /Learn/date.py | 1,685 | 4.3125 | 4 | '''Experiment on date, time and year fields'''
from datetime import datetime, timedelta #, date
def print_today_yesterday_lw_date():
"""Print today's date, yesterday;s date and last week this day"""
print(f"Today's date is {str(datetime.now())}")
print(f"Yesterday's date is {str(datetime.now() - timedelta(days=1))}")
print(f"Last week's this day is {str(datetime.now() - timedelta(weeks=1))}")
def birthday_prints():
"""print your birthday in different ways"""
birth_date_as_string = input("Enter your Birthday in the following format dd/mm/yyyy : ")
birth_date = datetime.strptime(birth_date_as_string, '%d/%m/%Y')
print(f"your birthday is {str(birth_date)}")
bday_string = "your birthday short is {0:%d}-{0:%B}-{0:%Y}".format(birth_date)
print(bday_string)
return bday_string, birth_date, birth_date_as_string
def is_leap_year(year_input):
"""Find whether the given year is leap or not"""
is_leap = False
try:
if year_input%400 == 0:
is_leap = True
elif (year_input%100 != 0) & (year_input%4 == 0):
is_leap = True
else:
is_leap = False
except ArithmeticError:
print("Arithmetic error occured")
except: # pylint: disable=bare-except
print("exception occured")
return is_leap
if __name__ == "__main__":
#INPUT_YEAR = int(input("Enter year (non -ve & non-zero & non-decimal: "))
for INPUT_YEAR in [2000, 1959, 2019, 2020, 2008, 2009]:
print("Year {0} - Is it leap year? {1}".format(INPUT_YEAR, is_leap_year(INPUT_YEAR)))
birthday_prints()
print_today_yesterday_lw_date()
| false |
eb5b36fd683ead2eb4205f18ab6897eb76327aa0 | pandiarajan-src/PyWorks | /educative_examples/benchmarking_ex3.py | 1,192 | 4.15625 | 4 | # Benchmarking
# Create a Timing Context Manager
"""
Some programmers like to use context managers to time small pieces of code. So let’s create our own timer context manager class!
"""
import random
import time
class MyTimer():
def __init__(self):
self.start = time.time()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
end = time.time()
runtime = end - self.start
msg = 'The function took {time} seconds to complete'
print(msg.format(time=runtime))
def long_runner():
for x in range(5):
sleep_time = random.choice(range(1,5))
time.sleep(sleep_time)
if __name__ == '__main__':
with MyTimer():
long_runner()
"""
In this example, we use the class’s __init__ method to start our timer.
The __enter__ method doesn’t need to do anything other then return itself.
Lastly, the __exit__ method has all the juicy bits. Here we grab the end time, calculate the total run time and print it out.
The end of the code actually shows an example of using our context manager where we wrap the function from the previous example in our custom context manager.
""" | true |
e86df3f56dc9ca95f6a2018b41e19aa3fc7f8e5b | pandiarajan-src/PyWorks | /Learn/converters_sample.py | 1,108 | 4.28125 | 4 | '''This example script shows how to convert different units - excercise for variables'''
MILES_TO_KILO_CONST = 1.609344
RESOLUTION_CONST = 2
def miles_to_kilometers(miles):
"""Convert given input miles to kilometers"""
return round((miles * MILES_TO_KILO_CONST), RESOLUTION_CONST)
def kilometers_to_miles(kilometers):
"""Convert given inputs kilometers to miles"""
return round((kilometers/MILES_TO_KILO_CONST), RESOLUTION_CONST)
def main():
"""main method to execute the complete code"""
try:
input_data = int(input("Enter input for miles to kilo and vice-versa : "))
print("Input: {0} Miles to Kilometers : {1}".format(input_data, \
miles_to_kilometers(input_data)))
print("Input: {0} Kilometers to Miles : {1}".format(input_data, \
kilometers_to_miles(input_data)))
except Exception as e_catch: # pylint: disable=broad-except
print("Exception message {0}".format(e_catch.__str__))
if __name__ == "__main__":
main()
| true |
58ef0063ab66182a98cfeb82a2173be41952ac75 | chigginss/guessing-game | /game.py | 1,870 | 4.21875 | 4 | """A number-guessing game."""
from random import randint
def guessing_game():
# pick random number
repeat = "Y"
scores = []
#Greet player and get the player name rawinput
print("Hello!")
name = raw_input("What is your name? ")
while repeat == "Y":
start = int(raw_input("Choose a starting number: "))
end = int(raw_input("Choose an ending number: "))
number = randint(start, end)
# Get the player to chose a number between 1 and 100 rawinput
print("%s, I'm thinking of a number between 1 and 100, guess my number! You only get three guesses!") % name
# print try to guess my number!
digit = 0
guess = 0
while digit < 15 and guess != number:
try:
guess = int(raw_input("What is your guess? "))
if guess < 1 or guess > 100:
print("Follow the instructions!!")
elif guess < number:
print("Your guess is too low, try again!")
elif guess > number:
print("Your guess is too high, try again!")
except ValueError:
print("Follow the instructions!!")
digit += 1
if guess == number:
scores.append(digit)
lowest_score = min(scores)
print("Congrats %s! You found my number in %d tries! \nYour best score is %d") % (name, digit, lowest_score)
else:
print("Too many tries!")
repeat = raw_input("Do you want to play again? Y or N: ")
guessing_game()
#two rawinput for the start and end number at line 15
#change line 24 to var start and end
#bigger the range the harder the game is >> 100 vs 50, the larger range is 2X,
#divide larger range by smaller 5(2) for 50 and 5(1) for 100
#measuring range: end - start + 1 = range
| true |
fd6d45ba6fecb3605e025a74ed5f56abc63e6625 | slayer6409/foobar | /unsolved/solar_doomsday.py | 1,692 | 4.4375 | 4 | """
Solar Doomsday
==============
Who would've guessed? Doomsday devices take a LOT of power. Commander Lambda wants to supplement the LAMBCHOP's quantum antimatter reactor core with solar arrays, and she's tasked you with setting up the solar panels.
Due to the nature of the space station's outer paneling, all of its solar panels must be squares. Fortunately, you have one very large and flat area of solar material, a pair of industrial-strength scissors, and enough MegaCorp Solar Tape(TM) to piece together any excess panel material into more squares. For example, if you had a total area of 12 square yards of solar material, you would be able to make one 3x3 square panel (with a total area of 9). That would leave 3 square yards, so you can turn those into three 1x1 square solar panels.
Write a function answer(area) that takes as its input a single unit of measure representing the total area of solar panels you have (between 1 and 1000000 inclusive) and returns a list of the areas of the largest squares you could make out of those panels, starting with the largest squares first. So, following the example above, answer(12) would return [9, 1, 1, 1].
Python
======
Your code will run inside a Python 2.7.6 sandbox.
Standard libraries are supported except for bz2, crypt, fcntl, mmap, pwd, pyexpat, select, signal, termios, thread, time, unicodedata, zipimport, zlib.
Test cases
==========
Inputs:
(int) area = 12
Output:
(int list) [9, 1, 1, 1]
Inputs:
(int) area = 15324
Output:
(int list) [15129, 169, 25, 1]
"""
def answer(area):
# your code here
n = ''
m = ''
area = n**2
result = []
print result
print answer(area) | true |
e77a9e0ab70fbb5916f12e1b864f5f5b7211ba48 | gauravkunwar/PyPractice | /PyExamples/factorials.py | 248 | 4.3125 | 4 | num=int(input("Enter the value :"))
if(num<0):
print("Cannot be factorized:")
elif (num==0):
print("the factorial of 0 is 1:")
else :
for i in range(0 to num+1):
factorial=factorial*i
print"the factorial of a given number is:",factorial
| true |
48d1eeffbf97cdf144e0f8f1fb6305da1141b5be | gauravkunwar/PyPractice | /PyExamples/largestnum.py | 352 | 4.3125 | 4 |
num1=float(input("Enter the first num:"))
num2=float(input("Enter the second num:"))
num3=float(input("Enter the third num:"))
if:
(num1>num2) and(num1>num3)
print("largest=num1")
elif:
(num2>num3) and(num2>num1)
print("largest=num2")
else
print("largest=num3")
#print("The largest number among,"num1","num2",num3","is", largest )
| true |
f1ac7ce434862b7b26f5225810e65f539ec38838 | Nike0601/Python-programs | /km_cm_m.py | 322 | 4.3125 | 4 | print "Enter distance/length in km: "
l_km=float(input())
print "Do you want to convert to cm/m: "
unit=raw_input()
if unit=="cm":
l_cm=(10**5)*l_km
print "Length in cm is: "+str(l_cm)
elif unit=="m":
l_m=(10**3)*l_km
print "Length in m is: "+str(l_m)
else:
print "Invalid input. Enter only cm or m"
| true |
f104a63a96199414da32eeb718326ecea5b4df7e | nithen-ac/Algorithm_Templates | /algorithm/bit_manipulation.py | 980 | 4.15625 | 4 | # Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word.
#
# common bit-wise operation
#
# operations priority:
# {}[]() -> ** -> ~ -> -x -> *,/,% -> +,- -> <<,>> -> & -> ^ -> | -> <>!= -> is -> in -> not x -> and -> or
def bit_wise_operations(a, b):
# not
~a
# or
a | b
# and
a & b
# xor
a ^ b
# shift operators
a << b
a >> b
# subtraction
a & ~b
# set bit, assign to 1
a |= 1 << b
# clear bit, assign to 0
a &= ~(1 << b)
# test bit
if a & 1 << b: pass
# extract last bit
a & -a
# remove last bit
a & (a - 1)
# check is odd or even
if a & 1: print('odd')
# clear right n bit
a & (~0 << b)
# clear left until to n
a & ((1 << b) - 1)
# reference
# https://leetcode.com/problems/sum-of-two-integers/discuss/84278/A-summary%3A-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently
| false |
073e62dd7605358faa87c85820aa8f0ebb19f9af | Julian0912/Book_DSA | /Chapter_8/BaseTree.py | 2,785 | 4.1875 | 4 | # -*- coding:utf8 -*-
# Author: Julian Black
# Function:
#
from abc import ABCMeta, abstractmethod
class Tree(metaclass=ABCMeta):
"""树的基类"""
class Position(metaclass=ABCMeta):
"""一个表示元素位置的基类"""
@abstractmethod
def element(self):
"""返回该位置的元素"""
@abstractmethod
def __eq__(self, other):
pass
def __ne__(self, other):
return not (self == other)
@abstractmethod
def get_root(self):
"""返回根节点,如果为空树则返回None"""
@abstractmethod
def parent(self, p):
"""返回p的父节点,如果p是根节点则返回None"""
@abstractmethod
def num_children(self, p):
"""返回p的子结点总数"""
@abstractmethod
def children(self, p):
"""返回一个p的子结点的迭代"""
@abstractmethod
def __len__(self):
"""返回树的结点数"""
def is_root(self, p) -> bool:
return self.get_root() == p
def is_leaf(self, p) -> bool:
return self.num_children(p) == 0
def is_empty(self) -> bool:
return len(self) == 0
def depth(self, p) -> int:
"""返回结点p的深度"""
if self.is_root(p):
return 0
return 1 + self.depth(self.parent(p))
def __base_height(self, p) -> int:
if self.is_leaf(p):
return 0
return 1 + max(self.__base_height(c) for c in self.children(p))
def height(self, p=None) -> int:
"""返回结点p的高度,默认选择根节点,即树的高度"""
if p is None:
p = self.get_root()
return self.__base_height(p)
def preorder(self, p=None):
"""先序遍历"""
if p is None:
p = self.get_root()
if p is None:
return None
yield p
for c in self.children(p):
for other in self.preorder(c):
yield other
def postorder(self, p=None):
"""后序遍历"""
if p is None:
p = self.get_root()
if p is None:
return None
for c in self.children(p):
for other in self.postorder(c):
yield other
yield p
# def __subtree_preorder(self, p):
# yield p
# for c in self.children(p):
# for other in self.__subtree_preorder(c):
# yield other
#
# def preorder(self):
# if not self.is_empty():
# for p in self.__subtree_preorder(self.get_root()):
# yield p
#
# def positions(self):
# return self.preorder()
#
# def __iter__(self):
# for p in self.positions():
# yield p.element()
| false |
5b1b2cf0dbd3a182ce8605a29c41fd441a951ffe | Bricegnanago/elliptique_courbe | /main.py | 873 | 4.15625 | 4 | # Algorithme
# de x3+ax+b
class Point:
def __init__(self, abs=4, ord=9):
self.abs = abs
self.ord = ord
def setpoint(self, newabs, neword):
self.abs = newabs
self.ord = neword
# print(point.ord)
def elliptiquecourbe(a, b, point):
return point.ord * point.ord - (point.abs ^ 3 + a * point.abs + b)
while 1:
point = Point()
point.abs = int(input("Veuillez saisir les cordonnées d'un point : "))
point.ord = int(input("Veuillez saisir les cordonnées d'un point : "))
print("***maintenant saisir les coefficient***")
a = int(input("a = "))
b = int(input("b = "))
result = elliptiquecourbe(a, b, point)
if result == 0:
print("result " + str(result) + " : ce Point appartient à la courbe")
else:
print("result " + str(result) + " : Ce Point n'appartient à la courbe")
| false |
f31a2f8ae56690da86253aed017a2dfa91a83343 | okdonga/algorithms | /find_matches_both_prefix_and_suffix.py | 2,873 | 4.15625 | 4 | ################
# Given a string of characters, find a series of letters starting from the left of the string that is repeated at the end of the string.
# For example, given a string 'jablebjab', 'jab' is found at the start of the string, and the same set of characters is also found at the end of the string.
# This is one match. Here, we call the first job - prefix, and the latter jab - suffix. Find all cases where a set of characters starting from the left of the string is also found at end of the string. The output should be the length of a series of letters that match this pattern. So, with 'jablebjab', a seris of letters that our pattern are 1, 'jab' 2, 'jablebjab'. So, the output is [3, 9]
# More examples as follows:
# eg1.
# input: alaghggiualagihjkbcala
# matches: 1. a 2. ala 3. alala
# output: [1, 3, 5]
# eg2.
# input: ababcababababcabab
# matches: 1. a 2. abab 3. ababcabab 4. ababcababababcabab
# output: [2, 4, 9, 18]
# PSEUDOCODE
# input : dad's nume + mum's name
# output : length of each combination of letters that can be both prefix and suffix
# find all possible cases of repeated letters that starts with a(original[0]) and ends with last word in the combined string (b)
# eg. ab, abab, ababcab, ababcabab, ababcababab, ... entire string
# compare if the prefix also match the last x digits of the string
# if it is, count the num and push it to to the results array
# CORNER CASE:
# 1. when there is no repeation in the string
def find_words_that_can_be_both_prefix_and_suffix(str):
total_length = len(str)
# If there is no repetition in the string, no need to proceed further
uniq_str = set(str)
if len(uniq_str) == total_length:
return [total_length]
start = str[0]
end = str[total_length-1]
# Find all cases of prefix that start with the first letter of string and end with the last letter of string
prefixes = []
for idx, letter in enumerate(str):
if letter == end:
prefixes.append(str[:idx+1])
# Out of all prefixes, find ones that also count as suffixes
prefixes_and_suffixes = []
for prefix in prefixes:
len_of_prefix = len(prefix)
suffix_start_idx = total_length - len_of_prefix
if str[suffix_start_idx:] == prefix:
prefixes_and_suffixes.append(len_of_prefix)
# prefixes_and_suffixes.append(prefix)
return prefixes_and_suffixes
print find_words_that_can_be_both_prefix_and_suffix('aaaaaa')
# print find_words_that_can_be_both_prefix_and_suffix('jab56jab')
# print find_words_that_can_be_both_prefix_and_suffix('a')
# print find_words_that_can_be_both_prefix_and_suffix('ab')
# print find_words_that_can_be_both_prefix_and_suffix('alala')
# print find_words_that_can_be_both_prefix_and_suffix('abcde')
# print find_words_that_can_be_both_prefix_and_suffix('ababcababababcabab')
| true |
0a9bda6adc975f8526710ef07c49d9d9f2577759 | ne1son172/GB2-algo-and-data-structures | /HW2/task1.py | 1,813 | 4.21875 | 4 | """
Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
Числа и знак операции вводятся пользователем.
После выполнения вычисления программа не должна завершаться, а должна запрашивать новые данные для вычислений.
Завершение программы должно выполняться при вводе символа '0' в качестве знака операции.
Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'),
то программа должна сообщать ему об ошибке и снова запрашивать знак операции.
Также сообщать пользователю о невозможности деления на ноль, если он ввел 0 в качестве делителя.
"""
num1 = 0
num2 = 0
sign = 0
while sign != '0':
num1 = float(input('Insert number 1 >>> '))
num2 = float(input('Insert number 2 >>> '))
sign = input('Insert sign >>> ')
if sign == '+':
summ = num1 + num2
print('Summ = ', summ)
elif sign == '-':
diff = num1 - num2
print('Difference = ', diff)
elif sign == '*':
comp = num1 * num2
print('Composition = ', comp)
elif sign == '/':
if num2 == 0:
print('Error: you can not divide by zero. Please, try again')
else:
quot = num1 / num2
print('Quotient = ', quot)
elif sign == '0':
continue
else:
print('Wrong sign-format! You can use +, -, *, / or 0. Please, try again.')
| false |
6d0745071e38ee8949a6392e51d8f036faef9dcc | arnillacej/calculator | /calculator.py | 397 | 4.34375 | 4 | num1 = float(input("Please enter the first number: "))
operation = input("Please choose an arithmetical operation '+,-,*,/': ")
num2 = float(input("Please enter the second number: "))
if operation == "+":
print(num1+num2)
elif operation == "-":
print(num1-num2)
elif operation == "*":
print(num1*num2)
elif operation == "/":
print(num1/num2)
else:
print("Incorrect character")
| true |
74fd1b9071853159dbed349504f704be01534532 | EricE-Freelancer/Learning-Python | /the power of two.py | 426 | 4.40625 | 4 | print("Hi! what is your name? ")
name = input()
anything = float(input("Hi " + name + ", Enter a number: "))
something = anything ** 2.0
print("nice to meet you " + name +"!")
print(anything, "to the power of 2 is", something)
#the float() function takes one argument (e.g., a string: float(string))and tries to convert it into a float
#because we are inputing a number = float
#input = string or alphabet only
| true |
a902a904c37effe53c9459ac554ca8ee39a90877 | raghuprasadks/pythoncrashcourse | /1-GettingStarted.py | 592 | 4.125 | 4 | print("Hello.Welcome to Python")
course = "Python"
print(course)
print(type(course))
'''
Data Types
1. String - str
2. Integer - int
3. Boolean - bool
4. Float - float
5. List
6. Tuple
7. Dictionary
8. Set
'''
age = 35
print(age)
print(type(age))
amount = 100.5
print(type(amount))
isActive = True
print(type(isActive))
# List
evennumbers = [2,4,6,8,10]
print(evennumbers)
print(type(evennumbers))
#Tuple
days = ("Monday","Tuesday","Wednesday")
print(type(days))
#Dictionary
tele = {"Raghu":9845547471,"Satvik":9845547472}
print(tele)
print(type(tele))
numset = {1,3,5,7}
print(type(numset))
| false |
be5e00cd27adb53a3e3c6f873ffdfc91acf1463f | Nayan356/Python_DataStructures-Functions | /Functions/pgm9.py | 676 | 4.3125 | 4 | # Write a function called showNumbers that takes a parameter called limit.
# It should print all the numbers between 0 and limit with a label to
# identify the even and odd numbers.
def showNumbers(limit):
count_odd = 0
count_even = 0
for x in range(1,limit):
if not x % 2:
count_even+=1
print(x, " is even")
else:
count_odd+=1
print(x," is odd")
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
print("Enter a limit: ")
l=int(input())
showNumbers(l) | true |
b88b8781aff585532384232fae3028ec7ce2d82d | Nayan356/Python_DataStructures-Functions | /DataStructures_2/pgm7.py | 472 | 4.4375 | 4 | # # Write a program in Python to reverse a string and
# # print only the vowel alphabet if exist in the string with their index.
def reverse_string(str1):
return ''.join(reversed(str1))
print()
print(reverse_string("random"))
print(reverse_string("consultadd"))
print()
# def vowel(text):
# vowels = "aeiuoAEIOU"
# print(len([letter for letter in text if letter in vowels]))
# print([letter for letter in text if letter in vowels])
# vowel('consultadd') | true |
c5a78bcae376bba759a179839b6eba037ecd6988 | Nayan356/Python_DataStructures-Functions | /DataStructures/pgm7.py | 232 | 4.375 | 4 | # Write a program to replace the last element in a list with another list.
# Sample data: [[1,3,5,7,9,10],[2,4,6,8]]
# Expected output: [1,3,5,7,9,2,4,6,8]
num1 = [1, 3, 5, 7, 9, 10]
num2 = [2, 4, 6, 8]
num1[-1:] = num2
print(num1)
| true |
84e673227276da95fa1bc8e4cf0801c5c77080a4 | Nayan356/Python_DataStructures-Functions | /Functions/pgm7.py | 519 | 4.4375 | 4 | # Define a function that can accept two strings as input and print the string
# with maximum length in console. If two strings have the same length,
# then the function should print all strings line by line.
def length_of_string(str1, str2):
if (len(str1) == len(str2)):
print(str1)
#print("\n")
print(str2)
elif (len(str1) < len(str2)):
print(str2)
else:
print(str1)
stri1 = input(str("enter First String: "))
stri2 = input(str("enter Second String: "))
print("\n")
length_of_string(stri1, stri2) | true |
12a117ecc823e95e01caa32c3687afc1009e38ea | sidson1/hacktoberfest2021-3 | /bmiCALCULATOR.py | 905 | 4.40625 | 4 | # A simple BMI calculator Using python
print("\n******-----MALNUTRATE!******------HEALTHY!******-------OVERWEIGHT!")
print("\nWELCOME TO FULLY AUTOMATED BMI CALCULATOR ARE YOU INTRESTED TO KNOW WHO YOU ARE\n\t\t\t *press Y* ")
var=input()
print("--------------------------------------------------------------------------------------------------------------------------")
msg=("\nEnter your age below ;) ")
print(msg)
age=input()
print("\nEnter your height in meter squared below :) ")
height=input()
print("\nEnter your weight in kilogram below :) ")
weight=input()
result=(int(weight)/float(height))
print("\nyour BMI =",result)
if result<18.5:
print("\nOh!...no!..(....Eat more....)You are MALNUTRATED!.... ")
elif result>24.9:
print("\nHey!...Buddy..(....Eat less....) You are OVERWEIGHT! ")
else :
print("\nCongratulations!... Bro.. You are HEALTHY! ")
| false |
4f708d85e2be8dba03ad84c944f1192f7fb9c961 | perryl/daftpython | /calc.py | 846 | 4.15625 | 4 | while True:
try:
x = int(raw_input('Enter a value: '))
break
except:
print "Integer values only, please!"
continue
while True:
try:
y = int(raw_input('Enter a second value: '))
break
except:
print "Integer values only, please!"
continue
add = x+y
dif = abs(x-y)
mul = x*y
quo = x/y
rem = x%y
print 'The sum of ',x,' and ',y,' is ',add
print 'The difference between ',x,' and ',y,' is ',dif
print 'The product of ',x,' and ',y,' is ',mul
if rem == 0:
print 'The quotient of ',x,' and ',y,' is ',quo
else:
fquo = float(x)/y
print 'The quotient of ',x,' and ',y,' is ',quo,' with a remainder of ',rem,' , '
print ' or when expressed as a decimal, ',fquo
if add % 2 == 0:
av1 = add/2
print 'Finally, the average of ',x,' and ',y,' is ',av1
else:
av2 = float(add)/2
print 'Finally, the average of ',x,' and ',y,' is ',av2
| true |
c8c98a63020ff5971183ce90bd3d4a43d95f0b95 | karayount/study-hall | /string_compression.py | 1,012 | 4.53125 | 5 | """ Implement a method to perform basic string compression using the counts of
repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.
If the "compressed" string would not become smaller than the original string,
your method should return the original string. You can assume the string has
only uppercase and lowercase letters (a-z).
>>> compress_string("aabcccccaaa")
'a2b1c5a3'
"""
def compress_string(string):
compressed = ""
char = string[0]
count = 1
index = 1
while index < len(string):
if string[index] == char:
count += 1
else:
compressed = compressed + char + str(count)
char = string[index]
count = 1
index += 1
compressed = compressed + char + str(count)
if len(compressed) < len(string):
return compressed
else:
return string
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** all tests passed.\n" | true |
6190823da69071ca54625f541a5e90463c9876b7 | karayount/study-hall | /highest_product.py | 1,388 | 4.34375 | 4 | """Given a list_of_ints, find the highest_product you can get from
three of the integers.
The input list_of_ints will always have at least three integers.
>>> find_highest_product([1, 2, 3, 4, 5])
60
>>> find_highest_product([1, 2, 3, 2, 3, 2, 3, 4])
36
>>> find_highest_product([0, 1, 2])
0
>>> find_highest_product([-8, -1, 2, 0, 1])
16
"""
def find_highest_product_slow(arr):
prod_seen = set()
num_seen = set()
max_prod = None
for num in arr:
if max_prod is None:
max_prod = num
for prod in prod_seen:
possible_max = prod * num
if possible_max > max_prod:
max_prod = possible_max
for seen in num_seen:
prod_seen.add(seen*num)
num_seen.add(num)
return max_prod
def find_highest_product(arr):
highest_seen_prod = None
lowest_seen_prod = None
max_prod = None
for num in arr:
if max_prod is None:
max_prod = num
for prod in prod_seen:
possible_max = prod * num
if possible_max > max_prod:
max_prod = possible_max
for seen in num_seen:
prod_seen.add(seen*num)
num_seen.add(num)
return max_prod
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. WE'RE WELL-MATCHED!\n"
| true |
52cffd996c81e097f71bec337c2dce3d69faecac | Potatology/algo_design_manual | /algorist/data_structure/linked_list.py | 1,947 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Linked list-based container implementation.
Translate from list-demo.c, list.h, item.h. Add iterator implementation.
"""
__author__ = "csong2022"
class Node:
"""List node."""
def __init__(self, item, _next=None):
self.item = item # data item
self.next = _next # point to successor
class List:
def __init__(self):
self.head = None
def is_empty(self) -> bool:
"""Is list empty?"""
return self.head is None
def __contains__(self, x):
"""Check if list contains the value."""
return self.search(x) is not None
def search(self, x) -> Node:
p = self.head
while p is not None and p.item != x:
p = p.next
return p
def insert(self, x) -> None:
"""Insert value."""
self.head = Node(x, self.head)
def delete(self, x) -> None:
"""Delete value iteratively."""
pred = None
p = self.head
while p is not None and p.item != x:
pred = p
p = p.next
if p is not None:
if pred is None:
self.head = p.next
else:
pred.next = p.next
p.next = None
def delete_r(self, x) -> None:
"""Delete value."""
self.head = self._delete_r(self.head, x)
def _delete_r(self, n, x) -> Node:
"""Delete value recursively."""
if n is None:
return None
elif n.item == x:
return n.next
else:
n.next = self._delete_r(n.next, x)
return n
def __iter__(self):
"""Iterate over the linked list in LIFO order."""
current = self.head
while current is not None:
yield current.item
current = current.next
def print(self) -> None:
for x in self:
print(x, end=' '),
print()
| true |
af76bb19fcfa690fa49ea0390ef6ea6e9716f133 | Potatology/algo_design_manual | /algorist/data_structure/linked_queue.py | 1,773 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Implementation of a FIFO queue abstract data type.
Translate from queue.h, queue.c. Implement with singly linked list. Add iterator implementation.
"""
__author__ = "csong2022"
class Node:
"""Queue node."""
def __init__(self, item, _next=None):
self.item = item # data item
self.next = _next # point to successor
class Queue:
def __init__(self):
self.count = 0 # number of queue elements
self.first = None # first element
self.last = None # last element
def enqueue(self, x) -> None:
"""Enqueue"""
old_last = self.last
self.last = Node(x)
if self.is_empty():
self.first = self.last
else:
old_last.next = self.last
self.count += 1
def dequeue(self):
"""Dequeue"""
if self.is_empty():
raise IndexError('Queue underflow')
else:
x = self.first.item
self.first = self.first.next
self.count -= 1
if self.is_empty():
self.last = None
return x
def headq(self):
"""Head of the queue."""
if self.is_empty():
raise IndexError('Queue empty')
else:
return self.first.item
def is_empty(self) -> bool:
"""Is queue empty?"""
return self.count == 0
def __iter__(self):
"""Iterate through the queue in FIFO sequence."""
current = self.first
while current is not None:
yield current.item
current = current.next
def print(self) -> None:
for x in self:
print(x, end=' ')
print()
def size(self):
return self.count
| true |
fd96bd483b82593170856bc0d62ccab97ad33036 | abriggs914/CS2043 | /Lab2/palindrome.py | 466 | 4.125 | 4 | def palcheck(line, revline):
half = (len(line) / 2)
x = 0
while(half > x):
if(line[x] == revline[x]):
x += 1
else:
return False
return True
class palindrome :
line = raw_input("Please enter a string:")
print(line)
print(line[::-1])
revline = (line[::-1])
if(palcheck(line, revline)):
print "line", line, "is a palindrome"
else:
print "line", line, "is not a palindrome" | true |
85d156b95da272ad1d9cdb86cde272cd842e0fa0 | imclab/introduction-to-algorithms | /2-1-insertion-sort/insertion_sort.py | 728 | 4.34375 | 4 | #!/usr/bin/env python
#
# insertion sort implementation in python
#
import unittest
def insertion_sort(input):
"""
function which performs insertion sort
Input:
input -> array of integer keys
Returns: the sorted array
"""
for j in xrange(len(input)):
key = input[j]
i = j - 1 # second index cursor
while i >= 0 and input[i] > key:
input[i + 1] = input[i]
i -= 1
input[i + 1] = key
return input
class TestInsertionSort(unittest.TestCase):
def test_insertion_sort(self):
res = insertion_sort([3,5,6,1,2,4])
self.assertEqual(res, [1,2,3,4,5,6])
if __name__ == '__main__':
unittest.main()
| true |
51932bdfca69073d247dba1ebc7fa1d6de942a48 | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 02/capitulo 02/capitulo 02/exercicio-02-02.py | 1,576 | 4.21875 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 02\exercicio-02-02.py
##############################################################################
# O resultado da expressão:
# 10 % 3 * 10 ** 2 + 1 - 10 * 4 / 2
# é 81.0
#
# Realizando o cálculo com as prioridades da página 39,
# efetuando apenas uma operação por linha,
# temos a seguinte ordem de cálculo:
# 0 --> 10 % 3 * 10 ** 2 + 1 - 10 * 4 / 2
# 1 --> 10 % 3 * 100 + 1 - 10 * 4 / 2
# 2 --> 1 * 100 + 1 - 10 * 4 / 2
# 3 --> 100 + 1 - 10 * 4 / 2
# 4 --> 100 + 1 - 40 / 2
# 5 --> 100 + 1 - 20
# 6 --> 101 - 20
# 7 --> 81
#
# Se você estiver curioso(a) para saber por que o resultado
# é 81.0 e não 81, leia a seção 3.2, página 45.
# A operação de divisão sempre resulta em um número de ponto flutuante.
| false |
f58629ab3b18436da63c83b0a14bd1427aaba1a9 | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 04/04.04 - Programa 4.3 Calculo do Imposto de Renda.py | 995 | 4.4375 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem3\capítulo 04\04.04 - Programa 4.3 – Cálculo do Imposto de Renda.py
# Descrição: Programa 4.3 – Cálculo do Imposto de Renda
##############################################################################
# Programa 4.3 – Cálculo do Imposto de Renda
salário = float(input("Digite o salário para cálculo do imposto: "))
base = salário
imposto = 0
if base > 3000:
imposto = imposto + ((base - 3000) * 0.35)
base = 3000
if base > 1000:
imposto = imposto + ((base - 1000) * 0.20)
print(f"Salário: R${salário:6.2f} Imposto a pagar: R${imposto:6.2f}")
| false |
effd68bbed996738bcdf997fe5a8297adf24edef | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 05/capitulo 05/capitulo 05/exercicio-05-25.py | 1,330 | 4.1875 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 05\exercicio-05-25.py
##############################################################################
# Atenção: na primeira edição do livro, a fórmula foi publicada errada.
# A fórmula correta é p = ( b + ( n / b ) ) / 2
# A função abs foi utilizada para calcular o valor absoluto de um número,
# ou seja, seu valor sem sinal.
# Exemplos: abs(1) retorna 1 e abs(-1) retorna 1
n=float(input("Digite um número para encontrar a sua raiz quadrada: "))
b=2
while abs(n-(b*b))>0.00001:
p=(b+(n/b))/2
b=p
print ("A raiz quadrada de %d é aproximadamente %8.4f" % (n, p))
| false |
b467d3cd5637fd886eae302be0fd728110e006a5 | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 04/04.05 - Programa 4.4 - Carro novo ou velho, dependendo da idade com else.py | 874 | 4.4375 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem3\capítulo 04\04.05 - Programa 4.4 - Carro novo ou velho, dependendo da idade com else.py
# Descrição: Programa 4.4 - Carro novo ou velho, dependendo da idade com else
##############################################################################
# Programa 4.4 - Carro novo ou velho, dependendo da idade com else
idade = int(input("Digite a idade de seu carro: "))
if idade <= 3:
print("Seu carro é novo")
else:
print("Seu carro é velho")
| false |
49d9a01af9e9b47089bc0923ce444d07d5a558b5 | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 02/02.21 - Programa 2.2 Calculo de aumento de salario.py | 763 | 4.3125 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem3\capítulo 02\02.21 - Programa 2.2 – Cálculo de aumento de salário.py
# Descrição: Programa 2.2 – Cálculo de aumento de salário
##############################################################################
# Programa 2.2 – Cálculo de aumento de salário
salário = 1500
aumento = 5
print(salário + (salário * aumento / 100))
| false |
f350339f0416e4933dc04243e192d2fa2a994bea | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 08/08.35 - Programa 8.15 Funcao imprime_maior com numero indeterminado de parametros.py | 1,028 | 4.15625 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem3\capítulo 08\08.35 - Programa 8.15 – Função imprime_maior com número indeterminado de parâmetros.py
# Descrição: Programa 8.15 – Função imprime_maior com número indeterminado de parâmetros
##############################################################################
# Programa 8.15 – Função imprime_maior com número indeterminado de parâmetros
def imprime_maior(mensagem, *numeros):
maior = None
for e in numeros:
if maior is None or maior < e:
maior = e
print(mensagem, maior)
imprime_maior("Maior:", 5, 4, 3, 1)
imprime_maior("Max:", *[1, 7, 9])
| false |
463ba46cad291a2eae8fb8ffe0b9ddb1491d71c2 | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 08/08.41.py | 828 | 4.1875 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2019
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3
# Site: http://python.nilo.pro.br/
#
# Arquivo: listagem3\capítulo 08\08.41.py
# Descrição:
##############################################################################
Digite o índice que quer imprimir:abc
Algo de errado aconteceu: invalid literal for int() with base 10: 'abc'
Digite o índice que quer imprimir:-100
Algo de errado aconteceu: list index out of range
Digite o índice que quer imprimir:100
Algo de errado aconteceu: list index out of range
| false |
5e53080b0af272b0d9f0aa69e542bbaaa9af09f5 | Azeem-Q/Py4e | /ex84.py | 711 | 4.28125 | 4 | """
8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.
"""
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
x = line.split()
for i in x:
lst.append(i)
orglst = list()
for i in lst:
if i in orglst:
continue
else:
orglst.append(i)
orglst.sort()
print(orglst)
#print(len(lst))
#print(line.rstrip())
#print(range(4))
| true |
4877cfe0219914090f0eb38fec32a4cdafb780ec | mehnazchyadila/Python_Practice | /program45.py | 512 | 4.15625 | 4 | """
Exception Handling
"""
try:
num1 = int(input("Enter Any Integer number : "))
num2 = int(input("Enter any integer number : "))
result = num1 / num2
print(result)
except (ValueError,ZeroDivisionError,IndexError):
print("You have to insert any integer number ")
finally:
print("Thanks")
def voter(age):
if age < 18:
raise ValueError("Invalid Voter")
return "You are allowed to vote "
print(voter(19))
try:
print(voter(17))
except ValueError as e:
print(e)
| true |
87c7fa65332cd453521fbc957b430fd2878e2eb8 | antoniougit/aByteOfPython | /str_format.py | 916 | 4.34375 | 4 | age = 20
name = 'Swaroop'
# numbers (indexes) for variables inside {} are optional
print '{} was {} years old when he wrote this book'.format(name, age)
print 'Why is {} playing with that python?'.format(name)
# decimal (.) precision of 3 for float '0.333'
print '{0:.3f}'.format(1.0/3)
# fill with underscores (_) with the text centered
# (^) to 11 width '___hello___'
print '{0:_^11}'.format('hello')
# keyword-based 'Swaroop wrote A Byte of Python'
print '{name} wrote {book}'.format(name='Swaroop',
book='A Byte of Python')
# comma to prevent newline (\n) after print
print "a",
print "b"
print '''This is a triple-quoted
string print in Python'''
print 'This is the first line\nThis is the second line'
print 'This is the first line\tThis is the second line after a tab'
print "This is the first sentence. \
This is the second sentence."
# raw strings, prefix r or R
print r"Newlines are indicated by \n" | true |
f0816e433a5c7e300f913c571a6fa1145a272706 | kangyul/Python | /list.py | 1,182 | 4.5625 | 5 | # List - use "[]""
subway = ["Terry", "Sebastian", "Dylan"]
print(subway) # ['John', 'Tim', 'Dylan']
# .index finds an index of an element
print(subway.index("Dylan")) # 0
# .append inserts a new element at the end of the list
subway.append("Justin")
print(subway) # ['John', 'Tim', 'Dylan', 'Justin']
# inserting a new element "Ian" in subway[1]
subway.insert(1, "Ian")
print(subway) # ['Terry', 'Ian', 'Sebastian', 'Dylan', 'Justin']
# deleting an element from the back
subway.pop()
print(subway) # ['Terry', 'Ian', 'Sebastian', 'Dylan']
# check same element
subway.append("Dylan")
print(subway) # ['Terry', 'Ian', 'Sebastian', 'Dylan', 'Dylan']
print(subway.count("Dylan")) # 2
# sorting a list
num_list = [5, 3, 2, 4, 1]
num_list.sort()
print(num_list) # [1, 2, 3, 4, 5]
# reversing an order of a list
num_list.reverse()
print(num_list) # [5, 4, 3, 2, 1]
# clearing every element in a list
num_list.clear()
print(num_list) # []
# list can be used with different data types
num_list = [5, 2, 4, 3, 1]
mix_list = ["Shri", 20, False]
print(mix_list) # ['Shri', 20, False]
# extending a list
num_list.extend(mix_list)
print(num_list) # [5, 2, 4, 3, 1, 'Shri', 20, False] | false |
bd2d7b5e14cfcd1afdee8400f7eeadfa24cb13a7 | MarkHXB/Python | /Day_02/project.py | 688 | 4.28125 | 4 | """
Tip calculator
"""
bill = float(input("What was the total bill? $"))
tip = int(input("What percentage tip would you like to give? 10, 12 or 15 "))
people = int(input("How many people to split the bill? "))
#my own derivation
bill_people = bill/people
tip_per_person = bill_people * (tip/100)
total_amount_of_tip_per_person = bill_people + tip_per_person
print(f"Each person should pay: ${float(round(total_amount_of_tip_per_person,2))}")
#Or
"""
tip_as_percent = tip / 100
total_tip_amount = bill * tip_as_percent
total_bill = bill + total_tip_amount
bill_per_person = total_bill / people
final_amount = round(bill_per_person,2)
print(f"Each person should pay: ${final_amount}")
""" | false |
56a8b63c88b9eb29967cdbbf520db18e443f4ce9 | borko81/Algorithms-Data-Structures-Python | /arrays/reverse_array_in_list.py | 346 | 4.1875 | 4 | def reversed_array(nums):
start_index = 0
end_index = len(nums) - 1
while end_index > start_index:
nums[start_index], nums[end_index] = nums[end_index], nums[start_index]
start_index += 1
end_index -= 1
return nums
if __name__ == '__main__':
n = [1, 2, 3, 4, 5, 6, 7, 8]
print(reversed_array(n))
| false |
2dfb298dcdf0fe21871ae65949518515a088d7dd | kubos777/cursoSemestralPython | /CodigosClase/Objetos/Abstraccion-Clases-objetos-MetodosY-funcionesdeClase/Persona3.py | 1,494 | 4.125 | 4 | #*-* coding:utf-8*.*
class Persona3:
#Definimos el constructor
def __init__(self,nombre1,apellido1,edad1,estatura1,dinero):
self.nombre=nombre1
self.apellido=apellido1
self.edad=edad1
self.estatura=estatura1
self.dinero=dinero
print("Hola soy ",self.nombre," ",self.apellido,",tengo",self.edad,"años y mido ",self.estatura)
print("Tengo $ ",self.dinero,"en mi cuenta")
#Termina el constructor
#Definimos métodos de la clase
def comer(self,comida):
print("Hola soy ",self.nombre,"y estoy comiendo: ",comida)
def informarSaldo(self):
print("Soy ",self.nombre,"y actualmente tengo $ ",self.dinero," pesitos en mi cuenta.")
def prestarDinero(self,monto,destinatario):
self.informarSaldo()
destinatario.informarSaldo()
self.dinero=self.dinero-monto
destinatario.dinero=destinatario.dinero+monto
self.informarSaldo()
destinatario.informarSaldo()
#Función de la clase
def regalarDinero(donacion,donador,destinatario):
donador.informarSaldo()
destinatario.informarSaldo()
donador.dinero=donador.dinero-donacion
destinatario.dinero=destinatario.dinero+donacion
donador.informarSaldo()
destinatario.informarSaldo()
ricardo=Persona3("Ricardo","Singer",20,1.80,1000)
jorge=Persona3("Jorge","Chávez",21,1.70,5)
print(ricardo.edad)
print(jorge.dinero)
jorge.informarSaldo()
jorge.comer(", nada porque no tengo dinero")
ricardo.prestarDinero(500,jorge)
print("------------------------------------")
Persona3.regalarDinero(200,ricardo,jorge)
| false |
28d19efe095993d7b436dddf318ce5f6dd7d2c04 | kubos777/cursoSemestralPython | /CodigosClase/TiposDeDatos/conjuntos.py | 698 | 4.125 | 4 | ###########
# Conjuntos
###########
conjunto={1,2,2,3,4,5}
print("Tipo de dato: ",type(conjunto))
print(conjunto)
conjunto2=set([1,"A","B",2,1])
print(conjunto2)
print("Tipo de dato: ",type(cadena))
print("Indexacion: ",cadena[0])
print("Indexacion negativa: ",cadena[-1])
print("Tamaño: ",len(cadena))
print("Concatenación: ",cadena+cadena2)
print("Repetición: ",cadena*4)
#Operaciones con conjuntos
print("Diferencia: ",conjunto-conjunto2)
print("Diferencia simetrica: ",conjunto^conjunto2)
print("Union: ",conjunto|conjunto2)
print("Interseccion: ",conjunto&conjunto2)
print("And: ",conjunto and conjunto2)
print("Or: ",conjunto or conjunto2)
conjunto=list(conjunto)
print(conjunto[0]) | false |
8f590bec22c64d0c9d89bfcc765f042883955a02 | tprhat/codewarspy | /valid_parentheses.py | 807 | 4.34375 | 4 | # Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The
# function should return true if the string is valid, and false if it's invalid.
# Constraints
# 0 <= input.length <= 100
#
# Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore,
# the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as
# parentheses (e.g. [], {}, <>).
def valid_parentheses(string):
stack = []
for x in string:
try:
if x == '(':
stack.append(x)
elif x == ')':
stack.pop()
except IndexError:
return False
if len(stack) == 0:
return True
return False
| true |
657dd462815393c877709d5dcdef2485ec6d8763 | lidorelias3/Lidor_Elias_Answers | /python - Advenced/Pirates of the Biss/PiratesOfTheBiss.py | 678 | 4.3125 | 4 | import re
def dejumble(scramble_word, list_of_correct_words):
"""
Function take scramble word and a list of a words and
check what word in the list the scramble word can be
:param scramble_word: word in pirate language
:param list_of_correct_words: a list of words in our language
:return: the words that the scramble word can make
"""
valid_words = []
# for each word
for current_word in list_of_correct_words:
if sorted(current_word) == sorted(scramble_word):
valid_words.append(current_word)
return valid_words
if __name__ == '__main__':
print(dejumble("ortsp", ['sport', 'parrot', 'ports', 'matey']))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.