blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5a1da23b4558b4da778ae275f4fb8247735ff4f6 | Grey-EightyPercent/Python-Learning | /ex18.py | 778 | 4.40625 | 4 | # Names, Variables, Code, Funcstions!!! 函数!!
# this one is like your scripts with argv
def print_two(*args): # use def to give the function name
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
# ok, that *args is actually pointless, we can just do This
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
# this just takes one argument
def print_one(arg1):
print(f"arg1: {arg1}")
def print_none():
print("I got nothing'.")
# There are no displays above because all of the 'print' command are in the function! only when you give values to the function it can be actived
# Run functions respectively!!!!!
print_two("zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
| true |
904a6832d6427b1c93eed2231c7eb335d40b750c | apulijala/python-crash-course | /ch3-4/locations.py | 1,007 | 4.28125 | 4 |
def places_to_visit():
locations = ["Varanasi", "Kedarnath", "Badrinath", "Dwaraka", "Ukraine"]
print(f"Places to visit")
print(locations)
def places_to_visit_using_sorted():
locations = ["Varanasi", "Kedarnath", "Badrinath", "Dwaraka", "Ukraine"]
print("\nSorted Locations")
print(sorted(locations))
print("\n Original List")
print(locations)
def places_to_visit_reversed():
locations = ["Varanasi", "Kedarnath", "Badrinath", "Dwaraka", "Ukraine"]
print("\n places to visit")
print("Original List")
print(locations)
print("Reversed Locations")
locations.reverse()
print(locations)
print("Reversed again List")
locations.reverse()
print(locations)
def places_to_visit_using_sort():
locations = ["Varanasi", "Kedarnath", "Badrinath", "Dwaraka", "Ukraine"]
print("\nSorted Locations using sort")
locations.sort()
print(locations)
print("\n Rerversed List")
locations.sort(reverse=True)
print(locations)
| false |
f40a4c7f84d966786da49f21e22eb1dcc349327b | apulijala/python-crash-course | /ch3-4/pizza.py | 1,790 | 4.28125 | 4 |
def pizzas():
pizzas = ("Pepperoni", "Cheese", "Tomato")
print("\n")
for pizza in pizzas:
print(f"I like {pizza}")
print("I really love Pizza!")
def pets():
pets = ("Dog", "Horse", "Cat")
print("\n")
for pet in pets:
print(f"A {pet} would make a great Pet")
print("Any of these animals would make a great pet!")
def counting_to_twenty():
for number in range(1,21):
print(number)
def million_nums():
million = list(range(1,1000001))
print("Sum of million numbers is ", sum(million))
print("Minimum of million numbers is ", min(million))
print("Maximum of million nummbers is", max(million))
def threes():
list_of_threes = [value*3 for value in range(1,11)]
print("\nList of threes are")
for num in list_of_threes:
print(num)
def cubes_using_for_loop():
nums_1_to_10 = list(range(1, 11))
print("\n Cubes Using for loop")
for num in nums_1_to_10:
print(num**3)
def cubes_using_for_comprehension():
print("\n Cubes Using for comprehension")
cubes_1_to_10 = [value**3 for value in list(range(1, 11))]
for num in cubes_1_to_10:
print(num)
print("\n First three items")
print(cubes_1_to_10[0:3])
print("\n Middle three items")
print(cubes_1_to_10[3:6])
print("\n Last three items")
print(cubes_1_to_10[7:])
def pizzas_deep_copy():
pizzas = ["Pepperoni", "Cheese", "Tomato"]
friend_pizzas = pizzas[:]
friend_pizzas.append("Green Chillies")
pizzas.append("Marmelade")
print("\n Original Pizzas are")
for orig_pizza in pizzas:
print(f"Original pizza is {orig_pizza}")
print("\n Friend Pizzas are")
for friend_pizza in friend_pizzas:
print(f"Friend pizza is {friend_pizza}")
| true |
a7eb80d09873836fa28a834b76ede6d4696b8a81 | apulijala/python-crash-course | /ch3-4/guest_list.py | 2,058 | 4.15625 | 4 |
def guest_list():
guests = ["Krishna", "Rama", "Govinda", "Datta"]
print("\n")
for guest in guests:
print(f"Jaya Guru Datta {guest}, Please come to my Dinner")
"""
Create a guest list minus one.
Removing Govinda.
"""
def guest_list_minus_one():
guests = ["Krishna", "Rama", "Govinda", "Datta"]
guest_not_comming = guests.pop(2)
print("\n")
print("Guest List minus one")
print(f"{guest_not_comming} has dropped out ")
guests.insert(2, "Hari")
for guest in guests:
print(f"Jaya Guru Datta {guest}, Please come to my Dinner")
def add_new_guests():
guests = ["Krishna", "Rama", "Govinda", "Datta"]
guest_not_comming = guests.pop(2)
print("\n")
print("Adding New Guests")
print(f"{guest_not_comming} has dropped out ")
guests.insert(2, "Hari")
guests.insert(0, "Lalitha")
guests.insert(3, "Hanuman")
guests.append("Lakshmi")
for guest in guests:
print(f"Jaya Guru Datta {guest}, Please come to my Dinner")
def remove_all_except_two():
guests = ["Krishna", "Rama", "Govinda", "Datta"]
guest_not_comming = guests.pop(2)
print("\n")
print("Remove all except two")
print(f"{guest_not_comming} has dropped out ")
guests.insert(2, "Hari")
guests.insert(0, "Lalitha")
guests.insert(3, "Hanuman")
guests.append("Lakshmi")
print("Can invite only two people for Dinner")
guest_removed = guests.pop()
print(f"{guest_removed}, I cannot invite you, Sorry")
guest_removed = guests.pop()
print(f"{guest_removed}, I cannot invite you, Sorry")
guest_removed = guests.pop()
print(f"{guest_removed}, I cannot invite you, Sorry")
guest_removed = guests.pop()
print(f"{guest_removed}, I cannot invite you, Sorry")
guest_removed = guests.pop()
print(f"{guest_removed}, I cannot invite you, Sorry")
print("\n")
for guest in guests:
print(f"{guest}, You are still Invited")
del guests[1]
del guests[0]
print("Guests now are", guests)
| false |
a25342fe26e0766e5003e6839b661789fa916a53 | SaentRayn/Data-Structures-By-Python | /Python Files/Set-Prob.py | 835 | 4.375 | 4 | def intersection(set1, set2):
differentValues = set()
# Add Code to only add values that are not in both sets to the differentValues
# Hint: One need only cycle a value and check if it is in the other set
return(differentValues)
def union(set1, set2):
unionOfSets = set()
# Add code to add both the values from set1 and set2 to the unionOfSets
return(unionOfSets)
#############################################################################
# Problems to solve
#############################################################################
s1 = {1,3,5}
s2 = {1,2,3,4,5}
print(intersection(s1,s2)) # Should show {1, 3, 5}
print(union(s1,s2)) # Should show {1, 2, 3, 4, 5}
s1 = {1,2,3,100}
s2 = {6,7,8,100}
print(intersection(s1,s2)) # Should show {100}
print(union(s1,s2)) # Should show {1, 2, 3, 100, 6, 7, 8} | true |
50871b83a9b35cd72104f1684a6e6c30b9bd0aa5 | jb240707/Google_IT_Automation_Python | /Interacting with OS/test_script.py | 2,719 | 4.5 | 4 | """
The create_python_script function creates a new python script in the current working directory, adds the line of comments to it declared by the 'comments' variable, and returns the size of the new file. Fill in the gaps to create a script called "program.py".
"""
import datetime
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, "w") as file:
file.write(comments)
filesize = len(comments)
return(filesize)
print(create_python_script("program.py"))
"""
The new_directory function creates a new directory inside the current working directory, then creates a new empty file inside the new directory, and returns the list of files in that directory. Fill in the gaps to create a file "script.py" in the directory "PythonPrograms".
"""
def new_directory(directory, filename):
if not os.path.exists(directory):
os.mkdir(directory)
os.chdir(directory)
with open(filename, 'w') as f:
pass
return(os.listdir())
print(new_directory("PythonPrograms", "script.py"))
"""
The file_date function creates a new file in the current working directory, checks the date that the file was modified, and returns just the date portion of the timestamp in the format of yyyy-mm-dd. Fill in the gaps to create a file called "newfile.txt" and check the date that it was modified.
"""
def file_date(filename):
# Create the file in the current directory
with open(filename, "w") as file:
pass
timestamp = os.path.getmtime(filename)
# Convert the timestamp into a readable format, then into a string
new_date = datetime.datetime.fromtimestamp(timestamp)
# Return just the date portion
# Hint: how many characters are in “yyyy-mm-dd”?
return ("{}".format(new_date.date()))
print(file_date("newfile.txt"))
# Should be today's date in the format of yyyy-mm-dd
"""
The parent_directory function returns the name of the directory that's located just above the current working directory. Remember that '..' is a relative path alias that means "go up to the parent directory". Fill in the gaps to complete this function.
"""
def file_date(filename):
# Create the file in the current directory
with open(filename, 'w') as file:
pass
timestamp = os.path.getmtime(filename)
# Convert the timestamp into a readable format, then into a string
curr_time = datetime.datetime.fromtimestamp(timestamp)
# Return just the date portion
# Hint: how many characters are in “yyyy-mm-dd”?
return ("{}".format(curr_time.strftime("%Y-%m-%d")))
print(file_date("newfile.txt"))
# Shojuld be today's date in the format of yyyy-mm-ddcddd
| true |
fa3f9e982b12fc3726adeebf47e40a9d4a475c18 | Sannj/learn-python-in-a-day | /bmiCalc.py | 796 | 4.21875 | 4 | def calBMI(h, w):
bmi = int(w)/(int(h)/100)**2
print('Your BMI is: {}'.format(round(bmi, 2)))
bmi = round(bmi, 2)
if bmi > 25:
print('You have this sweetheart! You can get rid of those extra pounds!')
elif bmi < 18.5:
print('Omg. You need Nutella like right now! You need more pounds.')
else:
print('Keep maintaining this!')
print('Hello! Welcome to the best BMI calculator in this world :P\nNow you will be prompted to enter a few values and then your BMI will be displayed! \nWohoo!')
height = input('Now, enter your height in centimeters ')
weight = input('Awesome! Now enter your weight in kilograms please. ')
print('The computer is calculating your BMI. Hold on tight!\n')
for x in range(5):
for y in range(x+1):
print('.', end='')
print('\n')
calBMI(height, weight)
| true |
68b6d97adc41e0aa374fc1235e342605aa8c9ae6 | llakhi/python_program | /Practise_1.py | 1,408 | 4.15625 | 4 | # split a string and display separately
filename = input("Type file name")
print ("Filename : ",filename)
print ("Split the file name and show ")
data = filename.split('.')
print("file name - " ,data[0])
print("file name - " ,data[1])
# Write a program and display all the duplicates of list
alist = [10,20,30,10,40,50]
print (list(set(alist)))
aname = "python is general purpose interpreted cross platform programming lang"
print (aname)
print("Diplay in upper case:-",(aname.upper()))
print("Display count of p in string:- ",aname.count("p"))
print ("Replace with Ruby :- ",(aname.replace("python","ruby")))
print ("Count no of words and display :- ",aname.count(""))
# IF statement
a = 10
b=12
if a < b :
print (" A is smaller ")
else:
print("B is greater")
print(list(range(1,10))) # range only works with list or tuple
print(list(range(1,10,2))) #display even numbers
print (list(range(10,0,-1))) # display in reverse order
# FOR LOOP
alist = [10,20,30,40,50]
for val in alist:
print(val)
# with range
for val in range (1,5):
print (val)
#display all the keys
adict = {"chap1":10,"chap2":20,"chap3": 30 }
for item in adict.keys():
print("key :",item)
print ("value :",adict[item])
# forloop with string
name = "pythono programming"
for char in name :
print(char)
aset = {10,10,10}
for val in aset:
print(val)
| true |
bf5d24a9e92a2afe969b118890bce75e2f57d9cc | clive-bunting/computer-science | /Problem Set 2/probset2_1.py | 745 | 4.25 | 4 | balance = 4842 # the outstanding balance on the credit card
annualInterestRate = 0.2 # annual interest rate as a decimal
monthlyPaymentRate = 0.04 # minimum monthly payment rate as a decimal
monthlyInterestRate = annualInterestRate / 12.0
totalPaid = 0.0
for month in range(1,13):
minimumMonthlyPayment = monthlyPaymentRate * balance
totalPaid += minimumMonthlyPayment
balance -= minimumMonthlyPayment
balance += (monthlyInterestRate * balance)
print 'Month:',
print month
print 'Minimum monthly payment:',
print round(minimumMonthlyPayment , 2)
print 'Remaining balance:',
print round(balance, 2)
print 'Total paid:',
print round(totalPaid, 2)
print 'Remaining balance:',
print round(balance, 2) | true |
0311b7f276f93289f83999eb43227c13283433f7 | VovaRen/Tasks | /Tasks_2/Except.py | 1,222 | 4.15625 | 4 | # Функция принимает числа введённые пользователем
# через пробел.
# Необходимо вернуть их сумму, если
# все элементы являются чилами и их
# кол-во меньше 11.
# Если какое-то из условий не соблюдается
# вызвать исключение.
def sum_nums():
"""Функция складывает не более 10 целых
чисел (чисел с плавающей точкой), введенных пользователем.
:return sum_nums: float
"""
input_nums = input("Введите несколько чисел через пробел (не больше 10): ")
try:
list_input_nums = [float(i) for i in input_nums.split(' ')]
if len(list_input_nums) < 11:
print("Сумма введённых чисел: ", sum(list_input_nums))
else:
raise ValueError
except ValueError:
print('Введите только числа через пробел в кол-ве не больше 10!')
sum_nums()
if __name__ == '__main__':
sum_nums()
| false |
d46d1b419391f408934e1f1a94092d18f9c50d61 | Irbah28/Python-Examples | /recursion_examples.py | 1,365 | 4.3125 | 4 | '''A few simple examples of recursion.'''
def sum1(xs):
'''We can recursively sum a list of numbers.'''
if len(xs) == 0:
return 0
else:
return xs[0] + sum1(xs[1:])
def sum2(xs):
'''Or do the same thing iteratively.'''
y = 0
for x in xs:
y += x
return y
def product1(xs):
'''Similarly we can recursively take the product of a list of numbers.'''
if len(xs) == 0:
return 1
else:
return xs[0] + sum1(xs[1:])
def concat1(xs):
'''Concatenate a list of strings.'''
if len(xs) == 0:
return ''
else:
return xs[0] + concat1(xs[1:])
def reverse1(xs):
'''Or reverse a list.'''
if len(xs) == 0:
return xs
else:
return reverse(xs[1:]) + [xs[0]]
# At this point we realise all of these examples are practically
# identical (i.e. the recursion structure is the same), we can
# abstract them into two recursive functions.
def foldl(xs, op, id):
'''Folds a list xs from the left with binary operation op,
and identity id.'''
if len(xs) == 0:
return id
else:
return op(foldl(xs[1:], op, id), xs[0])
def foldr(xs, op, id):
'''Folds a list xs from the right with binary operation op,
and identity id.'''
if len(xs) == 0:
return id
else:
return op(xs[0], foldr(xs[1:], op, id))
| true |
37a83e497842185ec4fa9c8126d959f1d38164b6 | msmiel/mnemosyne | /books/Machine Learning/Machine Learning supp/code/chapter2/Divisors3.py | 240 | 4.125 | 4 | def divisors(num):
count = 1
div = 2
while(div < num):
if(num % div == 0):
count = count + 1
div = div + 1
return count
result = divisors(12)
if(result == 1):
print('12 is prime')
else:
print('12 is not prime')
| true |
22c635a85256152016cf90c55d2a68fb33335f24 | s-andromeda/Two-Pointers-2 | /Problem2.py | 1,120 | 4.15625 | 4 | from typing import List
"""
Student : Shahreen Shahjahan Psyche
Time Complexity : O(N)
Space Complexity : O(1)
"""
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
i = m - 1
j = n - 1
k = m + n - 1
# started at the end of the nums1's values which is m and nums2's
# values which is n. Now if nums1 current value is greater than nums2
# current value, then swapping the current nums1 value to the last. else
# otherwise
while(i>=0 and j>=0):
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
k -= 1
# If all the nums1 values are shifted to the last and i is out of bound,
# just transfering the values from nums2 at the beginning of the nums1
while(j>=0):
nums1[k] = nums2[j]
j -= 1
k -= 1 | true |
0a7879e26edb46c5b55cdb9322997c8ffea49274 | rohitharyani/LearningPython | /functionAndMethodsHw.py | 1,927 | 4.28125 | 4 | import math
def volume(radius):
'''
Calculate volume of a sphere based on the formula
'''
return (4.0*math.pi*(radius**3))/3
print("Volume of sphere is: ",volume(3))
#-----------------------------------
def valueInRange(num,low,high):
'''
Check for a given value in a defined range
'''
return "Value in range" if num in range(low,high+1) else "Value not in range"
print(valueInRange(3,1,10))
#------------------------------------
def up_low(sentence):
'''
Count the number of upper and lower case characters in a given string
'''
d={"upper":0, "lower":0}
for c in sentence:
if c.isupper():
d["upper"]+=1
elif c.islower():
d["lower"]+=1
else:
pass
print("Upper: ",d["upper"])
print("Lower : ",d["lower"])
sentence = "Hello, my name is Rohit Haryani"
print(sentence)
up_low(sentence)
#------------------------------------
def unique(list):
'''
Display the unique values in a list
'''
answer = set()
for i in list:
answer.add(i)
return answer
sample = [1,1,1,2,3,3,6,6,6,5,5,5,8,8,8,9]
print("Unique elements of the list are: ",list(unique(sample)))
#-------------------------------------------
def multiply(list):
'''
Calculate the multiplication of the elements of a list
'''
answer = 1
for i in list:
answer*=i
return answer
sample1 = [1,2,3,-4]
print("Multiplication of list is: ", multiply(sample1))
#-------------------------------------------
def palindrome(sentence):
'''
Check if a string is a palindrome
'''
return "Palindrome" if sentence == sentence[::-1] else "Not a palindrome"
sentence = "helleh"
print(palindrome(sentence))
#--------------------------------
import string
def isPangram(sentence, alphabet=string.ascii_lowercase):
'''
Check if string is a panagram
'''
alphaset = set(alphabet)
return "Is Pangram" if alphaset <= set(sentence.lower()) else "Not a Pangram"
sentence = "abcdefghijklmnopqrstuvwxxyz"
print(isPangram(sentence)) | true |
9d21e3afdbd6b659169c55463e7415572fd96cfe | rohitharyani/LearningPython | /InheritanceAndPolymorphism.py | 1,326 | 4.28125 | 4 | #Inheritance
class Animal():
def __init__(self):
print("Animal Created")
def who_am_i(self):
print("I am an Animal")
def eat(self):
print("I am eating")
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog Created")
def who_am_i(self):
print("I am a dog")
def bark(self):
print("Woof!")
my_animal = Animal()
my_dog = Dog()
my_dog.eat()
my_dog.who_am_i()
my_dog.bark()
#----------------------------------------
#Polymorphism
class Dog():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says woof!"
class Cat():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says meow!"
niko = Dog("Niko")
felix = Cat("Felix")
print(niko.speak())
print(felix.speak())
for pet in [niko,felix]:
print(type(pet))
print(pet.speak())
def pet_speak(pet):
print(pet.speak())
pet_speak(niko)
pet_speak(felix)
#---------------------------------
#ERROR
class AnimalBase():
def __init__(self,name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this abstract method!")
class Doggy(AnimalBase):
def speak(self):
return self.name + " says woof!"
fido = Doggy('Fido')
print(fido.speak()) | false |
63bc550f76e9a09cfdc638aa4969469f8068fe32 | cornel-kim/MIT_Class_October | /lesson3a.py | 820 | 4.1875 | 4 | #we have covered, variables, data types and operators.
#implement python logics. if else statements. conditinal statements
#mpesa buy airtime- account you are buying for, account balance,
# pin, okoa jahazi arrears.
# Account = input("Please input the account number:")
# Amount = input("Please input the amount or airtime:")
# Pin = int(input("Input valid pin:"))
# if Pin == 4000:
# print("You have bought the airtime successfuly")
#
# else:
# print("wrong pin, try again")
number = -3#check a number if it is positive or negative
if number < 0:
print("negative number")
else:
print("positive number")
student_marks = 250
if student_marks < 250:
print("repeat the unit")
else:
print("You passed")
#check student performance for pass and fail, i.e over 50 is
# pass and less than 50 is fail
| true |
11d674f105b3d7851c61a501c946be7202432ed4 | gabrielbolivar86/simple_python_scripts | /tire_volume.py | 1,815 | 4.5625 | 5 | #calculate the volume of a tire and storage it on TXT document
#Libraries
import math
from datetime import date
#1st get the data necesary to calculate the tire volume
# tire_width = float(input("Enter the width of the tire in mm (ex 205): "))
# tire_aspect = float(input("Enter the aspect ratio of the tire (ex 60): "))
# tire_diameter = float(input("Enter the diameter of the wheel in inches (ex 15): "))
#comment the variables of the line 6 to 8 and uncomment 11 to 16 for debuging
tire_width = 185
print (f"Enter the width of the tire in mm (ex 205): {tire_width}")
tire_aspect = 50
print (f"Enter the aspect ratio of the tire (ex 60): {tire_aspect}")
tire_diameter = 14
print (f"Enter the diameter of the wheel in inches (ex 15): {tire_diameter}")
pi = math.pi
#2nd set new variables in order to apply them to the formula that calculates the volume
w = float(tire_width)
a = float(tire_aspect)
d = float(tire_diameter)
#3rd calculate the tire volume with the formula
v = format(pi*w**2*a*(w*a+2.540*d)/10000000000, '.2f' )
#4th Return data to the user
print(f'The approximate volume is {v} liters')
#From here starts the 2nd week prove
#1st define today on a variable
current_date = date.today()
print (current_date)
#2nd convert the data to storage into string
current_date_str = str(current_date)
tire_width_str = str(tire_width)
tire_aspect_str = str(tire_aspect)
tire_diameter_str = str(tire_diameter)
volume_str = str(v)
#3nd set a variable with the information to storage
data_to_storage = ("| " + current_date_str +" | "+ tire_width_str +" | "+ tire_aspect_str +" | "+ tire_diameter_str+" | "+ volume_str + " |")
#4th open file that we will use as a database
file_object = open("volume.txt", 'a')
file_object.write(str(data_to_storage))
file_object.write('\n')
file_object.close() | true |
894ea0771249c060f9bbd1f623d2a07b5a8c2bf2 | hubbm-bbm101/lab5-exercise-solution-b2210356108 | /Exercises/Exercise1.py | 428 | 4.15625 | 4 | number = int(input("Enter the number:"))
if number % 2 == 0:
oddnumber = number - 1
formulanumber = (oddnumber+1)/2
else:
formulanumber = (number+1)/2
sumodd = formulanumber**2
print("Sum of odd numbers:", str(sumodd))
evennumbers = range(2,number,2)
sumeven = 0
a = 0
for i in evennumbers:
sumeven = i + sumeven
a+=1
average = sumeven/a
print("average of even numbers:", str(average))
| true |
08956994c6649c0e52b64fc54fd751d59ae8ce52 | zephyr-c/oo-tic-tac-toe | /components.py | 2,326 | 4.125 | 4 | class Player():
"""A player of the tic-tac-toe game"""
def __init__(self, name, game_piece):
self.name = name
self.game_piece = game_piece
class Move():
"""A single move in the tic-tac-toe game"""
def __init__(self, author, position):
self.author = author
self.position = position
def __repr__(self):
"""display game piece in representation"""
return f"{self.author.game_piece}"
class Board():
"""Game Board containing/displaying the moves of the game"""
moves = [[' ', '1', '2', '3'], ['1', '_', '_', '_'], ['2', '_', '_', '_'], ['3', '_', '_', '_']]
def display(self):
for row in self.moves:
print(row[0], row[1], row[2], row[3])
def add_move(self, move):
# space = self.moves[move.position[0]][move.position[1]]
if self.moves[move.position[0]][move.position[1]] != '_':
print('Space already occupied! \nInvalid move!')
else:
self.moves[move.position[0]][move.position[1]] = move
class Game():
"""An instance of a game of tic-tac-toe"""
def __init__(self, board, player1, player2):
self.board = board
self.player1 = player1
self.player2 = player2
self.winner = None
# self.started_at = started_at
# self.finished_at = finished_at
# def check_winner(self):
# b = self.board.moves
# wins = {'d_right': [b[1][1], b[2][2], b[3][3]],
# 'd_left': [b[3][1], b[2][2], b[1][3]],
# 'col_1': [row[1] for row in b[1:]],
# 'col_2': [row[2] for row in b[1:]],
# 'col_3': [row[3] for row in b[1:]],
# 'row_1': b[1],
# 'row_2': b[2],
# 'row_3': b[3]}
# for path in wins.values():
# if (all(spc(type) != str for spc in path) and
# all(spc.author == path[0].author for spc in path)):
# self.winner = path[0].author
# print(f"{self.winner} is the winner")
# else:
# print("No winner yet!")
if __name__ == '__main__':
harry = Player("Harry", "X")
hermione = Player("Hermione", "O")
my_board = Board()
game = Game(my_board, harry, hermione)
first_move = Move(harry, [1, 3])
| true |
aeef567aa047d2190d91cb6dbb32b505fb7c6b04 | michellejanosi/100-days-of-code | /projects/rock_paper_scissors.py | 1,785 | 4.21875 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
# Rock wins against Scissors.
# Scissors win against Paper.
# Paper wins against Rock.
player = int(input("What do you choose? Pick 0 for Rock, 1 for Paper, or 2 for Scissors. "))
choice = [0, 1, 2]
computer = random.choice(choice)
if player < 0 or player >= 3:
print("Invalid number. You lose")
quit()
if player == 0:
if computer == 0:
print(rock)
print("Computer chose:")
print(rock)
print("It's a draw")
elif computer == 1:
print(rock)
print("Computer chose:")
print(paper)
print("You lose")
else:
print(rock)
print("Computer chose:")
print(scissors)
print("You won")
elif player == 1:
if computer == 0:
print(paper)
print("Computer chose:")
print(rock)
print("You win")
elif computer == 1:
print(paper)
print("Computer chose:")
print(paper)
print("It's a draw")
else:
print(paper)
print("Computer chose:")
print(scissors)
print("You lose")
else:
if computer == 0:
print(scissors)
print("Computer chose:")
print(rock)
print("You lose")
elif computer == 1:
print(scissors)
print("Computer chose:")
print(paper)
print("You win")
else:
print(scissors)
print("Computer chose:")
print(scissors)
print("It's a draw") | false |
d0e98e7202d56fbefd7264203a5d5851a425fbaa | michellejanosi/100-days-of-code | /projects/area_calc.py | 621 | 4.3125 | 4 | # You are painting a wall. The instructions on the paint can says that 1 can of paint can cover 6 square meters of wall. Given a random height and width of wall, calculate how many cans of paint you'll need to buy.
# number of cans = (wall height ✖️ wall width) ÷ coverage per can.
import math
height = int(input("Height of wall: "))
width = int(input("Width of wall: "))
coverage = 6
def paint_area_calc(height, width, cover):
area = height * width
num_of_cans = math.ceil(area / cover)
print(f"You'll need {num_of_cans} cans of paint.")
paint_area_calc(height=height, width=width, cover=coverage) | true |
5a54831a9faa524123b5c4cc35c95b022ad8ab4b | michellejanosi/100-days-of-code | /algorithms/leap_year.py | 961 | 4.3125 | 4 | # A program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February.
# A leap year is on every year that is evenly divisible by 4 **except** every year that is evenly divisible by 100 **unless** the year is also evenly divisible by 400
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
# determin the number of days in a month in a given year
def days_in_month(year, month):
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap_year = is_leap_year(year)
if leap_year and month == 2:
return 29
else:
return 28
return month_days[month] - 1
print("Check how many days are in a given month.")
year = int(input("Enter a year: "))
month = int(input("What is the month: "))
days = days_in_month(year, month)
print(f"{days} days")
| true |
50b6ab8a005c611d38156b585713391f42faa973 | Eylon-42/classic-sudoku-py | /backtrack.py | 2,746 | 4.125 | 4 | import random
def validate_sudoku(board, c=0):
m = 3
c = 0
validate = False
# check all 81 numbers
while c < 81:
i, j = divmod(c, 9) # the current cell coordinate
i0, j0 = i - i % m, j - j % m # the start position of the 3 x 3 block
current_number = board[i][j] # current number to check
board[i][j] = '0' # take the number out of lst in order to check if we find duplicates
if (current_number not in board[i] # not in row
and all(row[j] != current_number for row in board) # not in column
and all(current_number not in row[j0:j0 + m] # not in block
for row in board[i0:i0 + m])):
board[i][j] = current_number # if duplicate not found return the number to its place for next check
validate = True
else:
return False # we found duplicate. solution not good
c += 1
if c + 1 >= 81 and validate: # finish all numbers in table and did not found duplicate
return validate
def make_board(m=3):
"""Return a random filled m**2 x m**2 Sudoku board."""
n = m ** 2
board = [[0 for _ in range(n)] for _ in range(n)]
def search(c=0):
"Recursively search for a solution starting at position c."
i, j = divmod(c, n)
i0, j0 = i - i % m, j - j % m # Origin of mxm block
numbers = list(range(1, n + 1))
random.shuffle(numbers)
for x in numbers:
if (x not in board[i] # not in row
and all(row[j] != x for row in board) # not in column
and all(x not in row[j0:j0 + m] # not in block
for row in board[i0:i])):
board[i][j] = x
# if not end of board and did not found duplicate call function recursively
if c + 1 >= n ** 2 or search(c + 1):
return board # end of board and found solution (meaning no duplicates)
else:
# No number is valid in this cell: backtrack and try again.
board[i][j] = 0
return None
return search()
def removeK(K, board):
count = int(K)
client_board = board
while count != 0:
cellID = random.randint(0, 80) # pick random cell number
i = cellID // 9 # get the x coordinate
j = cellID % 9 # get the y coordinate
if j != 0:
j = j - 1
if client_board[i][j] != 0: # if there is a number in the cell
count -= 1 # counter according to the difficulty lvl
client_board[i][j] = ' ' # delete number
return client_board
| true |
3789a408088b094e66aa0c7591ff3c93cd1515ca | trini7y/conjecture-proofs | /collatz_conjecture/collatz_sequence.py | 480 | 4.3125 | 4 | print( '''A program to see if the collatz
conjecture is true \n''')
print ("======****=================*****======= \n")
number = int(input('Input any number: '))
def collazt(number):
while number > 0:
if number % 2 == 0:
number = number // 2
elif number % 2 == 1:
number = (3 * number) + 1
if number == 1:
print(number)
break
print (number)
collazt(number)
| true |
9329edbb60144923e0ec8aad296650d2edacee38 | ThomasMcDaniel91/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 1,242 | 4.1875 | 4 | def intersection(arrays):
"""
YOUR CODE HERE
"""
# Your code here
# create empty dict
nums_dict = {}
# create empty list
result = []
# going through the first list in our list of lists
for num in arrays[0]:
# appending the values from the first list into our
# dict with an arbitrary value
nums_dict[num] = 0
# afterwards, go through the rest of the lists to check which numbers
# they share with the first list
for num in arrays[1:]:
# going through the items in each list and seeing if it exists
# in the dict created by the first list
for item in num:
if item in nums_dict:
# checking to see if the item is in the dict and then
# checking to make sure it isn't already in our results list
if item not in result:
result.append(item)
# return populated list of common numbers
return result
if __name__ == "__main__":
arrays = []
arrays.append(list(range(1000000, 2000000)) + [1, 2, 3])
arrays.append(list(range(2000000, 3000000)) + [1, 2, 3])
arrays.append(list(range(3000000, 4000000)) + [1, 2, 3])
print(intersection(arrays))
| true |
97ba0c6f0767147bca3924d5c37ac2516ea4150f | chinnagit/python | /sample.py | 610 | 4.125 | 4 | # name = raw_input('what is your name? ')
# color = raw_input('what is your favorite color ')
#
# print('Hi '+name + ' likes ' + color)
# weight = raw_input('what is your weight in pound? ')
# weight_in_kgs = float(weight)/2.25
# print('{name} weight is ' + str(weight_in_kgs))
#
# name = 'jayanth'
#
# print(name[-3:])
# is_good = False
#
# if is_good :
# print("pay 10 % down payment")
#
# else :
# print("pay 20 % down payment")
numbers = [10, 5, 25, 40, 20, 30]
maxNumber = 0
for number in numbers:
if number > maxNumber :
maxNumber = number
print("Max number: "+str(maxNumber))
| true |
64257fa443d9b6aa8c7cb8553087adc29454e048 | julianruben/mycode | /dict01/dictChallenge.py | 1,199 | 4.28125 | 4 | #!/usr/bin/env python3
heroes= {
"wolverine":
{"real name": "James Howlett",
"powers": "regeneration",
"archenemy": "Sabertooth",},
"harry potter":
{"real name": "Harry Potter",
"powers": "magic",
"archenemy": "Voldemort",},
"captain america":
{"real name": "Steve Rogers",
"powers": "frisbee shield",
"archenemy": "Hydra",}
}
doItAgain = "Y"
# excellent use of a while loop!
# now, you only want the loop to run again UNLESS they type 2, right?
# then consider using this:
#while doItAgain < "2":
while doItAgain == "Y":
char_name = input(" Which character do you want to know about? (Wolverine, Harry Potter, Agent Fitz)?").lower()
char_stat = input("What statistic do you want to know about? (real name, powers, archenemy)?").lower()
if heroes.get(char_name) is not None:
value = heroes[char_name].get(char_stat)
print(f"{char_name.title()} 's {char_stat} is: {value}")
else:
print("The character you have given is not present")
doItAgain = input("Do you want to continue (Y / N)?")
| true |
b378875888e67a74f00b0e375b97d43e4e684b45 | Montenierij/Algorithms | /Bipartite.py | 1,731 | 4.15625 | 4 | ######################################################
# Jacob Montenieri
# Introduction To Algorithms
# Lab 9
# This lab goes over if a graph is bipartite or not.
# This is determined by seeing if vertices can be
# colored blue and red without having adjacent
# matching colors.
######################################################
class Graph:
def __init__(self):
self.graph_dict = {}
def addEdge(self, node, neighbour):
if neighbour not in self.graph_dict.keys():
self.graph_dict[neighbour] = []
if node not in self.graph_dict:
self.graph_dict[node] = [neighbour]
else:
self.graph_dict[node].append(neighbour)
def show_edges(self):
for node in self.graph_dict:
for neighbour in self.graph_dict[node]:
print("(", node, ", ", neighbour, ")")
def bipartite(self):
for v in self.graph_dict.keys():
visited[v] = ""
queue = [0]
visited[0] = "Red"
while queue:
s = queue.pop(0)
for i in self.graph_dict[s]:
if visited[i] == "":
queue.append(i)
if visited[i] == visited[s]:
return False
if visited[s] == "Red":
visited[i] = "Blue"
elif visited[s] == "Blue":
visited[i] = "Red"
return True
g = Graph()
visited = {}
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 3)
g.addEdge(2, 3)
g.addEdge(1, 0)
g.addEdge(2, 0)
g.addEdge(3, 1)
g.addEdge(3, 2)
if g.bipartite():
print("Graph is bipartite")
else:
print("Graph is not bipartite")
| true |
eabb5ea3d79d26d0275b2a95e7136d842152c88b | elainew96/coding_exercises | /project_python/ch_01/hello.py | 840 | 4.53125 | 5 | '''
Exercise: hello, hello!
Objective: Write and call your own functions to learn how the program counter steps through code.
You will write a program that introduces you and prints your favorite number.
Write the body of the function print_favorite_number
Write a function call at the end of the program that calls print_favorite_number.
Write a new function, say_introduction that prints Hello, my name is X. and I am a Y. on two separate lines, where X and Y are replaced by whatever you like.
Add a line that calls say_introduction so that the introduction is printed before the favorite number.
'''
def print_favorite_number():
print("My favorite number is 6!")
def say_introduction():
print("Hello, my name is Elaine.")
print("I am a UC Davis alumni.")
say_introduction()
print_favorite_number()
| true |
40d31dc0ae389a1ee4b2a90df9d7d7ba766ec62d | MadhuriSarode/Python | /ICP1/Source Code/stringReverse.py | 712 | 4.15625 | 4 |
# Get the input from user as a list of characters with spaces as separators
input_List_of_characters = input("Enter a list elements separated by space ")
print("\n")
# Split the user list
userList = input_List_of_characters.split()
print("user list is ", userList)
# Character list to string conversion
inputString = ""
for char in userList:
inputString += char
print("input string = ", inputString)
# Deleting 2 characters
char_deleted_string = inputString[:inputString.index('y')] + inputString[inputString.index('y')+2:]
print("String with 2 characters deleted = ", char_deleted_string)
# Reversing the string
reversed_string = char_deleted_string[::-1]
print("Reversed string = ", reversed_string)
| true |
7164e6216b0549046af29246d672d5e5a8df21f4 | UMDHackers/projects_langs | /factorial.py | 242 | 4.125 | 4 | #factorial
def factorial(number):
if number == 0:
return 0
if number == 1:
return 1
return number * factorial(number-1)
#main
number = input("Enter a number: ")
print("number: "+ str(number) + " factorial "+ str(factorial(number))) | true |
09ecb6d8c3b8b9ea03c27b38b5b5abf42483d45c | marceloamaro/Python-Mombaca | /Lista Aula06 - Listas e Tuplas/06.py | 1,283 | 4.28125 | 4 | """Encapsule o código da questão anterior em uma função, que recebe a lista criada e a letra de uma operação. A função deve retornar o resultado da operação representada por esta letra de acordo com o enunciado da questão anterior."""
def operacao(lista,letra):
if letra == "a" or letra == "A":
print(f"Os dez primeiros números da lista são: {lista[0:10]}\n")
elif letra == "b" or letra == "B":
print(f"Os dez últimos números da lista são: {lista[31:41]}\n")
elif letra == "c" or letra == "C":
print(f"Os cinco itens do meio da lista são: {lista[18:23]}\n")
elif letra =="d" or letra == "D":
lista.reverse()
print(f"lista reversa: {lista}\n")
elif letra == "e" or letra == "E":
print(f"primeiro indice {lista[0]} ,ultimo indice {lista[-1]}\n")
elif letra == "f" or letra == "F":
lista = [item**2 for item in range(0,41)]
print(f"Itens elevados ao quadrado: {lista}\n")
elif letra == "g" or letra == "G":
lista = [numero for numero in range(0,41) if numero % 2 == 0]
print(f"Lista dos pares: {lista}")
else:
print("letra invalida")
letra = input("Digite uma letra\n")
lista = []
for i in range(0,41):
lista.append(i)
operacao(lista,letra) | false |
c455dd1391008f7185f4a6af94a6baf655ef0d88 | marceloamaro/Python-Mombaca | /Lista Aula03 Decisões e Repetições/08.py | 365 | 4.1875 | 4 | """
Faça uma função que receba uma lista de números inteiros e retorne o maior elemento desta lista. Utilize o for
"""
lista = []
def criar(lista):
for i in range(0, 10):
lista.append(int(input(f"digite um valor para prosição {i}:")))
print(f"Voce digitou os valores da {lista}")
print ("O maior elemento: ", max(lista))
x = criar(lista) | false |
2e1e3159f0361b5cfacd0c4917a4978a8228b0aa | marceloamaro/Python-Mombaca | /Lista Aula03 Decisões e Repetições/01.py | 794 | 4.25 | 4 | """
Escreva uma função que simule o funcionamento de um radar eletrônico. Essa função deve receber a velocidade do carro de um usuário. Caso ultrapasse 80 Km/h, exiba uma mensagem dizendo que o usuário foi multado. Nesse caso, exiba o valor da multa, cobrando R$ 90 reais pela infração + R$ 5 reais por km acima de 80 km/h
"""
velocidade = float(input("Qual a velocidade Atual do carro em km/h-->"))
def result(velocidade):
if velocidade > 80:
print("MULTADO, o VIDAL lhe passou a caneta")
print("MULTADO, Voce execedeu o limite permitido de 80km/h")
multa = 90 +((velocidade - 80)*5)
print("o Valor da multa é de R${:.2f}!".format(multa) )
else:
print("tenha um bom dia, Dirigia com segurança")
return
x = result(velocidade)
| false |
105fe95176771abda3276207c93a49981716d7f0 | marceloamaro/Python-Mombaca | /Lista Aula07 - Dicionários e Sets/05.py | 668 | 4.25 | 4 | """Utilizando o dicionário criado na questão anterior faça: Uma função que retorne apenas os valores pares do dicionario da questão anterior Uma função que retorne apenasas chaves vogais do dicionário da questão anterior """
nome="marcelo"
def estrutura(nome):
dic = {x : [x for x in range(7) ] for x in nome}
print("\n", dic)
estrutura(nome)
lista_vogais=['a','e','i','o','u','A','E','I','O','U']
def vogais(nome,lista_vogais):
for i in nome:
if i in lista_vogais:
print(i)
vogais(nome,lista_vogais)
def numeros(nome):
b = {x : [x for x in range(7) if x %2 == 0 ] for x in nome}
print("\n",b)
numeros(nome) | false |
dedd5f66fc529649a7120dfa62f024225b44eaf1 | marceloamaro/Python-Mombaca | /Lista Aula06 - Listas e Tuplas/02.py | 339 | 4.21875 | 4 | """Faça o mesmo que que se pede na questão anterior, mas a terceira lista não pode ter itens repetidos. """
lista1 = [1, 2, 3, 4, 5]
lista2 = [5, 6, 7, 8, 9]
def lista_final(lista1,lista2):
lista3 = []
lista3.extend(lista1)
lista3.extend(lista2)
lista3 = set(lista3)
print(f"{lista3}")
lista_final(lista1,lista2) | false |
519288225b0eb3990bbfbe5a4c2968d9eb6c5a99 | oldmonkandlinux/python-basics | /for.py | 254 | 4.15625 | 4 | '''
for loop
'''
for item in 'Ashish':
print(item)
for item1 in ['apples', 'mangoes', 'pears']:
print(item1)
for item2 in range(10):
print(item2)
for item3 in range(1, 10):
print(item3)
for item4 in range(1, 10, 2):
print(item4)
| false |
d6f22db680a74d0f8623a7b0f41895a206582a23 | vs666/Pirates-of-the-Pacific | /Coins.py | 1,535 | 4.125 | 4 | from data import *
import random
# coin class is used to check all the functionalities of coins in the game
class Coin:
# this is the compulsary constructor method
def __init__(self):
self.bitcoin = []
self.bcX = []
self.bcY = []
self.coin_amount = 12
self.initialize()
# this is to initialize the coins on the screen
def initialize(self):
for i in range(self.coin_amount):
self.bitcoin.append(pygame.image.load('bitcoin.png'))
self.bcX.append(random.randint(32, 746))
self.bcY.append(random.randint(32, 746))
# this is to put/draw the coins on the screen
def coin(self):
for i in range(self.coin_amount):
screen.blit(self.bitcoin[i], (self.bcX[i], self.bcY[i]))
# this is to add a coin if a coin is consumed by the ship
def addCoin(self, i):
self.bcX[i] = random.randint(32, 746)
self.bcY[i] = random.randint(32, 746)
screen.blit(self.bitcoin[i], (self.bcX[i], self.bcY[i]))
# this is to check if an object (ship) has collided with a coin and
# consumed it
def coinCollide(self):
for i in range(self.coin_amount):
# print("HERE")
if abs(self.bcX[i] -
objects["player"][objects["mode"]].player_X) <= 32 and abs(
self.bcY[i] -
objects["player"][objects["mode"]].player_Y) <= 32:
self.addCoin(i)
return True
return False
| false |
325b1be9213bccac043365fdea0e961fef784612 | tanvipenumudy/Competitive-Programming-Solutions | /HackerRank/Problem-Solving/equalize_the_array.py | 2,087 | 4.34375 | 4 | # Karl has an array of integers. He wants to reduce the array until all remaining elements are equal.
# Determine the minimum number of elements to delete to reach his goal.
# For example, if his array is arr = [1,2,2,3], we see that he can delete the 2 elements 1 and 3 leaving arr = [2,2].
# He could also delete both twos and either the 1 or the 3, but that would take 3 deletions.
# The minimum number of deletions is 2.
# Function Description
# Complete the equalizeArray function in the editor below. It must return an integer that
# denotes the minimum number of deletions required.
# equalizeArray has the following parameter(s):
# arr: an array of integers
# Input Format
# The first line contains an integer n, the number of elements in arr.
# The next line contains n space-separated integers arr[i].
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the equalizeArray function below.
def equalizeArray(arr):
set_a = set(arr)
list_a = arr
count_ele = 0
ele_a = 0
for i in set_a:
if list_a.count(i) > count_ele:
ele_a = i
count_ele = list_a.count(i)
diff_a = list(set_a.difference({ele_a}))
print(diff_a)
count = 0
for i in diff_a:
while(i in list_a):
count += 1
list_a.remove(i)
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = equalizeArray(arr)
fptr.write(str(result) + '\n')
fptr.close()
# Output Format
# Print a single integer that denotes the minimum number of elements Karl must delete for
# all elements in the array to be equal.
# Sample Input
# 5
# 3 3 2 1 3
# Sample Output
# 2
# Explanation
# Array arr = [3,3,2,1,3]. If we delete arr[2] = 2 and arr[3] = 1, all of the elements in
# the resulting array, A` = [3,3,3], will be equal. Deleting these 2 elements is minimal.
# Our only other options would be to delete 4 elements to get an array of either [1] or [2]. | true |
d8bee4e1fa1b74568c8f4f30dbb9841b699edbf4 | tanvipenumudy/Competitive-Programming-Solutions | /HackerRank/Python/python-evaluation.py | 512 | 4.4375 | 4 | # It helps in evaluating an expression.
# The expression can be a Python statement, or a code object. --->
# >>> eval("9 + 5")
# 14
# >>> x = 2
# >>> eval("x + 3")
# 5
# eval() can also be used to work with Python keywords or defined
# functions and variables. These would normally be stored as strings. -->
# >>> type(eval("len"))
# <type 'builtin_function_or_method'>
# Without eval() -- >
# >>> type("len")
# <type 'str'>
A = input()
eval(A) # Don't use print() function since it prints None as well | true |
4d5d9e634d8c48382f373555a27501f490a5d941 | irisnunezlpsr/class-samples | /assignmentTester.py | 277 | 4.3125 | 4 | # creates a variable called word and sets it equal to "bird"
word = "bird"
# sets word equal to itself concatenated with itself
word = word + word
# word is now equal it itself concatenated with itself times 2
word = word + word
# should print birdbirdbirdbird
print(word)
| true |
fa981020f339414abf2c9bc1347be190638b1488 | pradeep14316/Python_Repo | /Python_exercise/ex13.py | 393 | 4.28125 | 4 | #Ask the user for a number and determine whether the number is prime or not.
def get_number():
num = int(input("Enter a number:\n"))
return num
def prime_check():
'check whether number is a prime or not'
num = get_number()
if (num % 2 != 0) and (num / num == 1):
print(num,"is a prime number")
else:
print(num,"is not a prime number")
prime_check()
| true |
f93238b907911d6b990c1f03cc0050bf54c65d24 | trevllew751/python3course | /bouncer.py | 301 | 4.125 | 4 | age = input("How old are you?\n")
if age:
age = int(age)
if age >= 21:
print("You can enter and you can drink")
elif age >= 18:
print("You can enter but you need a wristband")
else:
print("You cannot come in little one")
else:
print("Please enter an age")
| true |
bc40b023ec89a51b34fcb77aa27f7d80ea8c57cf | iscoct-universidad/dai | /practica1/simples/exercise2/bubble.py | 486 | 4.46875 | 4 | import numpy as np
def bubbleSorting(array):
length = len(array)
for i in range(0, length - 1):
for j in range(i, length):
if array[i] > array[j]:
temp = array[i]
array[i] = array[j]
array[j] = temp
desiredLength = int(input("Introduzca la longitud del array deseado: "))
array = np.random.rand(desiredLength)
print("Unsorted array:", array)
bubbleSorting(array)
print("Sorted array:", array) | true |
5d33c4b42e2198cac51d4f22db6776218aa1a68e | CatarinaBrendel/Lernen | /curso_em_video/Module 2/exer053.py | 332 | 4.125 | 4 | print "Enter a Phrase and I'll tell you if it is a Palindrome or not"
sentence = str(raw_input("Your phrase here: > ")).strip().lower().replace(' ', '')
pal = ""
for i in sentence:
pal = i + pal
if pal == sentence:
print "'{}' is a palindrome!".format(sentence)
else:
print "'{}' is NOT a palindrome!".format(sentence)
| true |
8ada8c672d4e4e5fc5d99621003aaefee3719531 | SMGuellord/PythonTut | /moreOnFunctions.py | 1,063 | 4.15625 | 4 | #argument with a default value.
def get_gender(sex='unknown'):
if sex is 'm':
sex = "Male"
elif sex is 'f':
sex = "Female"
print(sex)
#using keyword argument
def dumb_sentence(name='Bucky', action='ate', item='tuna'):
print(name, action, item)
#undefined number of arguments
def add_numbers(*args):
total = 0
for a in args:
total += a
print(total)
print("==========================================")
print("Function with default argument value")
print("============================================")
get_gender('m')
get_gender('f')
get_gender()
print("==========================================")
print("Function with keyword argument value")
print("============================================")
dumb_sentence("Sally", "eat", "slowly")
dumb_sentence(item="banana")
dumb_sentence(name="Sally", action="cooks")
print("==========================================")
print("Function with undefined number of arguments")
print("============================================")
add_numbers(3)
add_numbers(2,5,6)
| true |
484f0730135dfa75d2dda0ae46d0ca88f153156c | HuiJing-C/PythonLearning | /cjh/06object_oriented_programming/05instance_and_Class.py | 1,315 | 4.15625 | 4 | # 由于Python是动态语言,根据类创建的实例可以任意绑定属性。给实例绑定属性的方法是通过实例变量,或者通过self变量
class Student(object):
age = 18
def __init__(self, name):
self.name = name
if __name__ == '__main__':
s = Student("jack")
s.score = 90
print(s.name, s.score) # jack 90
# 但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student类所有
# 当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到。
print(s.age) # 实例属性 18
print(Student.age) # 类属性 18
# 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的age属性
s.age = 19
print(s.age) # 19
print(Student.age) # 18
# 如果删除实例的age属性, 再次调用s.age,由于实例的age属性没有找到,类的age属性就显示出来了
del s.age
print(s.age) # 18
# 从上面的例子可以看出,在编写程序的时候,千万不要把实例属性和类属性使用相同的名字,因为相同名称的实例属性将屏蔽掉类属性,但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性。
| false |
224e7e8d6fa1306e5f48dc35bd50487167de057d | HuiJing-C/PythonLearning | /cjh/06object_oriented_programming/03inheritance_polymorphism.py | 1,309 | 4.28125 | 4 | # 多态 inheritance 继承 polymorphism
class Animal(object):
def run(self):
print("Animal Run")
class Dog(Animal):
pass
class Cat(Animal):
# 多态
def run(self):
print("Cat Run")
def run_twice(animal):
animal.run()
animal.run()
class Fish(object):
def run(self):
print("fish swimming")
if __name__ == '__main__':
d = Dog()
d.run() # Animal Run (继承)
c = Cat()
c.run() # Cat Run
# 在继承关系中,如果一个实例的数据类型是某个子类,那它的数据类型也可以被看做是父类。但是,反过来就不行
print(isinstance(d, Animal)) # True
run_twice(Animal()) # Animal Run
run_twice(Cat()) # Cat Run
# 对于静态语言(例如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或者它的子类,否则,将无法调用run()方法。
# 对于Python这样的动态语言来说,则不一定需要传入Animal类型。我们只需要保证传入的对象有一个run()方法就可以了
# 这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。
run_twice(Fish()) # fish swimming
| false |
a5b66740552298a3373bfb4cd1068337577e47fd | GinaFabienne/python-dev | /Day2/mathOperators.py | 377 | 4.1875 | 4 | 3 + 5
4 - 2
3 * 2
8 / 2
#when you are dividing you almost always end up with a float
print(8 / 4)
print(type(8 / 4))
#powers
print(2 ** 2)
#PEMDAS (from left to right)
#Order of operations in python
#()
#**
#* /
#+-
#multiplication and division are priotitised the same but the one on left will happen first when they are both in same problem.
#eg
print(3 * 3 + 3 / 3 - 3)
| true |
45664a37ca38d8c7ea8af599be1958f48fd697b4 | bnoel2777/CSSI19 | /Day10/review.py | 458 | 4.125 | 4 | def Greater(x,y):
if x>=y:
return x
else:
return y
x = float(raw_input("Enter your first number"))
y = float(raw_input("Enter your second number"))
print Greater(x,y):
def Concatnation():
x = raw_input("Enter a string")
return x + x :
print Concatnation():
def Add(x,y,z):
x = (raw_input("Enter your first number"))
y = (raw_input("Enter your second number"))
z = (raw_input("Enter your third number"))
sum= (x + y + z) + 3
print Add():
| true |
1c05ba0af10868c703e8e69eb2a9a66b37417792 | l1onh3art88/bikingIndustry | /bicycles.py | 1,393 | 4.4375 | 4 | #Classes mirror the bike industry. There are 3 classes: Bicycle, Bike Shops,
#and Customers
class Bicycle(object):
def __init__(self, model, weight, cost):
self.model = model
self.weight = weight
self.cost = cost
class BikeShop(object):
def __init__(self, name,profit):
self.name = name
self.inventory = []
self.profit = profit
def sell(self, bike):
"""
Sells a bike
Adds to the shops profit by subtracting the price the bike is being
sold at from the cost to manufacture the bike
The bike is then removed from the inventory of the bikeshop
"""
self.profit += (1.2*(bike.cost)-(bike.cost))
self.inventory.remove(bike)
def balance(self):
print("The shop has made " + str(self.profit) + " dollars!")
class Customer(object):
def __init__(self,name,fund):
self.name = name
self.fund = fund
self.garage = []
def buy(self, bike):
"""
Buys a bike, subtracts the price the bike is being sold at from the
customer's fund.
Bike is then appended to the garage array to store the bike
Method ends buy printing the sold bike's model
"""
self.fund -= 1.2*(bike.cost)
self.garage.append(bike)
print("\n" +bike.model)
| true |
c88c866abdba67fee284b4f0eb3e62d286f24fc7 | AvidDollars/project-euler-solutions-python | /2_even_fibonacci_numbers.py | 1,458 | 4.125 | 4 | """
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
"""
from timer import timer
from types import FunctionType
@timer.register(4_000_000, lambda num: num if num % 2 == 0 else 0)
def fibonacci_numbers(max_num: int, filter_: FunctionType) -> int:
first, second = 2, 3
summation = 0
while first < max_num:
summation += filter_(first)
summation += filter_(second)
first += second
second += first
return summation
@timer.register(4_000_000) # timewise it has on average the same performance as 'fibonacci_numbers'
def fibonacci_numbers_two(max_num: int) -> int:
def yield_even_fib(max_num: int) -> int:
first, second = 2, 3
while first < max_num:
yield first
first += second
yield second
second += first
return sum(fib_num for idx, fib_num in enumerate(yield_even_fib(max_num)) if idx % 3 == 0)
timer.run(repeats=10_000, inject_results=True)
### DON'T REMOVE IT ### ccb7252550a0e00e26edb5d29f96d116 ###
#
# 'fibonacci_numbers':
# elapsed time: 0.132s, repeats: 10000, result: 4613732
# 'fibonacci_numbers_two':
# elapsed time: 0.133s, repeats: 10000, result: 4613732
| true |
3099801b30fc5781b0a94e2f250363cadb382477 | saramissak/GWC-mini-projects | /TextAdventure.py | 1,111 | 4.21875 | 4 |
# Update this text to match your story.
start = '''
You wake up one morning and find that you aren't in your bed; you aren't even in your room.
You're in the middle of a giant maze
A sign is hanging from the ivy: "You have one hour. Don't touch the walls."
There is a hallway to your right and to your left.'''
print(start)
print("Type 'left' to go left or 'right' to go right.")
user_input = input()
while user_input != "left" and user_input != "right":
print('try again')
user_input = input()
if user_input == "left":
print("You decide to go left and...") # Update to match your story.
# Continue code to finish story.
elif user_input == "right":
print("You choose to go right and ...") # Update to match your story.
# Continue code to finish story.
#have one of the next three lines not all
#else:
#if not(user_input == "left" or user_input =="right")
#elif user_input != "left" or "right":
#print("That is an invalid input. Try again! 'left' or 'right'?")
#if user_input != 'left' or 'right':
#print("That is an invalid input. Try again! 'left' or 'right'?") | true |
b7b4e5ffde731bcfec622c9f55f0e18093c32a65 | RishikaMachina/MySuper30 | /Precourse 2/Exercise2.py | 997 | 4.28125 | 4 | def quicksort(arr):
#when left part of right part is left with one number or no number; stop the recursion
if (len(arr) ==0) or (len(arr)==1):
return arr
#considering first element as pivot
pivot = arr[0]
i = 0
for j in range(len(arr)):
if arr[j] < pivot:
# swap values of arr[i] and arr[j] after increamenting i value
i += 1
arr[j],arr[i] = arr[i], arr[j]
# swap pivot and arr[i] values
arr[0],arr[i] = arr[i],arr[0]
#call quickSort function for left part of list till pivot index
left = quicksort(arr[:i])
# add pivot to the list
left.append(arr[i])
return left+ quicksort(arr[i+1:]) # calling quick sort for right part of the list
alist = [54,26,93,17,77,31,0,9,2,4,6,90]
print("original array is ",alist)
print("sorted array: ",quicksort(alist))
'''
#output
original array is [54, 26, 93, 17, 77, 31, 0, 9, 2, 4, 6, 90]
sorted array: [0, 2, 4, 6, 9, 17, 26, 31, 54, 77, 90, 93]
'''
| true |
01b89b6636c319d4daccf5c77c840755c4dc5270 | robbiecares/Automate-the-Boring-Stuff | /07/RegexStripv2_firsttry.py | 1,070 | 4.4375 | 4 | # ! python3
# RegexStrip_firsttry.py - a regex version of the .strip method
import re
string = "***$123$***"
#string = input("Please enter a string: ")
StripChar = "*"
#StripChar = input('''Please input the character that you'd like to trim from the ends of the string. If you'd like to trim whitespace only just press enter.
#Character: ''')
def trimmer(string,StripChar = " "):
modstring = string
TrimFrontRegex = re.compile(r'^[StripChar]')
FrontSearch = TrimFrontRegex.search(modstring)
#StripBackRegex = re.search(r'(.*)([StripChar]*$)', modstring)
while FrontSearch != None:
modstring = modstring[1:]
print(modstring)
"""
FrontResult = StripFrontRegex.search(string)
beg, afterbeg = FrontResult.groups()
BackResult = StripBackRegex.search(afterbeg)
mid, end = BackResult.groups()
cutresult = mid
print(cutresult)
#TODO: backresult is leaving blankspaces at end of string
#TODO: incorporate second arguement (i.e. an alternative cut char) into code
"""
trimmer(string, StripChar) | true |
2acb1ff10853ef3a92daadb62f6e76f15cf0d061 | Bradleyjr/E2020 | /section_4/assignment_4b.py | 403 | 4.1875 | 4 | # This program draws
form turtle import *
# bgcolor() changes
bgcolor("lightblue)
color"red")
shape("turtle"
penup()
# The crawl variable is used to
crawl = 10
# The turn variable is used to
turn = 35
for i in range(50):
# stamp() is used to
stamp()
# With each loop, crawl is
crawl = crawl + 3
# The crawl variable controls the
frward(crawl)
right(turn)
exitonclick()
| true |
3740003dc7f81406634dfb7f77d617b6dc08a5cb | ShehryarX/python-cheatsheet | /classes.py | 1,120 | 4.25 | 4 | # A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object
# Create class
class User:
# Constructor
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f'My name is {self.name} and I am {self.age}'
def has_birthday(self):
self.age += 1
# Customer class
class Customer(User):
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
self.balance = 0
def set_balance(self, balance):
self.balance = balance
def greeting(self):
return f'My name is {self.name} and I am {self.age} and I owe a balance of {self.balance}'
# Init user object
shehryar = User('Shehryar Assad', 'xshehryar@gmail.com', 18)
# Edit property
shehryar.age = 19
print(shehryar.age)
# Call method
print(shehryar.greeting())
shehryar.has_birthday()
print(shehryar.age)
# Init customer
john = Customer('John Doe', 'john@gmail.com', 40)
john.set_balance(500)
print(john.balance)
print(john.greeting())
| true |
8c08db7f77659258a8b3e0f9b61d4d7b5d271d00 | TylerA73/Shapes | /triangle.py | 2,989 | 4.25 | 4 | # Imports
import math
from shape import Shape
# Triangle class
# Contains all of the details of the Triangle
class Triangle(Shape):
# __init__: Constructor
# Construcst the Triangle
# Sides of a Triangle: a, b, c
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
# set_a: Setter
# Sets the length of a
def set_a(self, a):
self.a = a
# set_b: Setter
# Sets the length of b
def set_b(self, b):
self.b = b
# set_c: Setter
# Sets the length of c
def set_c(self, c):
self.c = c
# get_a: Function
# Returns the length of a
def get_a(self):
return self.a
# get_b: Function
# Returns the length of b
def get_b(self):
return self.b
# get_c: Function
# Returns the length of c
def get_c(self):
return self.c
# area: Function
# Calculates the area of the triangle
def area(self):
# Heron's Formula
# Area = sqrt(s(s - a)(s - b)(s - c))
# s = (a + b + c)/2
s = self.semiperimeter()
area = math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
return area
# perimeter: Function
# Calculates the perimeter of the triangle
def perimeter(self):
return self.a + self.b + self.c
# semiperimeter: Function
# Calculate the semiperimeter of the triangle
def semiperimeter(self):
return self.perimeter()/2
# angle_ab_radians
# Calculates the angle between a and b in radians
def angle_ab_radians(self):
# cos(C) = (a^2 + b^2 - c^2)/2ab
a_squared = self.a * self.a
b_squared = self.b * self.b
c_squared = self.c * self.c
return math.acos((a_squared + b_squared - c_squared)/(2 * self.a * self.b))
# angle_bc_radians
# Calculates the angle between b and c in radians
def angle_bc_radians(self):
# cos(A) = (b^2 + c^2 - a^2)/2bc
a_squared = self.a * self.a
b_squared = self.b * self.b
c_squared = self.c * self.c
return math.acos((b_squared + c_squared - a_squared)/(2 * self.b * self.c))
# angle_ca_radians
# Calculates the angle between c and a in radians
def angle_ca_radians(self):
# cos(B) = (c^2 + a^2 - b^2)/2ca
a_squared = self.a * self.a
b_squared = self.b * self.b
c_squared = self.c * self.c
return math.acos((c_squared + a_squared - b_squared)/(2 * self.c * self.a))
# angle_ab_degrees
# Calculates the angle between a and b in degrees
def angle_ab_degrees(self):
return math.degrees(self.angle_ab_radians())
# angle_bc_degrees
# Calculates the angle between b and c in degrees
def angle_bc_degrees(self):
return math.degrees(self.angle_bc_radians())
# angle_ca_degrees
# Calculates the angle between c and a in degrees
def angle_ca_degrees(self):
return math.degrees(self.angle_ca_radians())
| true |
0b96f728e58497b9b1212fe6c3c7510de8a80b0f | LaxmiNarayanaMurthyVemuri/Mentor216A-CSPP-1 | /FinalExam-Solutions/assignment3/tokenize.py | 684 | 4.21875 | 4 | '''
Write a function to tokenize a given string and return a dictionary with the frequency of
each word
'''
import re
def tokenize(string):
'''
TOKENIZE
'''
dictionary = {}
for i in string:
if i not in dictionary:
dictionary[i] = 1
else:
dictionary[i] += 1
return dictionary
def clean_string(text):
'''
CLEAN STRING
'''
return re.sub('[^a-zA-Z0-9]', " ", text.replace('\'', ''))
def main():
'''
MAIN
'''
sample_string = ""
for _ in range(int(input())):
sample_string += clean_string(input())
print(tokenize(sample_string.split()))
if __name__ == '__main__':
main()
| false |
7d39246616234177c780e233239c93b30c5c5c51 | vivsvaan/DSA-Python | /Mathematics/prime_factors.py | 644 | 4.15625 | 4 | """
Program to get prime factors of a number
"""
def prime_factors(number):
res = []
if number <= 1:
return res
while not number % 2:
res.append(2)
number = number // 2
while not number % 3:
res.append(3)
number = number // 3
i = 5
while i*i < number:
while not number % i:
res.append(i)
number = number // i
while not number % (i+2):
res.append(i+2)
number = number // (i+2)
i = i + 6
if number > 3:
res.append(number)
return res
print(prime_factors(int(input("Enter Number: "))))
| false |
2ce3222238c8087c4a7f8584bc1077a31ef2b52e | vivsvaan/DSA-Python | /Mathematics/palindrome_number.py | 390 | 4.21875 | 4 | """
Program to check if number is palindrome
"""
def is_palindrome(number):
num = number
reverse = 0
while num != 0:
last_digit = num % 10
reverse = reverse*10 + last_digit
num = num // 10
if reverse == number:
return True
return False
number = int(input("Enter number: "))
print("yes") if is_palindrome(number) else print("no")
| true |
358aab90c724826fa6b63ca69d34fc461d29c854 | ComradeMudkipz/lwp3 | /Chapter 3/instanceJoe.py | 619 | 4.21875 | 4 | # Chapter 3
# turtleInstance.py - Program which uses multiple turtles on screen.
import turtle
# Set up the window environment
wn = turtle.Screen()
wn.bgcolor('lightgreen')
wn.title('Tess & Alex')
# Create tess and set some attributes
tess = turtle.Turtle()
tess.color('hotpink')
tess.pensize(5)
# Create alex
alex = turtle.Turtle()
# Make tess draw equilateral triangle
for i in range(3):
tess.forward(80)
tess.left(12)
# Turn tess around
tess.right(180)
# Move her away from the origin
tess.forward(80)
# Make alex draw a square
for i in range(4):
alex.forward(90)
alex.left(90)
wn.mainloop()
| true |
c4d1e4b637c7fca7810d69f54fa8e42c300c9550 | ComradeMudkipz/lwp3 | /Chapter 2/alarmClockConverter.py | 623 | 4.53125 | 5 | # Chapter 2 - Exercise 8
# alarmClockConverter.py - Converts the time (24 hr) with the number of hours
# inputted and hours to pass.
# Prompt for current time and sets to an integer
timeNowPrompt = input("What time is it now? " )
timeNow = int(timeNowPrompt)
# Prompt for number of hours to pass and sets to an integer
hourAmountPrompt = input("How many hours do you want to set alarm? ")
hourAmount = int(hourAmountPrompt)
# Conversions
initTime = hourAmount + timeNow
days = initTime // 24
setTime = initTime - (days * 24)
# Print what time alarm will go off.
print("The alarm will go off at", str(setTime) + ":00")
| true |
fe8779680512758d6c1e991aab1053c3a46661f0 | khanmazhar/python-journey | /task_lab.py | 563 | 4.125 | 4 | x = input('Enter a number.')
y = input('Enter another number.')
try:
x_num = float(x)
y_num = float(y)
except:
print('Invalid Input! Try again...')
quit()
if x_num % 2 == 1 and y_num % 2 == 1:
print('Product of x and y is', x_num * y_num)
if y_num % 11 == 0 and y_num % 13 != 0:
if x_num % 11 != 0 and x_num % 13 == 0:
print('Vice versa!')
else:
print('False Alarm :(')
if x_num >= 0 and y_num >= 0 or x_num <= 0 and y_num <= 0:
print('Product would be positive.')
else:
print('Product would be negative.')
| true |
3b2dd979e59a1aee6beb6552c14033aae721d0f7 | Xolo-T/Play-doh | /Python/Basics/conditions.py | 1,923 | 4.34375 | 4 | # you dont need brackets in your conditions
# elif instead of else if
# after contion we just add a ':'
# -----------------------------------------------------------------------------
# Conditional
# -----------------------------------------------------------------------------
# if, elif, else, ternary
# and istead of &&
is_old = False
is_beautiful = True
is_married = False
# if is_old and is_beautiful:
# print('Marry her')
# elif is_married:
# pass
# else:
# print('You smart nyash')
# ternary
print('Marry her now!') if is_beautiful else print('You can do better bro!')
# indentation
# interpreter looks for spacing instead of curly braces
# Logical operators
# and, or , <, >, <=, >=, ==, != ,not ,not()
# chaining conditionals - is a big yes in python
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# Truthy and Falsy values in python
# -----------------------------------------------------------------------------
# Falsey values -
# Truthy values -
# is checks the value
print(True == 1)
print('' == 1)
print('1' == 1) # no type conversion only hapens in Truthy
print([] == 1)
print(10 == 10.0)
print([] == [])
# is checks the memory lication therefore stings and numbers are true
print(True is 1)
print('' is 1)
print('1' is 1)
print([] is 1)
print(10 is 10.0)
print([] is [])
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# short circuiting
# -----------------------------------------------------------------------------
# In and & or intepreter skips second part of conditioning is its not vecessary
# -----------------------------------------------------------------------------
| true |
f22f0b9803f963e0ba0283ad810a6aea49065cf0 | Xolo-T/Play-doh | /Python/Basics/generators.py | 414 | 4.21875 | 4 | # help us generate a sequence of values
# a generator is a subset of iterable
# a generator funtion is created using the range and the yeild keywords
# yield poses the funtion and returns to it when next is called
# next can only be called as much as the length of the range
def generator_fn(num):
for i in range(num):
yield i * 2
g = generator_fn(6)
# next(g)
# next(g)
print(g)
# print(next(g))
| true |
b403cef706ae3a3e6e47c28dbe881b374f7087af | kritik-Trellis/python-Training | /Examples/checkprime.py | 463 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 10:39:11 2020
@author: trellis
"""
import math
n=int(input("Enter the number of values you want to enter"))
values=[int(input("Enter the values")) for i in range(n)]
def checkPrime(num):
for i in range(2,int(math.sqrt(num))+1):
if(num%i==0):
return False
return True
prime=[]
for i in values:
ret=checkPrime(i)
if ret==True:
prime.append(i)
print(prime)
| true |
e1ec56591180c7138000e62bcecc207664636791 | jam941/hw | /hw06/selection_sort.py | 1,818 | 4.4375 | 4 | '''
Author: Jarred Moyer <jam4936@rit.edu>
Title: selection_sort.py
Language: python3
Description: Uses selective sorting to sort a list from a file specified by the user.
Assignment: Hw07
1: Insertion sort preforms better than selection sort the more sorted the list is initially.
For example: the test case [1,2,3,4,6,5,7,9,8] will sort faster in insertion sort rather than
substitution sort.
2: Insertion sort only moves numbers that must be moved, while substitution sort will always move
all but one number at least once.
'''
def get_next_idx(lst):
'''
Takes a list and returns the index of its smallest value
'''
best = int(lst[0])
best_count = 0
count = 0
for i in lst:
if i < best:
best = i
best_count = count
count += 1
return best_count
def selection_sort(data):
'''
Sorts a list by the paramater data using selection sort. returns the sorted list
data must be a list
'''
for i in range(0,len(data)):
x = get_next_idx(data[i:])
sliced = data[i:]
if(x!=0):
y = data[i]
data[i] = data[x+i]
data[x+i] = y
else:
pass
return data
def import_data(path):
'''
Converts a text file into a list of numbers.
returns a list where each cell is one line from the file
path must be a string
'''
f = open(path)
lst = []
for i in f:
lst = lst + [int(i)]
return lst
def main():
'''
Queries the user for a file to sort, then sorts the numbers from said file. prints the unsorted and sorted file.
:return:
'''
path = input('What file would you like to sort?: ')
data = import_data(path)
print('Initial list: ', data)
print(' Sorted list: ',selection_sort(data))
main() | true |
2711c8cfe027ee38dd9f6125d5256513f6475ddd | ellyanalinden/mad-libs | /mad-libs/Mad Lib/mad-libs/languageparts.py | 1,554 | 4.46875 | 4 | #!/usr/bin/env python
# import modules here
import random
# Create a dictionary of language parts. It must contain: noun, verb, adjective.
# The key should be one of the types of language (e.g. noun) and the value
# should be the list of words that you choose.
lang_parts = {
'noun': ['man', 'mountain', 'state', 'ocean', 'country'],
'verb': ['add', 'bite', 'work', 'run', 'arrest'],
'adj' : ['ambitious', 'brave', 'calm', 'delightful', 'faithful']
}
# this is a function that you can learn about in the functions chapter
def get_word_part(part):
# put your code to get a language part here
# NOTE: use 'part' (which is going to be either 'noun', 'verb', or
# 'adjective') to get the type of words from your 'lang_parts' dictionary.
# Store the result in a variable called 'words'
part = lang_parts.keys()
return part
words = get_word_part(part)
# NOTE: you can use 'random.shuffle(words)' to mix up 'words' and then just
# grab the first element or you can use 'random.choice(words)' to select a
# random element. You could also use random.randint(0, len(words)-1) to get
# a random index and then use that index to select a word. Store the result
# of this operation in a variable called word
word = random.choice(list(d.items()))
# NOTE: once you have a word you just say 'return word' and that's it! (so
# you don't need to change anything here).
return word
# make sure that you return the language part e.g.
return word
| true |
52ea24de292acecbc102d5ea98fdb9412b2eb914 | KevinQL/LGajes | /PYTHON/POO VIII. Herencia III - V31.py | 978 | 4.21875 | 4 | """
HERENCIA: Uso de dos funciones más utilizadas en python
super()
isinstance(9)
Vocabulario:
principio de sustentación ::: clasPadre "Es siempre un/a" clasHija ## isinstance(objeto, Clase)
"""
class Persona():
def __init__(self, nombre, edad, lugarResidencia):
self.nombre = nombre
self.edad = edad
self.lugarResidencia = lugarResidencia
def descripcion(self):
print("NOMBRE:",self.nombre, "\nEDAD:", self.edad, "\nRESIDENCIA:", self.lugarResidencia)
class Empleado(Persona):
def __init__(self, salario, antiguedad, nombre, edad, ciudad):
super().__init__(nombre, edad, ciudad)
self.salario = salario
self.antiguedad = antiguedad
def descripcion(self):
super().descripcion()
print("SALARIO:",self.salario,"\nANTIGÜEDAD:",self.antiguedad, "años",end="\n***\n")
Kevin = Empleado(2500, 15, "Kevin",22,"Andahuaylas")
Kevin.descripcion()
print(isinstance(Kevin, Empleado))
### True
print(isinstance(Kevin, Persona))
### True
| false |
2a273126ad102d44f6bb4edf63f69acae261e01c | stratosm/NLP_modules | /src/class_ratio.py | 662 | 4.25 | 4 | # Author: Stratos Mansalis
import pandas as pd
def ratio_(df, cl):
"""
Calculates the frequency by class of the dataframe
Arguments
---------
df: the given dataframe
cl: the name of the class
Usage
-----
df = ratio_(data, 'class')
Returns
-------
A dataframe with two columns:
- the first named 'Class' contains the name of each class.
- the second named 'Total' contains the frequency
"""
df = df[cl].value_counts()
df = df.to_frame()
df.reset_index(level=0, inplace=True)
df.columns = ['Class', 'Total']
return df
| true |
c3db6e40e20d3b746432443038ce632c370654b3 | stein212/turtleProject | /tryTurtle.py | 1,856 | 4.21875 | 4 | import turtle
# hide turtle
turtle.ht() # or turtle.hideturtle()
# set turtle speed to fastest
turtle.speed(0)
# fastest: 0
# fast: 10
# normal: 6
# slow: 3
# slowest: 1
# draw square manually
for i in range(4):
turtle.forward(10)
turtle.left(90)
# move turtle position
turtle.penup()
turtle.setpos(30, 0)
turtle.pendown()
# draw circle using turtle's api
turtle.circle(10) # the circle draws from the bottom -> top -> bottom
# move turtle position
turtle.penup()
turtle.setpos(60, 0)
turtle.pendown()
# draw an arc
turtle.circle(10, 90)
# move turtle position
turtle.penup()
turtle.setpos(90, 0)
turtle.pendown()
# draw a diamond
turtle.setheading(0) # set the direction the turtle is facing
turtle.circle(10, steps = 4)
# move turtle position
turtle.penup()
turtle.setpos(120, 0)
turtle.pendown()
# draw a square
turtle.left(45)
turtle.circle(10, steps = 4)
# move turtle position
turtle.penup()
turtle.setpos(0, 30)
turtle.pendown()
# draw a blue line
turtle.color("blue")
turtle.forward(10)
# set color back to black
turtle.color("black")
# move turtle position
turtle.penup()
turtle.setpos(30, 30)
turtle.pendown()
# draw rectangle with green fill and black stroke
turtle.setheading(0)
turtle.color("black", "green")
turtle.begin_fill()
turtle.forward(10)
turtle.left(90)
turtle.forward(5)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(5)
turtle.left(90)
turtle.end_fill()
# move turtle position
turtle.penup()
turtle.setpos(60, 30)
turtle.pendown()
# write some text
turtle.write("Hello World!", font=("Arial", 8, "normal"))
# move turtle position
turtle.penup()
turtle.setpos(120, 30)
turtle.pendown()
# write some text
turtle.write("Hello World Again!", font=("Arial", 10, "bold"))
# turtle.write has 2 more parameters which is align and move, align is more important in this project
turtle.exitonclick() | true |
1b43aa798eec9071c0dc44fd4545494909506ec6 | miraclecyq/pythonwork | /coffeeghost-q-in-py.py | 975 | 4.15625 | 4 | # -*- coding:utf-8 -*-
# Quick Python Script Explanation for Programme
# 给程序员的超快速Python脚本解说
import os
def main():
print 'Hello World!'
print "这是Alice\'的问候。"
print '这是Bob\'的问候。'
foo(5,10)
print '=' * 10
print '这将直接执行'+os.getcwd()
counter = 0 #变量得先实例化才可进一步计算
counter += 1
print counter
'''这是我自己加的多行注释
'''
food =['苹果','杏子','李子','梨']
for i in food:
print '俺就爱整只:'+i
print '数到10'
for i in range(10):
print i
def foo(param1,secondParam):
result = param1 + secondParam
print '%s 加 %s 等于 %s'%(param1,secondParam,result)
if result < 50:
print '这个'
elif (result >= 50) and ((param1 == 42) or (secondParam == 24)):
print '那个'
else:
print '嗯...'
return result
if __name__=='__main__':
main()
| false |
956d829748aba3d4a631e871449e8468b21672bc | claudiuclement/Coursera-Data-Science-with-Python | /Week2-word-counter-problem.py | 483 | 4.46875 | 4 | #Word counter problem - Week 2
#This code is much simpler than the code provided by the course tutor
#Code used below
from collections import Counter
#opens the file. the with statement here will automatically close it afterwards.
with open("/Users/Claudiu/Downloads/word_cloud/98-0.txt") as input_file:
#build a counter from each word in the file
count = Counter(word for line in input_file
for word in line.split())
print(count.most_common(10))
| true |
669cf95f8ca83e5586452b090f1ebf1267a3c161 | farahzuot/data-structures-and-algorithms-python | /tests/challenges/test_array_shipt.py | 693 | 4.3125 | 4 | from data_structures_and_algorithms.challenges.array_shift.array_shift import insertShiftArray
"""
type of list
type of num
add a number to odd list
add a number to even list
"""
def test_list_type():
actual = insertShiftArray(5,4)
expected = 'invalid input'
assert actual == expected
def test_num_type():
actual = insertShiftArray([1,2,3],'3')
expected = 'TypeError! should be an int'
assert actual == expected
def test_add_even():
actual = insertShiftArray([4,6,8,12],10)
expected = [4,6,10,8,12]
assert actual == expected
def test_add_odd():
actual = insertShiftArray([13,6,5,4,2],10)
expected =[13,6,5,10,4,2]
assert actual == expected | true |
00a3dd214090957c8387f75df441feb07360f7e3 | farahzuot/data-structures-and-algorithms-python | /data_structures_and_algorithms/challenges/ll_zip/ll_zip.py | 872 | 4.1875 | 4 | # from data_structures_and_algorithms.data_structures.linked_list.linked_list import Linked_list
def zipLists(first_l,sec_l):
if type(first_l) != list or type(sec_l) != list:
return "invalid input"
'''
this function takes in two linked lists as arguments. Zip the two linked lists together into one so that the nodes alternate between the two lists and return a reference to the head of the zipped list.
'''
a=len(first_l)+len(sec_l)
n=0
count=1
t=True
while True:
if t:
first_l.insert(count,sec_l[n])
count+=1
n+=1
t=False
else:
first_l.insert(count+n,sec_l[n])
count+=1
n+=1
if len(first_l) == a:
return first_l
if __name__ == "__main__":
pass
print(zipLists([1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9]))
| true |
ff2f8db32772d21a9677160e1eb38564ddeee223 | farahzuot/data-structures-and-algorithms-python | /tests/challenges/test_ll_zip.py | 925 | 4.21875 | 4 | from data_structures_and_algorithms.challenges.ll_zip.ll_zip import zipLists
def test_happy_path():
'''
this function will test the normal path
'''
actual = zipLists([1,2,3],[1,2,3])
expected = [1,1,2,2,3,3]
assert actual == expected
def test_invilid_input():
'''
this function will test if the inputs are not lists
'''
actual = zipLists(1,[1,2,3])
expected = "invalid input"
assert actual == expected
def test_listTwo_longer_than_listOne():
'''
this function will test if the second list longer than the first list
'''
actual = zipLists([1,2,3],[1,2,3,4,5])
expected = [1,1,2,2,3,3,4,5]
assert actual == expected
def test_listOne_longer_than_listTwo():
'''
this function will test if the first list longer than the second list
'''
actual = zipLists([1,2,3,4,5],[1,2,3])
expected = [1,1,2,2,3,3,4,5]
assert actual == expected | true |
c630c22542fbde46f0a585d5b0e58dca12b840e0 | malloryeastburn/Python | /pw.py | 724 | 4.125 | 4 | #! python3
# pw.py - An insecure password locker program.
# password dict
PASSWORD = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
import sys, pyperclip
# if user forgets to include a command line argument, instruct user
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
# if account is stored in PASSWORDS, copy to clipboard
# else, notify user
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)
| true |
06eea92ff092eef3df728b082305ff0eb792b444 | izark99/100DaysPython | /Day004/day4.4_rock_paper_scissors.py | 1,259 | 4.25 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
your_choose = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
if your_choose > 2 or your_choose < 0:
print("You type wrong number! So I choose random for you")
your_choose = random.randint(0,2)
if your_choose == 0:
print(rock)
elif your_choose == 1:
print(paper)
else:
print(scissors)
elif your_choose == 0:
print(rock)
elif your_choose == 1:
print(paper)
elif your_choose == 2:
print(scissors)
print("Computer choose: ")
ramdom_choose = random.randint(0,2)
if ramdom_choose == 0:
print(rock)
elif ramdom_choose == 1:
print(paper)
else:
print(scissors)
if your_choose == 0 and ramdom_choose == 2:
print("You win!")
elif ramdom_choose > your_choose:
print("You lose!")
elif ramdom_choose < your_choose:
print("You win!")
elif ramdom_choose == your_choose:
print("Draw!")
else:
print("You lose!")
| false |
49c4065b5e8c44814d8fb0cf973aec16b8e0cc74 | helloworld755/Python_Algorithms | /dz2_task6.py | 1,042 | 4.125 | 4 | # В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать
# не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше
# введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано,
# то вывести загаданное число.
from random import randint
num = randint(0, 100)
i = 0
while i < 10:
user_num = int(input('Угадайте число: '))
if user_num == num:
print('Вы угадали!')
i = 10
else:
if user_num > num:
print('Ваше число больше загаданного.')
else:
print('Ваше число меньше загаданного.')
i += 1
print(f'Загаданное число: {num}')
| false |
fd00067ec525dd0f4be2d2fa29c9b9e6e4866f5b | reisthi/python-excercises | /tuples.py | 1,258 | 4.25 | 4 | """Tuple exercises"""
# Tuples and strings are immutable
# A single item is not a tuple item. Ex: tuple = (1)
# Unless you add a comma in the end. Ex: tuple = (1,)
def get_oldest(bar1, bar2):
"""Return earliest of two MM/DD/YYYY-formatted date strings."""
year_one, year_two = bar1.split('/')[-1], bar2.split('/')[-1]
month_one, month_two = bar1.split('/')[-2], bar2.split('/')[-2]
day_one, day_two = bar1.split('/')[-3], bar2.split('/')[-3]
date_one = (year_one, month_one, day_one)
date_two = (year_two, month_two, day_two)
if date_one > date_two:
return print(str(date_two), "is older than: ", str(date_one))
else:
return print(str(date_one), "is older than: ", str(date_two))
def name_key(name):
"""Return last-first name tuple from first-last name tuple."""
first_name = name.split(' ')[-2]
last_name = name.split(' ')[-1]
return last_name, first_name
def sort_names(name):
"""Return given first-last name tuples sorted by last name."""
return sorted(name, key=name_key)
def name_key_simpler(name):
first, last = name.split()
return last, first
def swap_ends(bar):
"""Swap the first and last items in the given list."""
bar[0], bar[-1] = bar[-1], bar[0] | true |
12c9bd5d17c032731f1c5898b22c81f0086149a3 | reisthi/python-excercises | /lists.py | 925 | 4.4375 | 4 | """List exercises"""
list_one = ['a', 'b', 'c', 1, 2, 3]
list_deux = ["Un", "deux", "trois"]
list_trois = ["Un", "deux", "trois"]
list_quatre = ["UN", "deux", "trois"]
def combine_lists(one, two):
"""Return a new list that combines the two given lists."""
return one + two
def rotate_list(my_list):
"""Move first list item to end of list and return the item."""
# return my_list[0], my_list[-1] == my_list[-1], my_list[0]
item = my_list.pop(0)
my_list.append(item)
return item
def reverse_words(sentence):
"""Return the given sentence with the words in reverse order."""
return sentence.reverse()
def ith_item_power(bar, index):
"""Returns i-th element raised to the i-th power."""
result = bar[index]
return result**index
def comp_lists(one, two):
""" Compares two lists. Obs: It's case sensitive."""
same_items = set(one) & set(two)
return same_items
| true |
b19c48279f02a322bcfff4cca970090a2ec1b5e2 | Ernest93/Ernest93 | /Zajęcia 3.py | 2,542 | 4.25 | 4 | """
#escapowanie znaków specjlanych
zmienna = r"To jest jakiś \ntekst z użytym znakiem nowej lini który ni będzie interpretowany"
print(zmienna)
zmienna = 'To jest jakiś: "tekst" z użytym cudzysłowem'
print(zmienna)
zmienna = 'To jest \n nowa linia'
print(zmienna)
"""
#kilka sposobów na formatowanie stringów
"""
wartosc_zmiennej = 23
zmienna = f"To jest napis: {wartosc_zmiennej}" #nie trzeba martiwć się rzutowaniem
print(zmienna)
zmienna = "To jest napis: " + str(wartosc_zmiennej)
print(zmienna)
zmienna = 012.33001
print("zmienna %s" % zmienna)
print("zmienna %f" % zmienna)
print("zmienna %d" % zmienna)
#więcej o stringach https://docs.python.org/3/tutorial/introduction.html#strings
#inne ciekawe znaczniki formatowania https://docs.python.org/3/library/string.html#format-examples
print("To jest {ilosc} sposób na wprowadzanie {nazwa}".format(nazwa='zmiennych', ilosc=3))
#sprawdzanie wielu warunków
"""
""""
liczba = 13456
if(liczba % 3 == 0 and liczba % 5 == 0):
print("liczba podzielna przez 3 i 5")
elif(liczba % 3 == 0 or liczba % 5 == 0):
print("liczba podzielna przez 3 lub 5")
elif(liczba % 3 == 0):
print("liczba podzielna przez 3")
elif(liczba % 5 == 0):
print("liczba podzielna przez 5")
else:
print("nie podzielna przez 3 i 5")
"""
""""
#tworzenie obiektu typu range()
duzy_zakres = range(1,40000000)
lista = [1, 2, "trzy", 4, "pięć"]
print(lista)
#nadpisywanie wartości
lista[0] = "jeden"
lista[0] = "1"
lista[0] = "raz"
#dodawanie na koniec listy
lista.append("sześć")
#kasowanie na podstawie indeksu
del(lista[0])
#kasowanie na podstawie wartości
print(lista.remove("trzy")) #sprawdźcie co się stanie jak podamy wartość której nie ma
#zrzucanie elementu
print(lista.pop(2))
#inne ciekawe fukncje https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
duza_lista = list(range(1,50))
#ogromna_lista = list(range(1,40000000)) #może "zabić" komputer ;)
#listy zagnieżdżone
lista_2d = [
[1,2,3],
[4,5,6, "NAPIS"],
[7,8,9]
]
lista_2d[1][3] = lista_2d[1][3] + '!!!!'
print(lista_2d)
#rozpakowywanie
wyrazy = ("raz", "dwa", "trzy")
a, b, c = wyrazy
"""
print("Policzę dla ciebie do 100")
i=1
while (i <= 100):
print(str(i) + ' ', end='') # print bez nowych linii
# print(i)
i += 1
print('\nA teraz Cię o coś zapytam')
print('=' * 20) #mnożenie stringów
#pętla przydatna przy odpytywaniu użytkownika o coś
decyzja = None
while(decyzja != 'T'):
decyzja = input("Wcisnij 'T' aby zakonczyc program: ") | false |
feb9c24aa6bedfcae32654759a74b239fb3e84b1 | vyashole/learn | /03-logic.py | 835 | 4.34375 | 4 | # just declaring some variables for use here
x = 5
y = 10.5
z = 5
# Booleans: Booleans are logical values that can be True or False
# you can use logical operators to check if an expression is True or False
print(y > x) # True
print(x == y) # False
print(z < x) # True
# Here are the different operators
# This will be useful in if statements and loops
# Cpmparison Operators
# == Equal (note the double equal signs single equals is used for assignment)
# != Not equal
# > Greater than
# < Less than
# >= Greater than or equal
# <= Less than or equal
# Logical Operators
# and Returns True if both expressions are true
# or Returns True if one of the expressions is true
# not Reverse the result, returns False if the result is true
# Examples:
print(x > 3 and x < 10)
print(x > 3 or x < 4)
print(not(x > 3 and x < 10))
| true |
5bef3ff143aefaf55973e00c9c52264afb50ab32 | nhat117/Hello-World | /condition/con.py | 431 | 4.125 | 4 | a = 10
b = 10
c = 5
d = 5
if (a > b):
print("Hello World")
if (a != b):
print("Hello World")
if(a == b):
print("Yes")
else :
print("No")
#else if is elif
if (a == b) :
print("1")
elif (a > b) :
print("2")
else :
print("3")
#and operator
if a == b and c == d:
print("Hello")
#or operator
if a == b or c == d :
print("Hello or")
# can print on 1 line
if a > b : print("Hello")
print("True") if a == b else print("False") | false |
a91cb26dbc8806d7c72744322c1075839c73fa76 | aambrioso1/CS-Projects | /tictactoe.py | 2,302 | 4.125 | 4 | # A program for solving the monkey tictactoe problem.
# A list of rows in the game board
row_list = ['COW', 'XXO', 'ABC']
# Other test games:
# row_list = ['AAA', 'BBB', 'CCC'] # single winners: 3, doublewinners: 0
# row_list = ['ABA', 'BAB', 'ABA'] # single winners: 1, doublewinners: 1
# row_list = ['AAA', 'CBC', 'CBC'] # single winners: 1, doublewinners: 3
# The string of letters use by the monkeys in the game.
string = row_list[0] + row_list[1] + row_list[2]
letterset = set(string) # Unique letters used in game.
# Each row is broken up into a list of individual letters.
bd = row_list[0] + row_list[1] + row_list[2]
# Define strings for the rows, colums and that must be checked.
row1 = bd[:3]
row2 = bd[3:6]
row3 = bd[6:]
col1 = '' + bd[0] + bd[3] + bd[6]
col2 = '' + bd[1] + bd[4] + bd[7]
col3 = '' + bd[2] + bd[5] + bd[8]
diag1 = '' + bd[0] + bd[4] + bd[8]
diag2 = '' + bd[2] + bd[4] + bd[6]
# Create a list of rows to check to use for iteration.
checklist = [row1, row2, row3, col1, col2, col3, diag1, diag2]
# Create the subsets of checklist that are wins for one monkey (singlewinnerlist)
# or two monkeys (double winnerlist).
countlist = []
singlewinners = []
doublewinners = []
for s in checklist:
for char in letterset:
countlist.append(s.count(char))
if s.count(char) == 3:
singlewinners.append(s)
if s.count(char) == 2:
doublewinners.append(s)
# print(countlist)
print('Single winners: ', singlewinners)
print('Double winners: ', doublewinners)
# Create a list of the monkeys that have a win on their own (singlewinnerlist) or with a partner (doublewinnerlist). Note that it is important count single monkeys and teams not wims!
singlewinnerlist = []
doublewinnerlist = []
for i in singlewinners:
k = set(i)
if k not in singlewinnerlist: # Only add unique single-winners to the list.
singlewinnerlist.append(k)
for i in doublewinners:
k = set(i)
if k not in doublewinnerlist: # Only add unique double-winners to the list.
doublewinnerlist.append(k)
print('Unique winner lists ', singlewinnerlist, doublewinnerlist)
print('\nThe solution is:')
print(len(singlewinnerlist))
print(len(doublewinnerlist)) | true |
b47b3013b01d68ccd576d3fb31c2c899e6ac307f | aambrioso1/CS-Projects | /mumble.py | 771 | 4.21875 | 4 | def word_parse(text):
'Breaks up text into words defined as characters separted by a space'
low = 0 # Position of the beginning of a word
hi = 0 # Position of the end of a word
word_list = []
for i in text:
if i ==' ': # Check if we reached the end of a word
word_list.append(text[low:hi])
low = hi+1 # Set the start position of the next word
hi += 1 # Step the next character in the word
word_list.append(text[low:len(text)]) # Put the last word on the list
return word_list
list1 = '1 mumble 3 mumble 5 mumble mumble 8 mumble'
words = word_parse(list1)
print('Here is the list of words spoken by Vesa: {}.'.format(words))
print('Vesa tried to count to {}.'.format(len(words)))
| true |
98a8af5f21dd3854aa73a14d49f6023fa692f77b | gauthamkrishna1312/python-basics | /Loop/Stars.py | 320 | 4.125 | 4 | num = int(input("Enter height : "))
row = 0
while row < num:
space = num - row - 1
while space > 0:
print(end =" ")
space = space - 1
star = row + 1
while star > 0:
print("*",end=" ")
star = star - 1
row = row + 1
print()
else:
print("\n\nStar Finished")
| false |
079e25d42ab313c66358ed881aae7c2381bd5253 | willkc15/CodingCurriculum | /01_Core/week05/submissions/pythonClasses.py | 601 | 4.15625 | 4 | #Abstract Class
class Animal():
def __init__(self, name):
self.name = name
print("Hello, I'm {}".format(self.name))
def who_ami_i(self):
raise NotImplementedError("Cannot create instances of an abstract class")
class Dog(Animal):
def who_am_i(self):
print("I am a dog")
def speak(self):
return self.name + " says Woof!"
class Cat(Animal):
def speak(self):
return self.name + " says Meow!"
niko = Dog("niko")
felix = Cat("felix")
#Polymorphism
def pet_speak(pet):
print(pet.speak())
pet_speak(niko)
pet_speak(felix) | false |
084402ba521a98fe595349274e8d499d5ddd6d20 | cristinamais/exercicios_python | /Exercicios Loop/exercicio 22 - secao 06.py | 701 | 4.28125 | 4 | """
22 - Escreva um programa completo que permita a qualquer aluno introduzir, pelo teclado, uma sequencia
arbitrária de notas (válidas no intervalo de 10 a 20) e que mostre na tela, como resultado, a correspondente
média aritmética. O número de notas com que o aluno pretenda efetuar o cálculo não será fornecido ao programa,
o qual terminará quando for introduzido um valor que não seja válido como nota de aprovação.
"""
soma = 0
cont = 0
mediaAritimetica = 0
nota = 10
while nota >= 10 and nota <= 20:
nota = float(input('Digite a nota: '))
if nota < 10 or nota > 20:
break
soma = soma + nota
cont += 1
mediaAritimetica = soma / cont
print(mediaAritimetica)
| false |
7fcdd203f8b6090aae41315e5640907f6d3d309e | cristinamais/exercicios_python | /Exercicios Colecoes Python/exercicio 02 - secao 07 - p1.py | 513 | 4.21875 | 4 | """
02 - Crie um programa que lê 6 valores inteiros e, em seguida, mostre na tela os valores lidos
"""
# Minha resolução:
"""
listaN = []
for n in range(6):
n = int(input('Digite o número: '))
listaN.append()
print(f'O número digitado foi: {n}')
"""
# Resolução do professor.
valores = []
# Recebe cada um dos valores
for n in range(6):
valor = int(input('Digite um número: '))
valores.append(valor)
# Imprime cada um dos valores
for valor in valores:
print(valor)
| false |
837d2e63f6492cad69210c57689589602a785a8a | cristinamais/exercicios_python | /Exercicios Loop/exercicio 47 - secao 06.py | 1,594 | 4.375 | 4 | """
47 - Faça um programa que apresente um menu de opções para o cálculo das seguintes operações entre dois números:
Adicao (opção 1) ..subtracao (opção 2)... multiplicacao (opção 3).. divisao (opção 4).. saida (opção 5)
O programa deve possibilitar ao usuário a escolha da operação desejada, a exibição do resultado e a volta ao menu de opções.
O programa só termina quando for escolhido a opção de saída (opção 5)
"""
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
print('Escolha uma das opções para fazer o cálculo: \nAdição (opção 1)\nSubtração (opção 2)\nMultiplicação (opção 3)\nDivisao (opção 4)\nSair (opção 5)')
escolha = int(input())
while escolha != 5:
if escolha == 1:
soma = n1 + n2
print(f'A soma dos números {n1} + {n2} = {soma}')
elif escolha == 2:
subtracao = n1 - n2
print(f'A subtração entre os números {n1} - {n2} = {subtracao}')
elif escolha == 3:
multiplicacao = n1 * n2
print(f'A multiplicação entre os números {n1} x {n2} = {multiplicacao}')
elif escolha == 4:
divisao = n1 / n2
print(f'A divisão entre os números {n1} / {n2} = {divisao:.2f}')
elif escolha == 5:
break
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
print('Escolha uma das opções para fazer o cálculo: \nAdição (opção 1)\nSubtração (opção 2)\nMultiplicação (opção 3)\nDivisao (opção 4)\nSair (opção 5)')
escolha = int(input())
| false |
7ece04482a9465d97127a7d629af0531789a3594 | cristinamais/exercicios_python | /Exercicios Estruturas Logicas e Condicionais/exercicio 01 - secao 05.py | 501 | 4.125 | 4 | """
1 - Faça um programa que receba dois números e mostre qual deles é o maior.
"""
numero1 = int(input("Digite o primeiro número: "))
numero2 = int(input("Digite o segundo número: "))
if numero1 > numero2:
print(f"Entre os números {numero1} e {numero2} .O número maior é: {numero1}")
elif numero1 == numero2:
print(f"Entre os números {numero1} e {numero2} .O número maior é: {numero1}")
else:
print(f"Entre os números {numero1} e {numero2} .O número maior é: {numero2}")
| false |
963ed4b25d1b60cda07b890614d5f6e6a4c5dc91 | cristinamais/exercicios_python | /Exercicios Loop/exercicio 21 - secao 06.py | 587 | 4.15625 | 4 | """
21 - Faça um programa que receba dois números. Calcule e mostre:
a) A soma dos números pares desse intervalo de números, incluindo os números digitados;
b) A multiplicação dos números ímpares desse intervalo, incluindo os digitados.
"""
numero1 = int(input('Digite o primeiro numero: '))
numero2 = int(input('Digite o segundo numero: '))
somaPares = 0
multiplicacaoImpar = 1
for i in range(numero1, numero2 + 1):
if i % 2 == 0:
somaPares = somaPares + i
else:
multiplicacaoImpar = multiplicacaoImpar * i
print(somaPares)
print(multiplicacaoImpar)
| false |
c08b69591c6d83f2f6de52e42ff44541bdfe8aeb | cristinamais/exercicios_python | /Exercicios Estruturas Logicas e Condicionais/exercicio 03 - secao 05.py | 366 | 4.125 | 4 | """
3 - Leia um número real. Se o número for positivo imprima a raiz quadrada.
Do contrário, imprima o número ao quadrado.
"""
numero = float(input("Digite um número: "))
if numero > 0:
numero = numero ** (1/2)
print(f'A raiz quadrada desse número é {numero:.2f}.')
else:
numero = numero ** 2
print(f'Este número ao quadrado é: {numero}')
| false |
54cf8fa431ac0ab108f7f4bf8786d1f6f8ca70a3 | cristinamais/exercicios_python | /Exercicios Loop/exercicio 49 - secao 06.py | 1,125 | 4.21875 | 4 | """
49 - O funcionário chamado Carlos tem um colega chamado João que recebe um salário que equivale a um terço do seu salário. Carlos gosta de fazer
aplicações na caderneta de poupança e vai aplicar seu salário integralmente nela, pois está rendendo 2% ao mês. João aplicará seu salário
integralmente no fundo de renda fixa, que está rendendo 5% ao mês. Construa um programa que deverá calcular e mostrar a quantidade de meses
necessários para que o valor pertencente a João iguale ou ultrapasse o valor pertencente a Carlos. Teste com outros valores para as taxas.
"""
salarioCarlos = int(input('Digite o valor do salário de Carlos: '))
salarioJoao = salarioCarlos // 3
print(f'Salário de João: {salarioJoao}')
renda1 = 0.02
renda2 = 0.05
cont = 0
while salarioJoao <= salarioCarlos:
salarioCarlos = salarioCarlos + (salarioCarlos * renda1)
salarioJoao = salarioJoao + (salarioJoao * renda2)
cont += 1
print(f'Salário Carlos + Aplicação: {salarioCarlos:.2f}\nSalário João + Aplicação: {salarioJoao:.2f}')
print(f'João levou {cont} meses para igualar ou ultrapassar Carlos.')
| false |
03306a34c58b5b490b157a3f261659b6b58406fd | cristinamais/exercicios_python | /Exercicios Estruturas Logicas e Condicionais/exercicio 13 - secao 05.py | 1,247 | 4.34375 | 4 | """
13 - Faça um algorítmo que calcule a média ponderada das notas de 3 provas.
A primeira e a segunda prova tem peso 1 e a terceira tem peso 2. Ao final,
mostrar a média do aluno e indicar se o aluno foi aprovado ou reprovado.
A nota para a aprovação deve ser igual ou superior a 60 pontos.
"""
nota1 = float(input("Digite a primeira nota: "))
nota2 = float(input("Digite a segunda nota: "))
nota3 = float(input("Digite a terceira nota: "))
#peso1 = (nota1 * 1) + (nota2 * 1) esse eu fiz
peso2 = nota3 * 2
mp = (nota1 + nota2 + peso2) / 3
if mp >= 60:
print(f'As suas notas foram: {nota1}, {nota2} e {nota3} e a sua média foi: {mp:.2f}, portanto você foi aprovado.')
else:
print(f'As suas notas foram: {nota1}, {nota2} e {nota3} sua média foi {mp:.2f}, portanto você foi reprovado.')
#print(dir(nota1))
"""
Olá Cristina,
Sua solução está correta.
Só uma observação:
Quando é 60 * 1?
E quanto é 50 * 1?
Concorda que qualquer número multiplicado por 1 é ele mesmo?
Então faz sentido usar o processador para efetuar este cálculo?
Acredito que não, então na linha 12 daria para remover e então alterar a mp para:
mp = (nota1 + nota2 + peso2) / 3
Faça o teste e qualquer coisa poste aqui.
Abraço!
""" | false |
b12e1e77f9e87c3da76d4d8f0bd19f14b85d96d3 | cristinamais/exercicios_python | /Exercicios Colecoes Python/exercicio 24 - secao 07 - p1.py | 789 | 4.25 | 4 | """
24 - Faça um programa que leia dez conjuntos de dois valores, o primeiro representando o número do aluno e o segundo
representado a sua altura em metros. Encontre o aluno mais baixo e o mais alto. Mostre o número do aluno mais baixo
e do aluno mais alto, juntamente com suas alturas.
"""
data = {}
for i in range(10):
numero = int(input('Digite o número do aluno: '))
altura = float(input('Digite a altura: '))
data[numero] = altura
# print(sorted(data.items())) -> Colocando os dados em ordem de maior para menor.
maximum = max(data, key=data.get)
print(f'O aluno mais alto está no número: {maximum} e a sua altura é {data[maximum]}')
minimum = min(data, key=data.get)
print(f'O aluno mais baixo está no número: {minimum} e a sua altura é: {data[minimum]}')
| false |
5791abe088bbf292869b0f6a2e2b6dd098e841d5 | cristinamais/exercicios_python | /Exercicios Estruturas Logicas e Condicionais/exercicio 26 - secao 05.py | 1,114 | 4.1875 | 4 | """
26 - Leia a distância em KM e a quantidade de litros de gasolina consumidos por
um carro em um percurso, calcule o consumo em km/l e escreva uma mensagem de
acordo com a tabela abaixo:
----------------------------------------
CONSUMO | (Km/l) | MENSAGEM
----------------------------------------
menor que | 8 | Venda o carro!
----------------------------------------
entre | 8 e 11 | Econômico!
----------------------------------------
maior que | 12 | Super Econômico!
------------------------------------------
"""
km = float(input("Digite a distancia percorrida: "))
litros = float(input("Digite a quantidade de litros consumido: "))
consumo = km / litros
if consumo < 8:
print(f'Venda o carro! O consumo foi de {consumo:.2f} Km/h')
elif consumo >= 8 and consumo <= 11:
print(f'Econômico! O consumo foi de {consumo:.2f} Km/h')
elif consumo > 12:
print(f'Super Econômico! O consumo foi de {consumo:.2f} Km/h')
else:
print(f'Cuidado o seu carro não está sendo econômico, consumo foi de {consumo:.2f} Km/h')
| false |
babe1e0f299cfe2224cbadd51fadc2047c3d34d5 | cristinamais/exercicios_python | /Exercicios List Comprehension/exercicio 14 - secao 08.py | 744 | 4.28125 | 4 | """
14 - Faca uma funcao que receba a distancia em KM e a quantidade de litros de gasolina consumidos por um carro em um
percurso, calcule o consumo em KM / l e escreva uma mensagem de acordo com a tabela abaixo:
__________________________________
CONSUMO (KM /l) MENSAGEM
----------------------------------
menor que 8 Venda o carro
entre 8 e 12 Economico
maior que 14 Super Economico
"""
km = float(input('Digite a distancia percorrida em KM: '))
l = float(input('Digite a quantidade de litros consumidos: '))
def consumo(*args):
if km / l < 8:
return 'Venda o carro'
elif (km / l > 8) and (km / l <= 12):
return 'Economico'
return 'Super Economico'
print(consumo())
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.