blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c7eb099dd3f48b31546d0b893eaa4ba6dcd0b47e
HankarM88/OOP_Pillars
/abstraction.py
820
4.28125
4
from abc import abstractmethod, ABC class Vehicle(ABC): def __init__(self, brand,speed, year): self.speed = speed self.year = year self.brand=brand def __str__(self): return f'{self.brand}\n{self.speed}\n{self.year}' def start(self): print("Starting engine") def stop(self): print("Stopping engine") @abstractmethod def drive(self): print('driving the car..') #create a class to inherit from class Car(Vehicle): def __init__(self,brand, speed, year,mileage): super().__init__(brand,speed, year) self.mileage = mileage def drive(self): print("the Car is in drive mode") def start(self): print('The Car is starting') car=Car('BMW','200km/h','2015',80000) print(car) car.drive() car.start()
false
7ef095e8af9a009705b1162fbd92c5e072ee8345
Jean-Bi/100DaysOfCodePython
/Day 19/turtle_race/main.py
2,354
4.65625
5
# Imports the Turtle and Screen classes from the turtle module from turtle import Turtle, Screen # Imports the random module import random # Initializes the variable that will allow to start/stop the race is_race_on = False # Creates a new Screen object screen = Screen() # Sets the size of the screen screen.setup(width=500, height=400) # Creates a user input for him to place his bet user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color :") # Stores turtles colors colors = ["red", "orange", "yellow", "green", "blue", "purple"] # Stores turtles starting positions y_position = [-100, -60, -20, 20, 60, 100] # Initializes a List that will contain the turtles all_turtles = [] # Creates 6 turtles for turtle_index in range(6): # Creates a new Turtle object with the shape of a turtle new_turtle = Turtle("turtle") # Lifts up the pen for the turtle so it doesn't leave a trail new_turtle.penup() # Assign a color to the turtle new_turtle.color(colors[turtle_index]) # Sets the starting position of the turtle new_turtle.goto(x=-230, y=y_position[turtle_index]) # Adds the turtle to the List of turtles all_turtles.append(new_turtle) # When the user places is bet, the race can begin if user_bet: is_race_on = True # THe race goes on while no turtle has finished while is_race_on: # Goes through all the turtles for turtle in all_turtles: # Tests whether the turtle has finished if turtle.xcor() > 230: # The turtle has finished # The race is off is_race_on = False # Retrieves the color of the winning turtle winning_color = turtle.pencolor() # Compares the color of the winning turtle and the color bet by the user if winning_color == user_bet: # The user picked the winner turtle print(f"You've won! The {winning_color} turtle is the winner!") else: # The user picked one of the loser turtle print(f"You've lost! The {winning_color} turtle is the winner!") # Makes the turtle go forward by a random distance between 1 and 10 paces turtle.forward(random.randint(0, 10)) # Sets the screen to exit when the user click screen.exitonclick()
true
95534160beac1c54bfcf03d0b9894847b998ab08
Jean-Bi/100DaysOfCodePython
/Day 26/day_26/main.py
917
4.15625
4
numbers = [1, 2, 3] new_numbers = [n+1 for n in numbers] print(new_numbers) name = "Jean-Baptiste" new_list = [letter for letter in name] print(new_list) new_range = [n*2 for n in range(1, 5)] print(new_range) names = ["Alex", "Beth", "Caroline", "Dave", "Eleanor", "Freddie"] short_names = [name for name in names if len(name) < 5] long_names = [name.upper() for name in names if len(name) > 5] print(short_names) print(long_names) import random student_score = {name: random.randint(0, 100) for name in names} print(student_score) passed_students = {name: score for (name, score) in student_score.items() if score > 50} print(passed_students) import pandas student_dict = { "student": ["Angela", "James", "Lily"], "score": [56,76, 98] } student_data_frame = pandas.DataFrame(student_dict) print(student_data_frame) for (index, row) in student_data_frame.iterrows(): print(row)
false
f039d916710391010395015f792abbd8865339cf
Jean-Bi/100DaysOfCodePython
/Day 8/day-8-2-exercise/main.py
824
4.28125
4
#Write your code below this line 👇 #Defines the function that checks if a number is a prime one def prime_checker(number): #Inititalizes the variable storing the result prime = True #Goes thourgh all the number from 2 to the tested number - 1 for i in range(2, number): #Tests if the tested number is divisible by the current number if number % i == 0: #As the tested number is divisible by the current number, it's not a prime number prime = False #Prints whether the number is prime or not depending of the value of the variable prime if prime == True: print("It's a prime number.") else: print("It's not a prime number.") #Write your code above this line 👆 #Do NOT change any of the code below👇 n = int(input("Check this number: ")) prime_checker(number=n)
true
2c2537dd12749dd35b9b1206937664297a1ec67b
Jean-Bi/100DaysOfCodePython
/Day 3/day-3-5-exercise/main.py
1,163
4.1875
4
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 #Assembles both names and lowers the case combined_names = (name1 + name2).lower() #Counts the number of times the letters in the word TRUE occurs true = combined_names.count("t") + combined_names.count("r") + combined_names.count("u") + combined_names.count("e") #Counts the number of times the letters in the word LOVE occurs love = combined_names.count("l") + combined_names.count("o") + combined_names.count("v") + combined_names.count("e") #Computes the score appending both parts score = int(str(true)+str(love)) #Test the score if score < 10 or score > 90: #The score is either less than 10 or more than 90 print(f"Your score is {score}, you go together like coke and mentos.") elif score >= 40 and score <= 50: #The score is between 40 and 50 print(f"Your score is {score}, you are alright together.") else: #The score is either between 10 and 39 or between 51 and 90 print(f"Your score is {score}.")
true
dcc0b43babe3bf87a5d06c47a45eeab20075b81d
Jean-Bi/100DaysOfCodePython
/Day 2/day-2-1-exercise/main.py
445
4.1875
4
# 🚨 Don't change the code below 👇 two_digit_number = input("Type a two digit number: ") # 🚨 Don't change the code above 👆 #################################### #Write your code below this line 👇 #Retrieves both digits of the number and casts them as integers first_digit = int(two_digit_number[0]) second_digit = int(two_digit_number[1]) #Adds up both digits result = first_digit + second_digit #Prints the result print(result)
true
6fe4952fc88325495138b2a6a21f09dbdbf6dab2
Jean-Bi/100DaysOfCodePython
/Day 2/day_2.py
1,910
4.4375
4
###17. Python Primitive Data Types### ##String --> literals "Hello" #Using brackets allows to choose a particular character print("Hello"[0]) #Using + sign with strings concatenates them print("123" + "345") ##Integer --> whole numbers 56283 #Using + sign with integers sums them print(123 + 345) #Underscores can be used with large numbers to make them more readable 123_456_789 ##Float --> decimal numbers 3.14159 #Boolean --> True/False are the only values True False ###19. Type Error, Type Checking and Type Conversion #TypeError #len(4837) #TypeError num_char = len(input("What is your name?")) #print("Your name has " + num_char + " characters.") #type() function returns the type of the data input print(type(num_char)) #str() function converts the data input to a string new_num_char = str(num_char) #Now it works as the variable new_num_char is a string print("Your name has " + new_num_char + " characters.") #float() function converts the data input to a float a = float(123) print(type(a)) ###20. Mathematical Operations in Python### #Addition 3 + 5 #Substraction 7 - 4 #Multiplication 3 * 2 #Division -> always returns a float 6 / 3 #Power 2 ** 2 ##PEMDAS #Parenthesis #Exposant #Multiplication, Division #Addition, Substraction print(3 * 3 + 3 / 3 - 3) #Challenge : How to get 6 from the previous operation ? print(3 * (3 + 3) / 3 - 3) ###22. Number Manipulation and F Strings in Python### #round() function rounds the number input print(round(8 / 3)) #round() function can round to any precision specified as the second parameter print(round(8 / 3, 2)) #// returns the result of the division as an integer, flooring the float result print(8 // 3) result = 4 / 2 #Equals result = result / 2 result /= 2 print(result) score = 0 height = 1.8 isWinning = True #f-String print(f"your score is {score}, your height is {height}, your are winning is {isWinning}")
true
e4de1fa74dc0229277de2823c581f4cb8e253821
Jean-Bi/100DaysOfCodePython
/Day 20-21/snake_game/scoreboard.py
1,498
4.4375
4
# Imports the Turtle class from the turtle module from turtle import Turtle class Scoreboard(Turtle): """Creates a scoreboard that keeps track of the score and tells the user the game is over.""" def __init__(self): super().__init__() # Initializes the score to 0 self.score = 0 # Sets the color of the text to white self.color("white") # Hides the default arrow self.hideturtle() # Lifts up the pen to not leave a trail self.penup() # Sets the position of the scoreboard to the top of the screen self.goto(0, 250) # Writes the scoreboard self.write(f"Score: {self.score}", align="center", font=("Arial", 24, "normal")) def update_scoreboard(self): """Clears the scoreboard and rewrites it.""" # Clears the scoreboard self.clear() # Writes the scoreboard self.write(f"Score: {self.score}", align="center", font=("Arial", 24, "normal")) def game_over(self): """Displays the game over message.""" # Sets the position of the message to the center of the screen self.goto(0, 0) # Writes the game over message self.write("GAME OVER", align="center", font=("Arial", 24, "normal")) def increment_score(self): """Increments the user's score by 1.""" # Increments the score by 1 self.score += 1 # Updates the scoreboard self.update_scoreboard()
true
9727323672c8815dad034c3db85c9f58bafd34a3
Jean-Bi/100DaysOfCodePython
/Day 10/day_10.py
1,048
4.3125
4
###97. Functions with Outputs### #Defining a function that returns a result using the return keyword -> the return keyword ends a function def format_name(f_name, l_name): formatted_f_name = f_name.title() formatted_l_name = l_name.title() #Returning a formatted string return f"{formatted_f_name} {formatted_l_name}" #Prints the result returned by the function format_name print(format_name("JeAn-baptIstE", "piNEt")) ###98. Multiple return values### def format_name(f_name, l_name): """Take a first and last name and format it to return the title case version of the name""" #Using an early return if inputs aren't valid if f_name == "" or l_name == "": return "You didn't provide valid inputs." formatted_f_name = f_name.title() formatted_l_name = l_name.title() #Returning a formatted string when inputs are valid return f"{formatted_f_name} {formatted_l_name}" #Prints the result returned by the function format_name print(format_name(input("What is your first name? "), input("What is your last name? ")))
true
1bb02d7272b0e119ad34e7d22af64f31bd7ddd9d
nmessa/Dover-Girls-Coding-2018_2019
/Birthday Pi/birthday1.py
742
4.25
4
## Finding your birthday in Pi ## Author: nmessa ## This program will find the location of a birthday in the first ## million/billion digits of Pi filename = 'pi_million_digits.txt' #filename = 'pi-billion.txt' with open(filename) as file_object: pi_string = file_object.read() birthday = input("Enter your birthday, in the form mmddyy: ") if birthday in pi_string: index = pi_string.find(birthday) print("Your birthday appears in the first million digits of pi!") print ('At location', index) else: print("Your birthday does not appear in the first million digits of pi.") ## Output ## Enter your birthday, in the form mmddyy: 090852 ## Your birthday appears in the first billion digits of pi! ## At location 1222420
true
096db6176b0a462999760982dd953246d429fa40
jiez1812/Python_Crash_Course
/CH4_WORKING_WITH_LISTS/numbers.py
219
4.375
4
# range() function to generate a series of numbers. # only print 1 to 4 in range(1, 5) for value in range(1,5): print(value) print() # Use range() to Make a List of Numbers numbers = list(range(1,6)) print(numbers)
true
f4a877b58fc3ff33a142cb74add85df9ffd0e02a
jiez1812/Python_Crash_Course
/CH7_User_Input_And_While_Loops/7-3_Multiple_of_Ten.py
247
4.1875
4
prompt = "Please enter a number to check whether it is a multiple of 10." prompt += "\nInput: " num = input(prompt) num = int(num) if num % 10 == 0: print("The number is a multiple of 10.") else: print("The numbe is not multiple of 10.")
true
4ca6b0bc4642a7ab348efc62a808a3d40b638435
jiez1812/Python_Crash_Course
/CH4_WORKING_WITH_LISTS/magicians.py
398
4.40625
4
#print("For every magician in the list of magicians, print the magician's name:") # Use for loop to print each name of magicians list magicians = ["alice", "david", "carolina"] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() +".\n") print("Thank you, everyone. That was a great magic show!")
true
b5018be7b104e0d40235f15a449454415179a74c
hyltonc4469/CTI-110
/M6Tutorial_HW_Lab_Hylton/M6LAB_NestedLoop_Hylton2.py
891
4.15625
4
#CTI-110 #M6LAB-Nested Loop #Marie Hylton #27 November 2017 def main(): import turtle play=turtle.Screen() play.title("My Nested Loop Snowflake") jesse=turtle.Turtle() play.bgcolor("skyblue") jesse.color("blue") jesse.speed(10) #User Input: numSides=int(input("How many sides in the polygon?")) #Initialize Variables angle=0 angle=360/numSides n=0 n=(numSides*2) distance=100 jesse.left(180) for x in range(numSides): for i in range(numSides): jesse.forward(95) jesse.right(angle) jesse.forward(95) jesse.left(angle) jesse.forward(35) for i in range(n): jesse.forward(30) jesse.right(angle) jesse.forward(distance) jesse.right(angle) jesse.forward(25) play.mainloop() main()
false
440231b38e1dd89aca5d64ddb9075749da2cd432
hyltonc4469/CTI-110
/M5HW_LAB_Hylton/M5HW1_AgeClassifier_Hylton.py
892
4.53125
5
#CTI-110 #M5HW1-Age Classifier #Marie Hylton #22 November 2017 # #User inputs age of a given person. #Determine appropriate age classification. #Base age classification on guidelines: #If age<=1 #Display "He/She is an infant." #If age 2:12 #Display "He/She is a child." #If age 13:19 #Display "He/She is a teenager." #If age>=20 #Display "He/She is an adult." def main(): age=0 #Ask the user to enter the person's age. while 1==1: age=float(input('Enter the age of the person: ')) #Determine the age classification of the person. if age<=1.0: print("He/She is an infant.") elif 1.0<age<13.0: print("He/She is a child.") elif 13.0<=age<20.0: print("He/She is a teenager.") else: print("He/She is an adult.") main()
true
311a045c21a28713cf4a8c028f73c538298ff27d
hyltonc4469/CTI-110
/M6Tutorial_HW_Lab_Hylton/M6T2_BugCollector_Hylton.py
667
4.34375
4
#CTI-110 #M6T2-Bug Collector #Marie Hylton #29 November 2017 # #This program will tally the number of bugs collected for 7 days: #Initialize the accumulator #Set accumulator to 0. #Total=0 #For each of 7 days: #Input the number of bugs collected for a day #Add bugs collected to the running total. #Display the total. def main(): total=0 for x in ['Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']: print('Enter the bugs collected on', x,':') bugs=int(input()) total=total+bugs print("You collected a total of", total, "bugs.") main()
true
6b43dd239312deff09dc4e5995dcb75be0689c78
guicarvalho/Python-Fundamental-Tempo-Real-Eventos
/files_with.py
1,401
4.125
4
# coding: utf-8 """ Esse arquivo demonstra como lidar com exececoes para abrir arquivos, fazer o uso do comando with. São mostrados alguns comandos que usamos geralmente. Podemos iterar os arquivos texto. """ try: with open('teste.txt', 'a') as file: print u'Arquivo aberto' print u'Arquivo fechado' except IOError: print 'Erro ao abrir arquivo.' meu_texto = 'Python assim como C++ e Smaltalk possui a tanto herança simples \ quando herança múltipla. \nNa herança simples, a classe extende de uma única \ super classe herdando todas as suas caracteristicas.\nDizemos que a classe \ filha é a classe mais especifica e a classe pai ou super classe é a classe \ mais genérica.\n' try: with open('teste.txt', 'w') as file: file.writelines(meu_texto) # escrever um objeto iterável. print u'Escrita encerrada.' with open('teste.txt', 'r') as file: for line in file.readlines(): print line print '-'*100 # outro jeito para ler um única linhas de cada vez with open('teste.txt', 'r') as file: try: line = file.readline() while line: print line line = file.readline() except (IOError, Exception) as e: print 'Erro ao iterar file: ERRO: %s' % e print '-'*100 # ler a terceira linha do with open('teste.txt', 'r') as file: file.seek(18,0) print file.readline() except Exception as e: print u'Erro ao abrir arquivo. ERRO: %s' % e.message
false
67e0918ee5b60efcff731fc4b11afef6f1bcd2f9
abbymk/comp110-21ss1-workspace
/exercises/ex02/vaccine_calc.py
1,930
4.25
4
"""A vaccination calculator.""" __author__ = "730230918" # The datetime data type is imported from the datetime library. # A datetime object models a specific date and time. # # Official Documentation: https://docs.python.org/3/library/datetime.html#datetime-objects from datetime import datetime # The timedelta data type is imported from the timedelta library. # A timedelta object models a "time span", such as 1 day or 1 hour and 3 minutes. # Subtracting two datetime objects will result in the timedelta between them. # Adding a datetime and a timedelta will result in the datetime offset by the timedelta. # # Official Documentation: https://docs.python.org/3/library/datetime.html#datetime.timedelta from datetime import timedelta today: datetime = datetime.today() fortnight: timedelta = timedelta(7 + 7) mini_month: timedelta = timedelta(24 + 1) future: datetime = today + mini_month over_a_year: timedelta = timedelta(374 + 1) future_1: datetime = today + over_a_year future_2: datetime = today + fortnight # Begin your solution here... people_pop: str = input(" Population: ") people_pop_int: int = int(people_pop) dose_administered: str = input(" Doses administered: ") dose_administered_int: int = int(dose_administered) dose_per_day: str = input(" Doses per day: ") dose_per_day_int: int = int(dose_per_day) target_percent: str = input(" Target percent vaccinated: ") target_percent_int: int = int(target_percent) target_percent_float: float = float(target_percent_int) target_percent_int_1: int = round(target_percent_float) print("We will reach " + target_percent + "% vaccination in 25 days, which falls on " + future.strftime("%B %d, %Y") + ". ") print("We will reach " + target_percent + "% vaccination in 375 days, which falls on " + future_1.strftime("%B %d, %Y") + ". ") print("We will reach " + target_percent + "% vaccination in 14 days, which falls on " + future_2.strftime("%B %d, %Y") + ". ")
true
d27e7b2fd2dbeb50c8c57921e0f46298e2190ed4
bialx/miscalleneous
/snippet.py
1,356
4.40625
4
""" This snippet can be used to transpose a 2D array. """ array = [['a', 'b'], ['c', 'd'], ['e', 'f']] transposed = zip(*array) print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')] """ get size of an object """ import sys variable = 30 print(sys.getsizeof(variable)) # 24 """ This method returns the length of a string in bytes.""" def byte_size(string): return(len(string.encode('utf-8'))) byte_size('😀') # 4 byte_size('Hello World') # 11 """ This method removes falsy values (False, None, 0 and “”) from a list by using filter(). """ def compact(lst): return list(filter(None, lst)) compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] """ merge dict and create dict from lists """ def merge_dictionaries(a, b): return {**a, **b} a = { 'x': 1, 'y': 2} b = { 'y': 3, 'z': 4} print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4} def to_dictionary(keys, values): return dict(zip(keys, values)) keys = ["a", "b", "c"] values = [2, 3, 4] print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3} """ **KWARGS """ dictionary = {"a": 1, "b": 2} def someFunction(a, b): print(a + b) return # these do the same thing: someFunction(**dictionary) someFunction(a=1, b=2) """ METHOD """ #title() -> captilize first letter #shuffle(list) -> randomize list #a, b = b, a -> swap
true
6921663c80fa5fec8029e3696ecc32a151a7f1e4
jordan78906/CSCI-161_projects
/HernandezAlmache_Jordan_4.py
2,299
4.3125
4
#Jordan Hernandez-Alamche #CSci 161 L03 #Assignment 4 #1 Prompt the user to enter a sentence. Store the txt as a str. After user input, the prog. should output #the entered str before printing options in (Part2). # Ex.Please enter a sentence: # ... # You entered:The most certain way to succeed is to always try one more time! #2 Display a Menu, as shown in the example below. Each option is represenetd by a single char. # Ex. MENU # c - Number of non-whitespace characters. # w - Number of words. # r - Reverse the order of the words. # q - Quit. # Choose an option: #if an invalid char is entered, continue to prompt for a valid choise. Continue to display menu options #until the user enters q to Quit. #3 Implement a function to count and return the number of chars in the str, exclude all whitespace. # Ex. Number of non-shitespace characters:{} #4 Implement a function to return the number of words in the str # Ex. Number of non-shitespace characters:{} #5 Implement a function to reverse each word of the entered sentence to display the sentence in reverse. # Ex. Output:time! more one try always to is succeed to way certain most The def white_space(main_sentence): count = 0 for i in main_sentence: if(i.isalnum()): count += 1 return count def num_words(main_sentence): words = len(main_sentence.split(' ')) return words def reverse_order(main_sentence): words = main_sentence.split(' ') rev_words = words[::-1] new_sentence = ' '.join(rev_words) print(new_sentence) return return new_sentence main_sentence = input('Please enter a sentence:') print('\nYou entered:', main_sentence) option = 0 while option != 'q': print('\nMENU\n' 'c - Number of non-whitespace characters.\n' 'w - Number of words.\n' 'r - Reverse the order of the words.\n' 'q - Quit.\n') option = input('\nChoose an option:') if option == 'c': count = white_space(main_sentence) print(count) elif option == 'w': words = num_words(main_sentence) print(words) elif option == 'r': reverse_order(main_sentence) elif option != 'q': print('Invalid character,try again.')
true
10d72ba8d617673842436b130400a5ad75585d31
jordan78906/CSCI-161_projects
/HernandezAlmache_Jordan_2.py
1,862
4.375
4
#Jordan Hernandez-Alamche #CSci 161 L03 #Assignment 2 ''' ask user for numeric value a)the value entered is a whole number b)the value is, or is not, a mult. of 7 c)the value is pos/neg/zero d)the value is, or is not, within 2011-2021 e)the value is, or is not, within 1000's(4 digit's)(2 ways to accomplish) ''' val1 = float(input('Please enter a numerical value:')) if val1 % 1 == 0: print(val1,'is a whole number.') else: print(val1,'is not a whole number.') if val1 % 7 == 0: print(val1,'is a multiple of 7.') else: print(val1,'is not a multiple of 7.') if val1 > 0: print(val1,'is a positive number.') elif val1 < 0: print(val1,'is a negative number.') else: print(val1,'is zero.') if val1 >= 2011 and val1 <= 2021: print(val1,'is within 2011 to 2021 inclusively.') else: print(val1,'is NOT within 2011 to 2021 inclusively.') if val1 >= 1000: print(val1,'is within the 1000\'s.') else: print(val1,'is NOT within the 1000\'s.') ''' ask for 2nd value. f)which of the 2 is smallest? or = g)val2 is, or is not a mult of val1 h)val1 is, or is not a mult of val2 ''' val2 = float(input('Enter a second numerical value:')) if val1 > val2: print('The second value ({1}) is smaller than the first value({0}).'.format(val1, val2)) elif val1 < val2: print('The first value ({0}) is smaller than the second value({1}).'.format(val1, val2)) else: print('The two values are equal.') if val2 % val1 == 0: print('The second value ({1}) is a multiple of the fisrt value({0}).'.format(val1, val2)) else: print('The second value ({1}) is NOT a multiple of the fisrt value({0}).'.format(val1, val2)) if val1 % val2 == 0: print('The first value ({0}) is a multiple of the second value({1}).'.format(val1, val2)) else: print('The first value ({0}) is NOT a multiple of the second value({1}).'.format(val1, val2))
false
e3c76cc1c996a598905f3beaef6b19623b283bf0
RenatoGFerreira/estudos-de-python
/Desktop/Estudos_Python/exercícios/ex039.py
761
4.15625
4
''' Faça um program que leia o ano de nascimento de um jovem e informe, de acordo com sua idade: - Se ele ainda vai se alistar ao serviço militar. - Se é a hora de se alistar. - Se já passou do tempo do alistamento. Seu programa tambem deverá mostrar o tempo que falta ou passou do prazo. ''' from datetime import date ano_atual = date.today().year print(ano_atual) ano_nascimento = int(input('Qual o seu ano de nascimento? ')) if ano_atual - ano_nascimento < 18: print(f'Faltam {18 - (ano_atual - ano_nascimento)} anos para o seu alistamento.') elif ano_atual - ano_nascimento > 18: print(f'Já se passaram {(ano_atual - ano_nascimento) - 18} anos do seu alistamento.') else: print('Com 18 anos está no ano de alistamento.')
false
4f7bff4d3234ef45e7c321633122cdd3214af763
RenatoGFerreira/estudos-de-python
/Desktop/Estudos_Python/exercícios/ex005.py
211
4.15625
4
#Faca um programa que leia um número inteiro e mostre na tela seu sucessor e seu antecessor num = int(input('Digite um número: ')) print(f'O antecessor do número {num} é {num-1} e seu sucessor é {num+1}')
false
12a40ba4d0c30fbe958ec2a8e9f6ab617b7095a8
RenatoGFerreira/estudos-de-python
/Desktop/Estudos_Python/exercícios/ex017.py
546
4.1875
4
''' Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e mostre o comprimento da hipotenusa. ''' import math cateto_oposto = float(input('Entre com o comprimento do Cateto Oposto: ')) cateto_adjacente = float(input('Entre com o comprimento do Cateto Adjacente: ')) hipotenusa = math.sqrt(cateto_oposto**2 + cateto_adjacente**2) print(f'Para o cateto oposto de {cateto_oposto} e cateto adjacente de {cateto_adjacente} temos o comprimento da hipotenusa de {hipotenusa:.2f}')
false
e8b070ddbaf5b28ac680b590c89944041e06d353
Nightfury874/DSA
/CountingFreq.py
1,377
4.375
4
# Python 3 program to count frequencies # of array items def countFreq(arr, n): # Mark all array elements as not visited visited = [False for i in range(n)] # Traverse through array elements # and count frequencies for i in range(n): # Skip this element if already # processed if (visited[i] == True): continue # Count frequency count = 1 for j in range(i + 1, n, 1): if (arr[i] == arr[j]): visited[j] = True count += 1 print(arr[i], count) # Driver Code if __name__ == '__main__': arr = [10, 20, 20, 10, 10, 20, 5, 20] n = len(arr) countFreq(arr, n) # Time Complexity : O(n2) # Auxiliary Space : O(n) # Python3 program to count frequencies # of array items def countFreq(arr, n): mp = dict() # Traverse through array elements # and count frequencies for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Traverse through map and print # frequencies for x in mp: print(x, " ", mp[x]) # Driver code arr = [10, 20, 20, 10, 10, 20, 5, 20 ] n = len(arr) countFreq(arr, n) #Time Complexity O(n)
true
3835db48be0cb8795ccd5e71e9b6bf70c2fd0696
bobrovka/train
/coursera/python/003_string_task/main.py
525
4.375
4
""" Вводится строка. Удалить из нее все пробелы. После этого определить, является ли она палиндромом (перевертышем), т.е. одинаково пишется как с начала, так и с конца. """ input_string = input("Введите строку: ") string = input_string.replace(' ', '') is_palindrome = False if string == string[::-1]: is_palindrome = True print(f"Это полиндром: {is_palindrome}")
false
7e3d8babef73bb89c8d324aa8a5a11e24fb4459b
pratapkaronde/Jumbotron
/jumbotron.py
2,284
4.4375
4
""" This program displays the MESSAGE text as a jumbotron screen using PyGame """ import pygame from pygame.locals import KEYDOWN, K_ESCAPE from bitmap import font_bitmap, CHARACTER_WIDTH, CHARACTER_HEIGHT MESSAGE = "Hello, World! " LED_RADIUS = 5 LED_DIAMETER = LED_RADIUS * 2 SCREEN_WIDTH = 1200 SCREEN_HEIGHT = LED_DIAMETER * CHARACTER_HEIGHT # 600 COLOR_BACKGROUND = (0, 0, 128) COLOR_LED_ON = (200, 200, 0) COLOR_LED_OFF = (150, 50, 0) def display_message(message_txt, start_x=0): """ Display the actual message text starting from the COLUMN start_x """ character_number = 0 x_increment = LED_DIAMETER + 2 x_start_character = LED_RADIUS x_position = x_start_character for letter in message_txt: ascii_code = ord(letter) for y_loop in range(CHARACTER_HEIGHT): mask = int(128) byte = font_bitmap[(ascii_code - 32)][CHARACTER_HEIGHT - y_loop - 1] x_position = x_start_character for _ in range(start_x, CHARACTER_WIDTH): y_position = ((y_loop * LED_DIAMETER) + 2) + LED_RADIUS led_color = COLOR_LED_OFF if int(byte) & int(mask): led_color = COLOR_LED_ON pygame.draw.circle(screen, led_color, (x_position, y_position), LED_RADIUS) x_position = x_position + x_increment mask = mask / 2 x_start_character = x_position start_x = 0 character_number = character_number + 1 if __name__ == "__main__": pygame.init() infoObject = pygame.display.Info() print(infoObject) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) RUNNING = True screen.fill(COLOR_BACKGROUND) timer = pygame.time.Clock() COLUMN = 0 while RUNNING: if COLUMN >= CHARACTER_WIDTH: COLUMN = 0 MESSAGE = MESSAGE[1:] + MESSAGE[0] display_message(MESSAGE, COLUMN) pygame.display.update() for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: RUNNING = False if event.type == pygame.QUIT: RUNNING = False COLUMN = COLUMN + 1 timer.tick(15)
true
f0868221566e21b4dedb67dc9add4f6eda9ef862
johnnyjw/oo_python
/OO_Python_1.py
1,106
4.15625
4
myint = 5 mystr = 'hello' print type(myint) print type(mystr) dir(myint) ## test concepts of methods from 'primary' objects var = 'hello, world!' print type(var) print var.upper() ## class with nothing in it!! class MyClass(object): pass this_obj = MyClass() print this_obj that_obj = MyClass() print that_obj ### redoing the class including a variable class MyClass(object): var = 10 this_obj = MyClass() that_obj = MyClass() print this_obj.var print that_obj.var #### New class class Joe(object): greeting = 'hello, Joe' thisjoe = Joe() print thisjoe.greeting #### redefined, but with a method! class Joe(object): def callme(self): print('calling "callme" method with instance: ') print self thisjoe = Joe() thisjoe.callme() print thisjoe ## Another Class class MyClass(object): def dothis(self): print('doing this') myinst = MyClass() myinst.dothis() ## Revise this class! import random class MyClass(object): def dothis(self): self.rand_val = random.randint(1,10) myinst = MyClass() myinst.dothis() print(myinst.rand_val)
true
d5d15af3c4350d41e51fca036f409a7efe8d02ed
CTTruong/09-21-Assignments
/CBC/Assignment-1.py
443
4.21875
4
first_number = int(input("First number: ")) operator = input("operator: ") second_number = int(input("Second number: ")) def calculator(first_number,operation,second_number): if operator == "+": return first_number + second_number elif operator == "-": return first_number - second_number elif operator == "*": return first_number * second_number else: return number1/number2 print(sum)
false
0e8a0630fb01767d6a64df08897965d362e38cbb
geyungjen/jentekllc
/algorithm/quick_sort.py
850
4.28125
4
#Quick Sort Implementation, in place sort #George Jen, Jen Tek LLC def partition(arr,low,high): #pivot (Element to be placed at right position) pivot = arr[high] i=low-1 for j in range(low,high): # If current element is smaller than the pivot if arr[j] < pivot: i+=1; # increment index of smaller element #swap arr[i] and arr[j] arr[i],arr[j]=arr[j],arr[i] arr[i+1],arr[high]=arr[high],arr[i+1] return i+1 def quickSort(arr,low,high): if low<high: pi = partition(arr, low, high) quickSort(arr,low,pi-1) quickSort(arr,pi+1,high) #Driver code: if __name__=='__main__': arr=[10,2,5,6,4] print("Before quick sort {}".format(arr)) quickSort(arr,0,len(arr)-1) print("After quick sort {}".format(arr))
true
64bd35619e828e9fbe47054372081a27a8c63a97
MCaldwell-42/lightning_exercises
/calculator.py
707
4.4375
4
# 1. write a function called add that accepts two arguments and returns their sum # 1. write a function called subtract that accepts two arguments and returns the difference # 1. write a function called calculate that accepts a function as an argument. In calculate's body, it should execute that function and pass it the numbers 3 and 5 # 1. print an execution of calculate and pass it a reference to add # 1. print an execution of calculate and pass it a reference to subtract def add(x, y): ans = x + y print(ans) return ans def subtract(x, y): ans = x - y print(ans) return ans def calculate(funky): ans = funky(3, 5) return ans calculate(add) calculate(subtract)
true
b229828e835703368dc9c42438fa5c6695a35b24
Huiting120/afs505_u1
/Assignments/Assignment4/ex36.py
2,443
4.28125
4
from sys import exit def rabbit_hole(): print(""" You've entered the rabbit hole, what do you want to do next? 1. kill all the rabbits 2. look around 3. exit 4. I don't know. """) choice = input("> ") if "kill" in choice: print("Good job, you found food! Let's go home with the rabbits.") exit(0) elif "look" in choice: dead("The rabbits saw you and killed you.") elif "exit" in choice: start() elif "don't know" in choice: dead("Indecisive Homo sapiens die.") else: dead("Didn't you read my question?") def pig_house(): print(""" You've entered the pig village and see all the pigs are sleeping. The pig king is sleeping in front of a door labeled: treasure. What do you do? 1. poke the pig king. 2. look around. 3. exit """) pig_king_moved = False while True: choice = input("> ") if choice == "poke the pig king" and not pig_king_moved: print("Do you want to enter the treasure room? y/n") desicion = input("> ") if desicion == "y": dead("It's a lie, there is no treasure, but a monster.") elif desicion == "n": print("You are a cautious person, good job. what do you do next? choose from the same options like last time.") pig_king_moved = True else: dead("Didn't you read my question?") elif choice == "poke the pig king" and pig_king_moved: dead("Why do you keep poking the pig king, now he is annoyed.") elif choice == "look around" and not pig_king_moved: print("You found a secret portal. Enter or not? y/n") desicion = input("> ") if desicion == "y": cat_cafe() elif desicion == "n": print("Well... OK. What's your next move then?") pig_king_moved = True else: dead("I said! Didn't you read my question?") elif choice == "look around" and pig_king_moved: dead("You should have ran away since your movement has waken up the pig king and he is annoyed.") elif choice == "exit": start() else: dead("I said! Didn't you read my question?") def cat_cafe(): print("This is the cat cafe! Best choice of your life! Enjoy!") exit(0) def dead(why): print(why, "You suck!") exit(0) def start(): print("You entered a cave.") print("There is a road to your left and your right.") print("Which way do you go?") choice = input("> ") if choice == "left": rabbit_hole() elif choice == "right": pig_house() else: dead("You stumble around the cave until you starve.") start()
true
67f94f0d0c3cefa6af53d32b85baef08828d2ab9
Huiting120/afs505_u1
/Assignments/Assignment4/ex33_rewrite1.py
232
4.15625
4
def add_number(max_number): i = 0 numbers = [] while i < max_number: numbers.append(i) i += 1 for num in numbers: print(num) print("Please define your maximum number:") my_number = int(input()) add_number(my_number)
true
5bcfef7cc335430a6d431d7d36e09964017855d3
mutanara/learningpython
/Daily learning/exercise/inheritance.py
769
4.125
4
class Animal(): noise = "Grunt" size = "Large" color = "brown" hair = "covers body " def get_color(self): return (self.color) def get_noise(self): return (self.noise) obj = Animal() obj.size = "small" obj.color = "black" obj.hair = "hairless" print(obj.size) print(obj.get_color()) class Dog(Animal): #this class Dog inherited features of parent class Animal, but it can also have it's own attributes. name = "Jon" size = "small" # this is called "override" as this classs is having the same parameters with the parent class but with different variables. hair = "hairless" instance = Dog() instance.color = "white" instance.name = "Jon Snow" print(Dog.hair) print(Dog.size) print(Dog.name) print(Dog.color)
true
213619683446a1379c75748ab04296b2831583f3
mutanara/learningpython
/Daily learning/exercise/myfunction.py
981
4.21875
4
# A function which breaks one big list of different items into other different list depending on the variable type, and sort each respective list. # Just add items inside the anylist below then see the magic happening. list_a = [] list_a = ["nara","Gemma","Mahame","Vicky", 1995, 1991,1989,1985,19.95,19.91,19.89,19.95] def part_sort(anymixedlist): str_list = [] int_list = [] float_list = [] for x in list_a: if isinstance(x, int): int_list.append(x) int_list.sort(reverse = False) for x in list_a: if isinstance(x, float): float_list.append(x) float_list.sort(reverse = False) for x in list_a: if isinstance(x, str): str_list.append(x) str_list.sort(key=str.lower) return str_list, float_list, int_list print(part_sort(list_a)) # Zipping function: # x = [1, 2, 3] # y = [4, 5, 6] # zip(x, y) # for i in zip(x, y): # print(i)
true
81bd16358e012c7f2295940d95dba14db15d7d86
CozySnake/Complete-Python-3-Bootcamp-Answers
/Section 3 Methods and Functions (Homework).py
984
4.34375
4
import string # Here I check if this text is a pangram. def ispangram(str1, alphabet=string.ascii_lowercase): str1 = str1.replace(' ', '') print(len(str1)) for letter in alphabet: if letter in str1.lower(): alphabet = alphabet.replace(letter, '') print(alphabet) if len(alphabet) == 0: print('The string is a pangram.') else: print('The string is not a pangram.') string.ascii_lowercase ispangram("The quick brown fox jumps over he lazy dog") def up_low(s): d = {'upper': 0, 'lower': 0} for letter in s: if letter.isupper(): d['upper'] += 1 elif letter.islower(): d['lower'] += 1 else: pass print('Original String : ' + s) print(f'No. of Upper case characters : {d["upper"]}') print(f'No. of Lower case Characters : {d["lower"]}') print(d['upper'], d['lower']) s = 'Hello Mr. Rogers, how are you this fine Tuesday?' up_low(s)
true
033cc52e91b7d81093b2034b8af6fc00af8c01d5
deniskrumko/advent-of-code
/2021/day_01/main.py
732
4.15625
4
def count_measurement_increases(data: list): """Count measurement increases only.""" return sum(data[i] > data[i - 1] for i in range(1, len(data))) def count_sliding_window_measurement_increases(data: list, window: int = 3): """Count sliding window measurement increases only.""" window_sizes = [sum(data[i:window + i]) for i in range(len(data) - window + 1)] return count_measurement_increases(window_sizes) if __name__ == '__main__': with open('2021/day_01/input.txt', 'r') as f: input_data = [int(i) for i in f.readlines()] print(f'Your result (1): {count_measurement_increases(input_data)}') print(f'Your result (2): {count_sliding_window_measurement_increases(input_data)}')
false
b1d04c315263224909564248f70545ff65eebf70
NoahtheDeveloper/Learning-Python
/test-9.py
402
4.21875
4
#This prints PI and a Squared Number # Imported Module is listed below import math # What is PI x = math.pi # Prints PI print(x) print ("PI has now been printed now moving to the next module.") # This is a function saying math squared. The number inserted is squared. x = math.sqrt(64) # This Prints the squared number. print(x) print ("64 Squared has now been printed")
true
ede639881eb4c7e5914208eaed79328180c982b9
Vinishbhaskar/RTU-DigitalLibrary
/Python_Programs/BubbleSort.py
755
4.5
4
def bubbleSort(array): sizeOfArray = len(array) # Traverse through all array elements for i in range(sizeOfArray - 1): # range(n) also work but outer loop will repeat one time more than needed. # Last i elements are already in place for j in range(0, sizeOfArray - i - 1): # traverse the array from 0 to sizeOfArray-index-1 # Swap if the element found is greater # than the next element if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] # Driver code to test above print("Enter the Array:") arr = [int(x) for x in input().split()] bubbleSort(arr) print("Sorted array is:") for i in range(len(arr)): print("%d" % arr[i])
true
aadaa11b725c98748fafbabbad7de7162825658a
luscious-dev/Some-Python-Stuffs
/shapes.py
826
4.21875
4
proceed = True while proceed == True: print("1) Square \n2) Triangle") choice = int(input("Enter a number: ")) if choice == 1: print("Ooohoo (Land of Wano sound)...you have chosen a square\n") length = float(input("Enter the length of one of the sides of the square, I want to find the area: ")) print("The area of the square is: ",length**2) elif choice == 2: print("Duh..you chose a triangle\n") height = float(input("How high is the triangle? : ")) base = float(input("How wide is the base? : ")) print("The area of your triangle is: ", (1/2) * base * height) else: print("You've gotta learn to follow simple instructions B**CH") response = input('Would you like to try again? [Y/N]') proceed = False if response == 'N' else True
true
fe71b2aff54a17e299bb443d4907eebc71e07b09
KasidisGit/unittesting-KasidisGit
/listutil.py
906
4.21875
4
def unique(lst): """Return a list containing only the first occurence of each distint element in list. That is, all duplicates are omitted. Arguments: list: a list of elements (not modified) Returns: a new list containing only distinct elements from list Examples: >>> unique([5]) [5] >>> unique(["b","a","a","b","b","b","a","a"]) ["b","a"] >>> unique([]) [] """ new_lst = [] try: if isinstance(lst, list): for element in lst: if element not in new_lst: new_lst.append(element) return new_lst except TypeError: raise ValueError("The argument must be list.") else: raise ValueError("The argument must be list.") if __name__ == "__main__": """Run the doctests in all methods.""" import doctest doctest.testmod(verbose=True)
true
1e0f9a7fb064afaa97cc93ae428c29b69661334e
PeaseVad/script0003
/src/homeworks/student3/homework1.py
1,426
4.40625
4
# 1) Write a python program to convert a list of characters into a string def list_to_string (l): s='' for i in l: s += i return s # print (list_to_string(('P','r','i','v','e','t'))) # 2)Write a python program to flatten a nested list. # def flatten_nested_list(l): # new_list = [] # for i in range(0,len(l)): # if isinstance(l[i], (list, tuple)): # tmp_list =l[i] # for j in range(0, len(tmp_list)): # new_list.append(tmp_list[j]) # elif isinstance(l[i], dict): # tmp_list = l[i].values() # for t in range(0, len(tmp_list)): # new_list.append(tmp_list[t]) # else: # new_list.append(l[i]) # return new_list # # d = flatten_nested_list([1,2,3,(7,8,9),{7:'v'}]) # print (d) # 3) Write a python function to print a dictionary where the keys are numbers # between 1 and n (both included) and the values are square of keys. “n” is # passed as function parameter. def generate_dict(n): my_dict = {} for i in range(1,n+1): my_dict[i] =i**2 return my_dict print (generate_dict(10)) def generate_dict2(n): return {x:x**2 for x in range(1,n+1)} def flatten_list2(l, c=[]): for elem in l: if isinstance(elem, list): flatten_list2(elem, c) else: c.append(elem) return c if __name__ == '__main__': pass
false
323b90f8c2a110792b4c899e4b60ac87d024211f
mihaela-mcreynolds/Python
/Pythagorean triples
544
4.21875
4
#!/bin/python import math ''' Mihaela McReynolds 2.7 Using a series of for loops, find all Pythagorean triples consisting of positive integers less than or equal to 20 ''' # make a list to hold the sets of three numbers listThree = [] listAll = [] # simple way, not only primitives for a in range(1, 21): # avoid duplication by making sure b is larger than a; this way, they are ordered by As for b in range(a,21): for c in range(1,21): if a * a + b * b == c * c: listThree=[a, b, c] listAll.append(listThree) print listAll
true
afc43a217e9f709b3e00f714d7c26729253229f3
AlexeyMartynov91/Python
/lesson_3/homework_3_1.py
811
4.15625
4
''' Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. ''' def funcdelete(div1, div2): """Возвращает результат деления. Именованные параметры: div1 -- делимое div2 -- делитель """ try: result = div1 / div2 except ZeroDivisionError: return "Деление на ноль" except: return 'Ошибка в значениях' return result print(funcdelete(1, 10)) print(funcdelete(1, '0')) print(funcdelete(1, 0))
false
c49178ab64fc54f2299e25f755948cb42175b5ee
cifpfbmoll/practica-6-python-JaumeFullana
/Practica 6/Ejercicio6.py
900
4.28125
4
#Escribe un programa que pida primero dos números (máximo y mínimo) y que después te pida números intermedios. #Para terminar de escribir números, escribe un número que no esté comprendido entre los dos valores iniciales. #El programa termina escribiendo la lista de números. numero1=int(input("Escribe un número:")) numero2=int(input(f"Escribe un número mayor que {numero1}:")) while numero1 >= numero2: numero2=int(input(f"{numero2} no es mayor que {numero1}. Vuelve a probar:")) numeroint=int(input(f"Escribe un número entre {numero1} y {numero2}:")) lista = [numeroint] while numeroint>numero1 and numeroint<numero2: numeroint=int(input(f"Escribe un número entre {numero1} y {numero2}:")) lista += [numeroint] del lista[-1] print (f"Los números situados entre {numero1} y {numero2} que has escrito son:",end=" ") for i in lista: print (i,end=", ")
false
14fcb9cd1b625ab428fb620ea528719355857ffb
cifpfbmoll/practica-6-python-JaumeFullana
/Practica 6/Ejercicio14B.py
1,468
4.125
4
# Desarrolla un programa que tenga las siguientes características: # -Piensa en un problema que requiera para su resolución el uso de sentencias repetitivas. # -Dicho problema resuélvelo con bucles for y while. # -Justifica en el propio programa porque una opción es adecuada y la otra no. # -¿Crees que si medimos el tiempo de ejecución de ambas soluciones demostrará que efectivamente # una solución es más eficiente? Investiga para comprobarlo. #Escribe dos numeros enteros, uno menor y otro mayor, despues encuentra todos los divisores del # numero mayor que hay entre ellos (ellos mismos no deben estar incluidos): menor=int(input("Escribe un numero:")) mayor=int(input(f"Escribe un numero mayor que {menor}:")) inicial=menor lista=[] import time start_time = time.time() for i in range(menor+1,mayor): if mayor%i==0: lista += [i] print("--- %s seconds ---" % (time.time() - start_time)) print ("Los divisores de",mayor,"que se encuentran entre",menor,"y",mayor,"son:",lista) # Aqui la opcion mas adecuada, a mi parecer, es la del for, porque para hacer lo mismo necesita # un codigo mas corto y porque no se aprovecha la ventaja del while de poder terminar antes el bucle, # porque los dos necesitan probar con todas las opciones hasta el final. #Si, asi ha sido. Lo he medido con una funcion de python, que he dejado puesta para que pueda ser comprobado, # y el bucle for se resuelve casi el doble de rapido que el while.
false
38d8f1d90c7f2d7765252bec9ac2e9fa1a7d17e9
Geometary/First-17-Tests
/test03.py
474
4.125
4
print "If 'student A' walked 4 hours to finish 3 miles," print "If 'student B' walked 7 hours to finish 9 miles," print "What is speed of 'student A'?", 3/4.0, "mph" print "What is speed of 'student B'?", 9/7.0, "mph" print "Is 'student A' quicker than 'student B'?" print 3.0/4.0>9.0/7.0 #This step is used as a checking step. print "Okay then." #order "round (a)" can estimate number "a" into a similar number, according to # "4 then decrease and 5 then increase" rule.
true
daff5262888e7b6a58a07ada1c934a8d9397f646
Dnorton12/CS261
/stack_da.py
2,859
4.21875
4
# Course: CS261 - Data Structures # Student Name: Christopher VO # Assignment: hw 2 # Description: Has Stack class that has methods to add, remove, pop, top, push values #of a dynamic array. # Last revised: 10/12/2020 from dynamic_array import * class StackException(Exception): """ Custom exception to be used by Stack class DO NOT CHANGE THIS METHOD IN ANY WAY """ pass class Stack: def __init__(self): """ Init new stack based on Dynamic Array DO NOT CHANGE THIS METHOD IN ANY WAY """ self.da = DynamicArray() def __str__(self) -> str: """ Return content of stack in human-readable form DO NOT CHANGE THIS METHOD IN ANY WAY """ out = "STACK: " + str(self.da.length()) + " elements. [" out += ', '.join([str(self.da.get_at_index(_)) for _ in range(self.da.length())]) return out + ']' def is_empty(self) -> bool: """ Return True is the stack is empty, False otherwise DO NOT CHANGE THIS METHOD IN ANY WAY """ return self.da.is_empty() def size(self) -> int: """ Return number of elements currently in the stack DO NOT CHANGE THIS METHOD IN ANY WAY """ return self.da.length() def push(self, value: object) -> None: """ This function takes a value as a parameter and will add it to current array """ self.da.append(value) def pop(self) -> object: """ This function will return the last value of current array and remove it from current array. """ if self.size() == 0: raise StackException value = self.da.get_at_index(self.size() - 1) self.da.remove_at_index(self.size() - 1) return value def top(self) -> object: """ This function will return the value at the end of current array without removing it. """ if self.size() == 0: raise StackException return self.da.get_at_index(self.size() - 1) # BASIC TESTING if __name__ == "__main__": print("\n# push example 1") s = Stack() print(s) for value in [1, 2, 3, 4, 5]: s.push(value) print(s) print("\n# pop example 1") s = Stack() try: print(s.pop()) except Exception as e: print("Exception:", type(e)) for value in [1, 2, 3, 4, 5]: s.push(value) for i in range(6): try: print(s.pop()) except Exception as e: print("Exception:", type(e)) print("\n# top example 1") s = Stack() try: s.top() except Exception as e: print("No elements in stack", type(e)) s.push(10) s.push(20) print(s) print(s.top()) print(s.top()) print(s)
true
8410dfd7e4eca3bb4bb849294a232010f90e305e
crestel-ong/Unit3-05-Python-Months
/month.py
1,007
4.3125
4
#!/usr/bin/env python3 # Created by: Crestel Ong # Created on: Sept 2021 # This is the Month program def main(): # this function displays the month a number represents # input user_number = int(input("Enter the number of a month(ex: 3 for March): ")) # process and output if user_number == 1: print("January") elif user_number == 2: print("February") elif user_number == 3: print("March") elif user_number == 4: print("April") elif user_number == 5: print("May") elif user_number == 6: print("June") elif user_number == 7: print("July") elif user_number == 8: print("August") elif user_number == 9: print("September") elif user_number == 10: print("October") elif user_number == 11: print("November") elif user_number == 12: print("December") else: print("Invalid number") print("\nDone.") if __name__ == "__main__": main()
true
a282131d5915a14d3962db6b2b1c0bb547fc4975
enhaocui/programming_languages
/pa6/untitled.py
1,533
4.28125
4
from misc import Failure class Vector(object): def __init__(self, args): """ this is the ctor for the Vector class, it takes in takes in one arg and if the arg is a int or long it checks to make sure that the value is positive. if it is a list it uses that list as the values and length of the vector. It raises an error on other inputs""" if isinstance(args, int) or isinstance(args,long): if (args < 0): raise ValueError("Vector length cannot be negative") self.values = [0.0] * args self.len = args elif isinstance(args, list): self.values = list(args) self.len = len(args) else: raise TypeError("Please input a number or a list") def __repr__(self): """ repr is the string represention of the class, it returns Vector(contents of the list)""" return "Vector(" + repr(self.values) + ")" def __len__(self): """ len returns the length of the vector""" return len(self.values) def __iter__(self): """ iter returns an object that can iterate over the values of the vector. it uses yield to iterate""" for x in self.values: yield x def __add__(self, other): """ add is used to add the elements of a vector to a sequence to return another vector, zip is used to bind elemnents""" return Vector([x + y for x, y in zip(self.values, list(other))])
true
5ab90d514b84e0c96c0cbad0995a466bc8dd1342
CameronAlvarado/code-challenges
/valleys.py
1,109
4.40625
4
def countingValleys(n, s): # what happens in the situation when the string doesn't # have us reach sea level again? # keep a dict of elevation changes associated with { U: 1, D: -1 } # s is a string of Us and Ds # keep track of the height height = 0 # keep track of number of valleys valleys = 0 # have a variable that keeps track of the previous step # loop through the string s for step in s: # depending on whether we see a U or a D if step == 'U': # update the height counter accordingly height += 1 # if the height counter returns to 0 if height == 0: valleys += 1 else: height -= 1 # how do we know that we reached a height of 0 as a result of # climbing down from a hill vs climbing up from a valley? # keep track of the most recent step we took, so that we know if # we climbed up from a valley # increment our valleys counter return valleys x = countingValleys(8, "UDDDUDUU") print(x)
true
b84d1400fc3f31ad20ed8e642fd3e768afc1a6d0
b-1434/34B14-Lab-Assignment-
/L3-Converting matrix to sparse matrix.py
1,062
4.28125
4
# Python program to convert a matrix to sparse def displayMatrix(matrix): for row in matrix: for element in row: print(element, end=" ") print() def convertToSparseMatrix(matrix): sparseMatrix = [] for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] != 0: temp = [] temp.append(i) temp.append(j) temp.append(matrix[i][j]) sparseMatrix.append(temp) # displaying the sparse matrix print("\nSparse Matrix: ") displayMatrix(sparseMatrix) # initializing a normal matrix normalMatrix = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4], [5, 0, 0, 0]] # displaying the matrix displayMatrix(normalMatrix) # converting the matrix to sparse # displayMatrix convertToSparseMatrix(normalMatrix) Output:- 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 5 0 0 0 Sparse Matrix: 0 0 1 1 1 2 2 2 3 3 3 4 4 0 5
true
70d8a3c2d2d06a89e134b898ea0e7df7aafb9f20
b3yond/3python
/latinNumbers.py
2,150
4.25
4
#!/usr/bin/env python3 numbers = { 1000: "M", 999: "IM", 995: "VM", 990: "XM", 900: "CM", 500: "D", 499: "ID", 495: "VD", 490: "XD", 400: "CD", 100: "C", 99: "IC", 95: "VC", 90: "XC", 50: "L", 49: "IL", 45: "VL", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I" } latins = ['M', 'D', 'C', 'L', 'X', 'V', 'I'] letters = dict(M=1000, D=500, C=100, L=50, X=10, V=5, I=1) def l2a(): latin = -1 while latin == -1: latin = input("Which number do you want to be in arabic? ").upper() for c in latin: if c in latins: pass else: print("Wrong input. Try again!") latin = -1 break arabic = 0 new = [] for c in latin: new.append(letters[c]) for i in range(len(new)): try: if new[i] < new[i+1]: arabic -= new[i] else: arabic += new[i] except IndexError: arabic += new[i] print("The latin number " + latin + " is the arabic number " + str(arabic) + ".") def a2l(): arabic = -1 while arabic == -1: try: arabic = int(input("Which number do you want to be in latin? ")) except ValueError: print("Wrong input. Try again!") if arabic < 1: print("Input has to be positive.") arabic = -1 var = arabic new = [] for foo in sorted(numbers.keys(), reverse=True): while var >= foo: new.append(numbers[foo]) var -= foo print("The arabic number " + str(arabic) + " is equivalent to the latin number " + "".join(new) + ".") def choosemode(): choice = 0 while choice == 0: print("(1) latin to arabic\n(2) arabic to latin") choice = input("Which function do you want to use? (1/2) ") if choice == "1": l2a() elif choice == "2": a2l() else: print("Wrong input. Try again!") choice = 0 def main(): choosemode() main()
false
3e671794f974dfa8ee49bd8c3d4f1b6701e55efd
vanessa-santana/Exercicios-Estudo_Python
/ex073_TuplasComTimesDeFutebol.py
925
4.125
4
'''Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times. b) Os últimos 4 colocados. c) Times em ordem alfabética. d) Em que posição está o time da Chapecoense. ''' times=('Corinthians','Palmeiras','Santos','Gremio','Cruzeiro','Flamengo','Vasco','Chapecoense','Atletico','Botafogo', 'Atletico-PR','Bahia','Sao Paulo','Fluminense','Sport-Recife','EC Vitoria','Coritiba','Avai','Ponte Rasa','Atletico-GO') print('-='*15) print(f'Lista de Times: {times}') print('-='*15) #for t in times: # print(t) print(f'Os cincos primeiros são: {times[0:5]}') print('-='*15) print(f'Os quatros ultimos são: {times[-4:]}') print('-='*15) print(f'Times em ordem alfabetica são : {sorted(times)}') print('-='*15) print(f'O Chapecoense esta na {times.index("Chapecoense")+1}ª posição')
false
48652a8f5f669b60a4c84632846580ae60bda883
vanessa-santana/Exercicios-Estudo_Python
/ex058_JogoDaAdivinhacao.py
1,343
4.25
4
''' Melhore o jogo do DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. ''' from random import randint computador=randint(0,10) print(''' Sou seu computador... Acabei de pensar em um numero entre 0 e 10. Será que você consegue adivinhar qual foi?? ''') acertou=False tentativas=0 while not acertou: jogador = int(input('Qual é seu palpite? ')) tentativas+=1 if jogador == computador: acertou = True else: if jogador < computador: print('Mais...Tente novamente.') elif jogador > computador: print('Menos...Tente novamente.') print('Acertou com {} tentativas. Parabens'.format(tentativas)) ''' Outro modo palpite=int(input('Qual o seu palpite? ')) cont=0 while palpite != computador: if palpite != computador: if palpite < computador: print('Mais...Tente novamente.') palpite=int(input('Qual o seu palpite? ')) cont+=1 else: print('Menos...Tente novamente.') palpite=int(input('Qual o seu palpite? ')) cont+=1 print('Acertou com {} tentativas. Parabéns'.format(cont)) '''
false
8b185714dc1376d102b449212ede5ea6b5f4d874
szat/Blackjack
/game21/Deck.py
2,249
4.25
4
__author__ = "Adrian Szatmari" __copyright__ = "Copyright 2018" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Adrian Szatmari" __status__ = "Production" import random import math class Deck: """ This class implements a deck, with the main argument being the number of players. A single card is just an integer, representing the position in the array representing a deck. There needs to be one deck per 3 players. The important method here is drawCard(), that randomly picks a card from the remaining deck. """ def __init__(self, nb_players): #one deck per 3 players nb_decks = math.ceil(nb_players/3) a_deck = [4,4,4,4,4,4,4,4,4,4,4,4,4] #count the aces in position 0 self.nb_cards = nb_decks*13*4 self.cards = [x * nb_decks for x in a_deck] def drawCard(self): """ This function picks a card from the deck in a random order, then updates the deck. """ if(self.nb_cards< 1): return -1 else: #lay out all the cards, and pick one c = random.randrange(0,self.nb_cards) for index, x in enumerate(self.cards): c -= x if(c < 0): #shave of card types until you get to the right card equiv. class c = index break self.cards[c] -= 1 self.nb_cards -= 1 #a card is just an integer here, representing the position in self.cards return c def toString(self): """ This function returns a string that prints the current state of the deck. """ string = "" lengths1 = [3,3,3,3,3,3,3,3,3,3,4,5,4] names = "Cards: \t | Ace | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Jack | Queen | King |" lengths2 = [len(str(x)) for x in self.cards] diff_length = [a_i - b_i for a_i, b_i in zip(lengths1, lengths2)] vals = "Number:\t | " for i in range(len(self.cards)): vals += str(self.cards[i]) vals += " "*diff_length[i] vals += " | " string += names string += "\n" string += vals return string
true
db3b27100f4f94f7258176b8f37754a4ae797963
jkarnam7/devopsclassgit
/app.py
418
4.25
4
#Calculate Persons Based On Year Of Birth....!!!! name = str(input("Please Enter Your Good Name:")) year = int(input("Please Enter The Year You Are Born:")) print(year) currentage = 2020 - year months = currentage*12 days = currentage*365 print("Hello "+name + " You are %d years old " % (currentage)) print("Hello "+name + " You are %d months old " % (months)) print("Hello "+name + " You are %d days old " % (days))
false
224a28cee376f838f3d94dc7e8ac26476082fa22
fzr72725/GalvanizePre
/Unit2/Assignment_1c.py
1,943
4.40625
4
def shift_on_character(string, char): ''' Find the first occurence of the character char and return the string with everything before char moved to the end of the string. If char doesn't appear, return the same string. Parameters ---------- string : {str} char : {str} Returns ------- str Example ------- >>> shift_on_character("galvanize", "n") 'nizegalva' ''' for i,e in enumerate(string): if e==char: return string[i:]+string[:i] return string def is_palindrome(string): ''' Return whether the given string is the same forwards and backwards. Parameters ---------- string : {str Returns ------- bool Example ------- >>> is_palindrome("rats live on no evil star") True >>> is_palindrome("the moon waxes poetic in sunlight") False ''' return string==string[::-1] def alternate(L): ''' Use list slicing to return a list containing all the odd indexed elements followed by all the even indexed elements. Parameters ---------- L : {list} Returns ------- list : {list} Example ------- >>> alternate(['a', 'b', 'c', 'd', 'e', 'f', 'g']) ['b', 'd', 'f', 'a', 'c', 'e', 'g'] ''' return [e for i,e in enumerate(L) if i%2!=0]+[e for i,e in enumerate(L) if i%2==0] def shuffle(L): ''' Return the result of a "perfect" shuffle. You may assume that L has even length. You should return the result of splitting L in half and alternating taking an element from each. Parameters ---------- L : {list} Returns ------- list : {list} Example ------- >>> shuffle([1, 2, 3, 4, 5, 6]) [1, 4, 2, 5, 3, 6] ''' h_1 = L[:len(L)/2] h_2 = L[len(L)/2:] return list(reduce(lambda total,e: total+e, zip(h_1, h_2))) if __name__ == '__main__': shuffle(L)
true
9dde44d8aa347011bef9666159b2b693ff621eee
Ankita-Dake/PythonConditions
/If-condition.py
590
4.375
4
# Simple if Statement i = 20 if i < 30: print("i is less than 30") # second way i = 10 if i == 20: print("i is equal to 10") print("i is not equal to 10") # another example i = 20 if (i % 2) == 0: print(" divide ") else: print("not divide") # another example num = int(input("enter number")) if num % 2 == 0: print("number is even") # largest three number a = int(input("enter a")) b = int(input("enter b")) c = int(input("enter c")) if a>b and a>c: print("a is largest") if b>a and b>c: print("b is largest") if c>a and c>b: print("c is largest")
false
1032597eb1639262ab89d5488f84801ef9f4592a
stanislavkozlovski/python3_softuni_course
/7.SQLite with Python/find_sales_from_city.py
1,237
4.125
4
""" sample input: python3 find_sales_from_city.py ./database """ import sys import sqlite3 if(len(sys.argv) < 2): print("You need to enter the path to the database!") exit() PATH_TO_DB = sys.argv[1] user_input_city = input("Въведете име на град: ") output_list = [] with sqlite3.connect(PATH_TO_DB, isolation_level=None) as db_connection: cursor = db_connection.cursor() # get all the sales from that city from the database sales = cursor.execute("SELECT item_key, sale_timestamp, price FROM sale WHERE city_name = ?", [user_input_city]) # iterate through the sales and save them as a string in a list for output_line in sales: sale_item_key = output_line[0] sale_timestamp = output_line[1] sale_price = float(output_line[2]) output_list.append("Артикул #: {0} дата/час: {1} сума: {2:.2f}".format(sale_item_key, sale_timestamp, sale_price)) if len(output_list) == 0: # check if we have any sales from said city print("Няма данни за продажби в град {}".format(user_input_city)) else: print("Продажби в град {}: ".format(user_input_city)) print() for output_line in output_list: print(output_line)
true
d66ac3fcd19a79d4c135ff85fb2a14ea1c5b9bae
InesTeudjio/FirstPythonProgram
/ex6.py
544
4.53125
5
# 6.Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. def add_string(str1): length = len(str1) if length > 3: if str1[-3:] == 'ing': str1 += 'ly' else: str1 += 'ing' if length < 3: str1 = str1 return str1 print(add_string('smilling')) print(add_string('love')) print(add_string('not'))
true
c15599271889249b612d0001fb9320cc73ab0fcf
lawalyusuf/PYTHON_LAB2
/trigFunctions.py
419
4.1875
4
#Trig Functions #Trigonometric functions are used to calculate sine and cosine in equations. By default, Python does not know how to calculate sine and cosine, but it can once the proper library has been imported. Units are in radians. # Import the math library # This line is done only once, and at the very top # of the program. from math import * # Calculate x using sine and cosine x = sin(0) + cos(0) print(x)
true
5f4821917452ff340f47ed8c03b8a04aa90d2830
Vishesh-Sharma221/Personal-Projects
/Calculator/calculator.py
874
4.3125
4
# intro print("Hey welcome! \n") print(''' Use these commands to use the calculator : Addition = '+' substraction = '-' multiplication = '*' division = '/' ''') # input var1 = input("enter here:") try: var2 = int(input("Enter the number:")) var3 = int(input("Enter the second number:")) except: print("the input must be a number !!") try : if var1 == '+': sum = var2 + var3 print("your answer is " , sum) elif var1 == '-': diff = var2 - var3 print("your answer is " , diff) elif var1 == '*': times = var2*var3 print("your answer is " , times) elif var1 == '/': div = var2/var3 print("your answer is" , div) else: print("wrong input ! try again") except: print("Wrong imput !! please try again ") #ez
true
d63ff6fc68cd4a36398079a9eae4eccedd5232be
chandan5569/python_Arrays
/transpose.py
338
4.15625
4
x=[] print('enter the elemets of the matrices') for i in range(3): a=[] for j in range(3): a.append(int(input())) x.append(a) b=[[0,0,0],[0,0,0],[0,0,0]] for m in range(3): for n in range(3): b[m][n]=x[n][m] if x==b: print('given matrices is transpose') else: print('not transpose')
false
5143b1962e9e3c7f65d9da01fbb3e74fdeec733c
ravitejam2307/Python_lab
/Lab Cycle/8_matrices_mul.py
1,155
4.34375
4
#Program to multiply two matrices #First matrix rows_a = int(input("Enter the Number of rows for the first matrix: " )) column_a = int(input("Enter the Number of Columns for the first matrix: ")) print("Enter the elements of First Matrix:") matrix_a= [[int(input()) for i in range(column_a)] for i in range(rows_a)] #Second matrix rows_b = int(input("Enter the Number of rows for the second matrix: ")) column_b = int(input("Enter the Number of Columns for the second matrix: ")) print("Enter the elements of Second Matrix:") matrix_b= [[int(input()) for i in range(column_b)] for i in range(rows_b)] print("First Matrix is: ") for n in matrix_a: print(n) print("Second Matrix is: ") for n in matrix_b: print(n) result=[[0 for i in range(column_b)] for i in range(rows_a)] for i in range(len(matrix_a)): for j in range(len(matrix_b[0])): for k in range(len(matrix_b)): result [i][j]+=matrix_a[i][k]*matrix_b[k][j] print("\nResultant Matrix of (Matrix_a X Matrix_b) is: ") for r in result: print(r)
false
85aff52949ac41afc20ee2bc73eca155548eae98
dsonaty/LearningPython
/Ch2/conditionals_start.py
743
4.1875
4
# # Example file for working with conditional statements # def main(): x, y = 100, 100 # conditional flow uses if, elif, else # if x = y the first condition (x < y) will evaluate to false # therefore the second condition (else) will evaluate to true # This is the reason we have to add the elif condition # Python does NOT use switch and uses elif as a substitute if (x < y): st = "x is less than y" elif (x == y): st = "x is the same as y" else: st = "x is greater than y" print(st) # conditional statements let you use "a if C else b" st = "x is less than y" if (x<y) else "x is greater than or equal to y" print(st) if __name__ == "__main__": main()
true
397fb4da8cdf57b2f2d8ed929d98c16ce9cc98ed
Cloud-Scripter/Python
/Programs/Factorial.py
206
4.28125
4
import sys def Factorial(num): result = 1 while(num > 1): result = result * (num) num = num - 1 return result user_input = input("Enter Number : ") print(Factorial(user_input))
false
90c4b3e5b614e413b598213f3b561ba00442610d
daozun/Python
/base_python/video/video_operator.py
313
4.125
4
# python运算符 a = 2 b = 5 c = 'h' print(a*b) # 10 print(a/b) # 0.4 print(a//b) # 0 //是取商的意思 print(a%b) # 2 %是取余的意思 print(a**b) # 32 **是幂运算,这个是2的5次幂的意思 print(c*10) # 字符串还可以和数字相乘,得到一个字符串,里面是乘以数字的总和
false
a3783dbb64dd1e8df96227d0a12b5370ff593bb7
daozun/Python
/base_python/video/video_while.py
365
4.15625
4
# 在Python里分为三种程序执行结构,分别是:自上而下、if、while i = 1 while i<=10: i = i+1 print(i) # 自上而下执行,在while语句里循环,当i=10时,执行了i=i+1,所以打印出来了11 n = 1 while n<=10: print(n) n = n+1 # 这次先打印后加就不会出现11了 j = 1 while j<=100: print(j) j = j+1
false
c9112662939c51710ba529011d16e2166137925f
feizhen/coursera-course
/Algorithmic-Toolbox/week2/fibonacci_number.py
223
4.15625
4
#!/usr/bin/env/ python3 # -*- conding: utf-8 -*- def fibonacci_number(n): fib = [0, 1] for x in range(2, n+1): fib.append(fib[x-1] + fib[x-2]) return fib[n] n = int(input()) print(fibonacci_number(n))
false
5a0b42f0254d4b2e8f874f6b87cac953c265a132
DimitryLenchevsky/CStutorial
/Dmitry_Lenchevsky.py
832
4.1875
4
sentence = "Не знаю, как там в Лондоне, я не была. Может, там собака — друг человека. А у нас управдом — друг человека!" print("Количество символов в строке будет:", len(sentence)) print("Инверсная строка:", sentence[::-1]) print("Все буквы прописные:", sentence.upper()) print("Чисто вхождений \"нд\" в строку:", sentence.count("нд"), ", \"ам\" в строке:", sentence.count('ам'), ", \"о\" в строке:", sentence.count('о')) print("Содержит ли срока числа?", sentence.isalnum()) print("Выведим последнее предложение строки:", sentence[73:107]) print("Исхрдная строка:", sentence)
false
e2e61961ed9bdc38072c009b413d08c8c9ba62cf
ozmaws/Chapter-2-Projects
/Project2.6.py
421
4.28125
4
# Request the inputs mass = int(input("Enter the mass in kg: ")) velocity = int(input("Enter the velocity in m/s: ")) # compute the momentum momentum = mass * velocity # compute kinetic energy kineticEnergy = (1/2) * mass * velocity ** 2 # Display the momentum and kinetic energy print("The momentum is " + str(momentum) + " kg*(m/s)") print("The kinetic energy is " + str(kineticEnergy) + " joules")
false
5d513fcc7dd1e64e067662931c282619424fcdc6
raghavpatpatia/Floxus-Education-Python-Bootcamp-101
/Assignment 1/Prime.py
347
4.21875
4
n = int(input("Enter number: ")) if n == 0 or n == 1: print(n, "is neither prime nor composite number.") elif n > 1: for i in range(2, int(n // 2) + 1): if (n % i) == 0: print(n, "is not a prime number.") break else: print(n, "is a prime number.") else: print(n, "is not a prime number.")
false
9c9a0a8a09a11656092cff22b1d2adb2c89f394c
Dan-krm/Calculations
/tripCost.py
1,322
4.5
4
# Author: Dan Richmond-Martina def trip_cost(air_fare, room_cost, number_of_people, number_of_nights): """ Computes the total amount due for a trip :param air_fare: A float which is the cost of the flight in dollars :param room_cost: A float which is the cost of the room in dollars :param number_of_people: An integer for the number of people attending the trip :param number_of_nights: An integer for the number of nights stayed at the hotel :return: The total cost of the trip per person """ number_of_rooms = number_of_people // 2 + number_of_people % 2 total = ((number_of_rooms * room_cost * number_of_nights) + (number_of_people * air_fare)) return total def display_trip_cost(): print("\n4: Calculate a Trips Cost\n") # Call the trip_cost function using user inputs for each parameter, then display the results group_total = trip_cost(air_fare=float(input("Enter the the cost of the flight: ")), room_cost=float(input("Enter the cost of a room per night: ")), number_of_people=int(input("Enter the number of people: ")), number_of_nights=int(input("Enter the number of nights: "))) print("The total cost of the trip for the group is: $" + str(group_total))
true
5b05ec3d986c621930bae2e67dd648b14d77124f
gl051/sorting-algorithms
/bubble_sort.py
429
4.3125
4
#!/usr/bin/env python """ Bubble Sort Algorithm Description: sort an input array of integers and return a sorted array """ def bubble_sort(iarray): switched = True n = len(iarray) while switched: switched = False for i in range(0, n-1): if iarray[i] > iarray[i+1]: iarray[i], iarray[i+1] = iarray[i+1], iarray[i] switched = True return iarray
false
cf73cb406a8c3c65f0acf58c44adf79d96a32f4c
y0shK/game-optimization
/FTL/ftl_path_optimization.py
2,349
4.125
4
# program optimizing flight paths in FTL """ FTL is a game in which a spaceship has to travel from sector to sector to gain points. The goal is to visit as many sectors as possible in the y component while never moving backwards in the x component. The optimal pattern looks like a sinusoidal function, but varies based on gameplay. This program aims to optimize the flight path given a random field of sectors. Links referenced: https://stackoverflow.com/questions/35363444/plotting-lines-connecting-points """ import matplotlib.pyplot as plt import random # random library to simulate the gameplay loop's random field xLoc = [] yLoc = [] upperBound = 10 # arbitrarily chosen to enclose points iterator = 3 # arbitrarily chosen to make travel between points feasible, not too far apart # artificially bound the points together so path travel is actually possible, not zigzagging all over the plane def pointBounds(array, bound, delta, index1, index2): while abs(array[index1] - array[index2]) > delta: # distance between points is greater than a given value array[index1] = array[index2] + delta if array[index1] > bound or array[index2] > bound: # if a point is out of the plane, bring it back in array[index1] = bound - random.randint(0, bound) if abs(array[index1] - array[index2]) <= delta: # conditions met, plane is sufficiently constricted break def graph(xAxis, yAxis): # graph lines that connect the ordered pairs to show connections for i in range(1, len(xAxis)): x1, x2 = xAxis[i], xAxis[i-1] y1, y2 = yAxis[i], yAxis[i-1] plt.plot([x1, x2], [y1, y2]) plt.scatter(xAxis, yAxis) plt.title("FTL graph") plt.show() # assign random locations in space to use for path optimization for i in range(0, 10): xLoc.append(random.randint(0, upperBound)) yLoc.append(random.randint(0,upperBound)) for i in range(len(xLoc)): # base case pointBounds(xLoc, upperBound, iterator, 0, 1) pointBounds(yLoc, upperBound, iterator, 0, 1) # induction pointBounds(xLoc, upperBound, iterator, 0, 1) pointBounds(yLoc, upperBound, iterator, i, i-1) xLoc.sort() # sort x-coordinates so no backwards motion occurs, all vertical motion okay print("X-coordinates: %s" % xLoc) print("Y-coordinates: %s" % yLoc) graph(xLoc, yLoc)
true
c1ce67613bfefe7edbab68e67ecea08337974cfc
BrandonBaLu/poo--1719110177
/semana-5/cesar.py
1,374
4.15625
4
print("**-Bienvenidos al cifrado de cesar-**") class cesar: # def _init_(self):# pass def cifrados(self): repetir = "S" while repetir == "s" or repetir == "S": texto = input("Inserta tu texto: ") n = 5 tipo=int(input("Ingrese el tipo de trabajo a realizar \n|1:Encriptar 2:Desencriptar|\ningrese numero\n")) abecedario = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' cifrado = '' texto = texto.upper() for s in texto: if s in abecedario: num = abecedario.find(s) if tipo==1: num = num + n elif tipo==2: num = num - n if num >= len(abecedario): num = num - len(abecedario) elif num < 0: num = num + len(abecedario) cifrado = cifrado + abecedario[num] else: cifrado = cifrado + s print("el texto cifrado o descifrado es:\n",cifrado) repetir = input("Desea ingresar una nueva cadena de texto? \nS/N\n ") if repetir == "n" or repetir == "N": print("*-gracias por usar el codigo cesar-*") break objetoCesar = cesar() objetoCesar.cifrados()
false
48074dfbcee6e8cc2dc6c80c41c76a8ed8cd7c72
Mendeleevuko/Python_Self_Study
/python_txt_downloads/mbox-short.py
945
4.34375
4
####Question #8.5 """Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end. Hint: make sure not to include the lines that start with 'From:'. You can download the sample data at http://www.py4e.com/code3/mbox-short.txt""" file_name = input("Enter a file name: ") file_handle = open(file_name) count_file = 0 for line in file_handle: if not line.startswith('From '): continue line_split = line.split() ##print(line) ##print(line_split) print(line_split[1]) count_file += 1 print(count_file) print("There were", count_file, "lines in the file with from as the first word") file_handle.close()
true
851be8aea148a1355e52b35c6dd5f61e8853350d
djcutch/PythonLevel1
/venv/Week 1/Exersice 1.9.py
1,750
4.1875
4
# 1.9 # 1 In a print statement, what happens if you leave out one of the parentheses, or both? In a print statement, what happens if you leave out one of the parentheses, or both? # print ("Hello World" # A. SyntaxError: unexpected EOF while parsing # 2. If you are trying to print a string, what happens if you leave out one of the quotation marks, # or both? # print ('hello) # A. SyntaxError: EOL while scanning string literal # 3. You can use a minus sign to make a negative number like -2. What happens if you put a plus sign before a number? What about 2++2? # A. print(2+-2) = 0 , print(2++2) = 4 # 4. In math notation, leading zeros are ok, as in 09. What happens if you try this in Python? What about 011? # A. print(09) = SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers # A. print (011) = SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers # 5. What happens if you have two values with no operator between them? # A. print (22 22) = What happens if you have two values with no operator between them? # 6. How many seconds are there in 42 minutes 42 seconds? # A. minutes = 60 , print(((minutes*42)+42)) = 2562 Seconds # 7. How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile. # A. miles = (1*1.61) ,print(miles*10) = 16.1 km # 8. If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace (time per mile in minutes and seconds)? What is your average speed in miles per hour? # miles = (10/1.61) # print (miles) 6.211180124223602 # print ((((60*42)+42)/miles),"seconds") 412.482 seconds # print ((60/miles),"Miles Per hour") 9.660000000000002 Miles Per hour
true
5c658aced039bccc10ee6c825dc0834873975994
AleksGo23/hw2py
/main.py
1,172
4.3125
4
# Aleks Gondek alg6177@psu.edu def getGradePoint(grade): gpa = 0.0 if grade == "A" : gpa = 4.0 elif grade == "A-" : gpa = 3.67 elif grade == "B+" : gpa = 3.33 elif grade == "B" : gpa = 3.0 elif grade == "B-" : gpa = 2.67 elif grade == "C+" : gpa = 2.33 elif grade == "C" : gpa = 2.0 elif grade == "D" : gpa = 1.0 else : gpa = 0.0 return gpa def run(): grade1 = input("Enter your course 1 letter grade: ") credit1 = input("Enter your course 1 credit: ") credit1 = float(credit1) gpa1 = getGradePoint(grade1) print("Grade point for course 1 is:",gpa1) grade2 = input("Enter your course 2 letter grade: ") credit2 = input("Enter your course 2 credit: ") credit2 = float(credit2) gpa2 = getGradePoint(grade2) print("Grade point for course 2 is:",gpa2) grade3 = input("Enter your course 3 letter grade: ") credit3 = input("Enter your course 3 credit: ") credit3 = float(credit3) gpa3 = getGradePoint(grade3) print("Grade point for course 3 is:",gpa3) GPA = (gpa1*credit1 + gpa2*credit2 + gpa3*credit3)/(credit1+credit2+credit3) print("Your GPA is:", GPA) if __name__ == "__main__": run()
false
6d46564eb5d9bad7b2e6a47c896d00a0f15975eb
v-melkov/python-basic
/homework_01/main.py
1,577
4.375
4
""" Домашнее задание №1 Функции и структуры данных """ def power_numbers(*args): """ функция, которая принимает N целых чисел, и возвращает список квадратов этих чисел >>> power_numbers(1, 2, 5, 7) <<< [1, 4, 25, 49] """ return [i ** 2 for i in args] # filter types ODD = "odd" EVEN = "even" PRIME = "prime" def is_prime(num): flag = True for i in range(2, num // 2 + 1): if num % i == 0: flag = False return num > 1 and flag == True def filter_numbers(nums, type): """ функция, которая на вход принимает список из целых чисел, и возвращает только чётные/нечётные/простые числа (выбор производится передачей дополнительного аргумента) >>> filter_numbers([1, 2, 3], ODD) <<< [1, 3] >>> filter_numbers([2, 3, 4, 5], EVEN) <<< [2, 4] >>> filter_numbers([1, 2, 3, 5, 6, 7], PRIME) <<< [2, 3, 5, 7] """ if type == 'odd': return list(filter(lambda i: i % 2 == 1, nums)) # Filter function # return [i for i in nums if i % 2 != 0] # List comprehension elif type == 'even': return list(filter(lambda i: i % 2 == 0, nums)) # return [i for i in nums if i % 2 == 0] elif type == 'prime': return list(filter(is_prime, nums)) # return [i for i in nums if is_prime(i)]
false
47123ea81f56f16de9bd5352efa0b3fdce7a08be
pen-ualberta/Introduction-to-Computing-Foundations-II
/Lab1/lab1.2.py
1,124
4.21875
4
#creating a list of months months = ('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT') print('The contents of object', id(months), months) #new months nMonths = ('NOV', 'DEC') #adding new months months = months + nMonths print(months) print('The contents of object', id(months), 'are', months) #the identities of the tuple has changed and therefore it is immuatable #list of precipitation amounts precipitation2019 = [15.5, 12.1, 18.5, 15.6, 10.7, 62.2, 41.4, 58.3, 15.7, 15.3, 24.8] #adding july levels precipitation2019.insert(6, 67.8) print(precipitation2019) #finding the amount for april aprilIndex = months.index('APR') print(str(precipitation2019[aprilIndex]) + 'mm fell in APR 2019') #asking for the month monthInput= input('Please enter a month? :') #if wrong answer if monthInput not in months: print('sorry, cannot find information for the month inputted') #finding precipitaiton levels for said month if monthInput in months: monthIndex = months.index(str(monthInput)) print(str(precipitation2019[monthIndex]) + 'mm fell in ' + monthInput+ ' 2019')
true
d1d70235ce5f0d6db901c6edafcf5a03c0012795
deenario/Python_Tasks
/Triangle.py
270
4.21875
4
height = int(input("Enter the height of the triangle ")) stars = 1 spaces = height for x in range(height): for y in range(spaces): print(" ",end="") for z in range(stars): print("*",end="") print("") spaces -=1 stars +=2
true
c67866e2fbff514ba5aa8eea67aae6dcc479b4ea
Creatorr/academy
/python/2015_09_CODEWARS_Column Names.py
1,692
4.25
4
################################################################################ # # Microsoft Excel uses a special convention to name its column headers. The # first 26 columns use the letters 'A' to 'Z'. Then, Excel names its column # headers using two letters. After 'ZZ', Excel uses three letters. # Write a function that takes as input the number of the column, and returns # its header. The input will not ask for a column that would be greater # than 'ZZZ'. # # Input: the first argument is a path to a file. Each line of the input file # contains one test case represented by one integer. # # Output: print one line containing the Excel column heading corresponding to # the integer in the input. # ################################################################################ # import sys # test_cases = open(sys.argv[1], 'r') test_cases = list() for i in range(18260, 18350): test_cases.append(str(i)) dictionary = ["Z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] for test in test_cases: if len(test) > 0: int_column = int(test) if int_column > 18278 or int_column < 1: continue if int_column <= 26: print dictionary[int_column] else: if int_column <= (27*26): print dictionary[(int_column - 1) / 26] + dictionary[int_column % 26] else: print dictionary[(int_column - 27) / (26 * 26)] \ + dictionary[((int_column - 1) / 26) % 26] \ + dictionary[int_column % 26] # test_cases.close()
true
7cc7c7c997ca41acf92161f268357ebe399a6d2b
Eq-Tran/Python-Practice
/Python/PracticePython-6.py
353
4.25
4
# String Lists # Ethan Tran 11/11/19 # Ask the use for a string and print out whether this string is a palindrome (word that is the same speeled backwards) s = "dood" def rev(s): return s[::-1] def isPalindrome(s): if rev(s) == s: print(s + ' is Palindrome') elif rev(s) != s: print(s + ' is not Palindrome') isPalindrome(s)
false
569df914fad67ed0b4766ecaa6912e88c5672d4b
amitks815/Old_programs
/assignprog/33.py
391
4.1875
4
list=[10,20,30,40,50,60,70] print "Original list=",list list.append(80) print "List output after value 80 is appended=", list list[4]=100 print"List output after element 100 is inserted in 4th position=", list list.sort() print "sorted list is =", list list.reverse() print "Sorted list in reverse order=",list del list[4:] print "List output after removing last 3 elements", list
true
4fab95fe3c5bdeccfb0159ebff70962778e4c3f5
amitks815/Old_programs
/assignprog/18.py
469
4.125
4
print " PRINT NUMBERS FROM 1 TO 100 USING FOR LOOP\n" for i in range(1,101): print i print "PRINT NUMBERS FROM 100 TO 1 USING FOR LOOP\n" for j in range(100,0,-1): print j print " PRINT NUMBERS FROM 1 TO 100 USING WHILE LOOP\n" k=1 while(k<101): print k k+=1 print "PRINT NUMBERS FROM 100 TO 1 USING WHILE LOOP\n" l=100 while(l>0): print l l-=1 print "Each character of helloworld in a seperate line" mystr="Helloworld" for n in mystr: print n
false
082e516dec009e2a569334916bade8c095d9a15b
amitks815/Old_programs
/assignprog/35.py
728
4.15625
4
tup1=('Monday','Tuesday','Wednesday','Thursday','Friday') print "Days in a week are=", tup1 tup2=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') print "Months in a year are=", tup2 print "concatenated tuple output is=",tup1+tup2 tup3=(1,322,43,5,67) tup4=(10,40,50,60,80) tup5=(27,63,444,11,0) print "Tuple 1=", tup3 print "Tuple 2=", tup4 print "Tuple 3=", tup5 if(cmp(tup3,tup4) and cmp(tup4,tup5) > 0): print "Tuple 1 is greater among 3" elif(cmp(tup4,tup5) and cmp(tup4,tup3) > 0): print "Tuple 2 is greater among 3" else: print "Tuple 3 is greater among 3" tup6=list(tup3) tup6.append(34) print "Element inserted after typecasting", tuple(tup6) del tup3[1] del tup3
false
c831860820db43db987da13ced80d0c41965c132
amitks815/Old_programs
/lectures/dataTypeDict.py
1,364
4.28125
4
##Dictionaries # Python has one more aggregator type Dictionaries, it also called as Associative array or Hash in other programming language. # Its stored information in the form of key and value pair # Its a Mutable # Its not ordered # Dict key is unique value cars = {'Alto' : 'Maruti', 'X320' : 'BMW', 'Ventto' : 'VolksWagon', 'i20' : 'Hyundai', 'Amaze' : 'Honda'} print (cars) print cars['Alto'] print cars['i20'] # method of keyword arguments(more details in functions) cars = dict(Alto = 'Maruti', X320 = 'BMW', Ventto = 'VolksWagon', i20 = 'Hyundai', Amaze = 'Honda') print (cars) print (cars.keys()) print (cars.values()) cars['Figo'] = 'Ford' print (cars) del(cars['i20']) print(cars) print min(cars) print max(cars) print ('Alto' in cars) print ('Audi' in cars) print ('Audi' not in cars) print ('Maruti' in cars) print ('Maruti' in cars.values()) print (cars['Audi']) print (cars.get('Audi')) print (cars.get('Audi', 'Not found')) print (cars.pop('Amaze')) print (cars.pop('x320')) print ('This is {a}, that is {b}'.format(a=11,b=33)) d = dict(a = 888, b = 777) print ('This is {a}, that is {b}'.format(**d)) #Nested dict x = {'123' : {'name' : "Sathish", 'sal' : "1500000", 'dept' : "Developer"}, 'Siva': ["Sathish",1500000,"Developer"]} print x['123']['name'] print x['123']['sal'] print x['123']['dept'] print x['Siva'][0]
true
869c005083161eec49d86672b6bd12fa3fe2f3c0
segordon/euler_python
/09.py
492
4.3125
4
__author__ = 'segordon' # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a**2 + b**2 = c**2 # # For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def find_triplets(): for c in range(2, 1000): for a in range(1,c): b = 1000 - c - a if (a ** 2) + (b ** 2) == (c ** 2): print a,b,c,a+b+c,a*b*c find_triplets()
false
81bcc32fb621ce34c4f797be42f37043175b1478
Zahidsqldba07/python-sandbox
/src/bubble_sort.py
894
4.40625
4
""" Bubble Sort Algorithm @complexity O(n^2) @author Akafael @ref https://en.wikipedia.org/wiki/Bubble_sort """ # !/usr/bin/env python def bubble_sort(arr): """ Sort Array Elements using Bubble Sort Algorithm :return: Examples: >>> bubble_sort([1]) [1] >>> bubble_sort([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ # Traverse through all array elements n = len(arr) for i in range(n): # Last i elements are already in place for j in range(0, n - i - 1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr if __name__ == '__main__': # Test Trivial Cases with doctest import doctest doctest.testmod()
false
6682d1b10f6ac54ccf26fa7c3f13d64625543e76
alu-rwa-dsa/week-2--create-multiple-unit-tests-fiona_wanji_dirac
/question_7.py
1,075
4.25
4
#import def count_letters(str_input): """count the number of letters""" if type(str_input) is not str: #raise type error when the input is not a string raise TypeError new_dic = {} str_input = str_input.lower() #make all letters to lower case for letter in str_input: if letter == " ": #skip spaces continue if letter in list(new_dic.keys()): #increment the existing key new_dic[letter] += 1 else: new_dic[letter] = 1 #add new key and initialize to 1 return new_dic # # ===== test case 0 ============= # print("=========== Test case 0 ============\n") # print(count_letters("my first name is dirac")) # # ===== test case 1 ============= # print("\n=========== Test case 1 ============\n") # print(count_letters(" my first name is dirac ")) # # ===== test case 2 ============= # print("=========== Test case 2 ============\n") # print(count_letters("MMMMmmmmmy first name is Dirac. I am a congolese born in Kinshasa."))
true
287150927064a482c16a9f287deac0bcae88c97b
SindyPin/Python_Exercises
/Matriz_Varias.py
2,180
4.15625
4
notas = [['José', 5.0, 6.5, 3.4], ['Carlos', 3.5, 6.7, 7.7], ['Rui', 4.4, 9.5, 9.5]] print('Mostrando todos os valores:') for linha in range(len(notas)): # note a diferença deste "for" para o que vem na linha abaixo for coluna in range(len(notas[linha])): print(f'A linha {linha}, coluna {coluna} possui o valor {notas[linha][coluna]}.') print('Mostrando todos os valores da primeira coluna:') for linha in range(len(notas)): print(f'A linha {linha}, coluna 0 possui o valor {notas[linha][0]}.') print('Mostrando o valor da segunda coluna e terceira linha:') print(notas[2][1]) print('Inserindo um novo aluno ao final da lista:') notas.append(['César', 5.0, 1.3, 4.5]) for linha in range(len(notas)): for coluna in range(len(notas[linha])): print(f'A linha {linha}, coluna {coluna} possui o valor {notas[linha][coluna]}.') print('Inserindo um novo aluno na segunda posição da lista:') notas.insert(1, ['Leonel', 9.0, 8.1, 0.3]) for linha in range(len(notas)): for coluna in range(len(notas[linha])): print(f'A linha {linha}, coluna {coluna} possui o valor {notas[linha][coluna]}.') print('Concatenando os dados de uma outra matriz:') novas_notas = [['Juliana', 5.5, 6.5, 7.0], ['Rebeca', 4.3, 1.9, 8.5]] notas.extend(novas_notas) for linha in range(len(notas)): for coluna in range(len(notas[linha])): print(f'A linha {linha}, coluna {coluna} possui o valor {notas[linha][coluna]}.') print('Removendo a última linha da lista:') notas.pop() for linha in range(len(notas)): for coluna in range(len(notas[linha])): print(f'A linha {linha}, coluna {coluna} possui o valor {notas[linha][coluna]}.') print('Removendo a linha referente ao Leonel:') notas.remove(['Leonel', 9.0, 8.1, 0.3]) for linha in range(len(notas)): for coluna in range(len(notas[linha])): print(f'A linha {linha}, coluna {coluna} possui o valor {notas[linha][coluna]}.') print('Corrigindo (modificando) a segunda nota do terceiro aluno:') notas[2][2] = 10.0 for linha in range(len(notas)): for coluna in range(len(notas[linha])): print(f'A linha {linha}, coluna {coluna} possui o valor {notas[linha][coluna]}.')
false
f43fc4af40e865a966b6f6112c9c56bc189411f9
SindyPin/Python_Exercises
/IMC_Portugues.py
1,107
4.125
4
# Crie um algoritmo que solicite o peso e a altura de uma pessoa (usando a função "input"). Em base desses dois valores, # calcule o IMC (índice de massa corporal) dessa pessoa. # O IMC é calculado da seguinte forma: IMC = peso/(altura²). # Mostre na tela o IMC. Em seguida, mostre qual é a categoria na qual a pessoa se enquadra da seguinte forma: # Se o IMC for menor do que 18,5: mostre "Abaixo do peso"; # Se for igual ou maior do que 18,5 e menor do que 25: "Peso normal"; # Se for igual ou maior do que 25 e menor do que 30: "Sobrepeso"; # Se for igual ou maior do que 30 e abaixo de 35: "Obesidade I"; # Se for igual ou maior do que 35 e abaixo de 40: "Obesidade II"; # Se for acima de 40: "Obesidade III". peso = float(input('Digite o valor do peso em kg: ')) altura = float(input('Digite o valor da altura em metros: ')) IMC = peso / (altura**2) if IMC < 18.5: print('Abaixo de peso') elif 18.5 <= IMC < 25: print('Peso normal') elif 25 <= IMC < 30: print('Sobrepeso') elif 30 <= IMC < 35: print('Obesidade do tipo I') elif 35 <= IMC < 40: print('Obesidade do tipo II')
false
f5884b2de791d9e737c7b28052a61c64ffa7a384
SindyPin/Python_Exercises
/Ex4.py
339
4.21875
4
# Crie uma lista e uma tupla. Tente modificar um dos elementos de cada uma. # O que ocorre? lista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(lista) lista[0:9:1] = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10] print(lista) lista[0:9:1] = [20, 30, 40] print(lista) tupla1 = 1, 2, 3 tupla2 = (1, 2, 3) print(tupla1) print(tupla2)
false
35ee9e9c342b9ea9b04a64af40db36e09f469843
tansudasli/python-sandbox
/core/tuple.py
718
4.3125
4
# tuples are immutable. daysOfWeek = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') mon = daysOfWeek[0] weekendDays = daysOfWeek[5:] print(weekendDays) print(mon) print(30 * "-") for day in daysOfWeek: print(day) print((30 * "-") + "# list 2 tuple") daysOfWeekList = list(daysOfWeek) print(type(daysOfWeek)) print(type(daysOfWeekList)) print((30 * "-") + "# tuple 2 list") animalList = ['pig', 'bear', 'pig'] animalTuple = tuple(animalList) print(type(animalList)) print(type(animalTuple)) print(30 * "-") #%% # another way to create a tupple ! instead of () isItTuple = "ali", "veli", 31 isItTuple #%% student_tuple = ("ali", "veli", [10, 20, 30]) student_tuple[2][1]
false
5d00d3b48e1dfafe81cd160f5ba3bd20f4d3bcf9
kamaleshajjarapu/Python
/10-NestedListsMerge.py
343
4.1875
4
def nested_to_single_list(l1,l2): #l2=[] for x in l1: #print(x) if type(x)==list: nested_to_single_list(x,l2) else: l2.append(x) return l2 def main(): l1=eval(input("Enter a nested list: ")) l2=[] l2=nested_to_single_list(l1,l2) print(l2) if __name__=='__main__': main()
false
be0826d70efe3e64f4f45a93fa20a7cc344f6d23
mblopes/calculator
/main.py
1,086
4.1875
4
from calculadora import soma, subtracao, multiplicacao, divisao def menu(): options = ['Somar', 'Subtrair', 'Dividir', 'Multiplicar', 'Sair'] print("\nCALCULADORA") for i, option in enumerate(options): print(f'[{i+1}] - {option}') option = int(input('Selecione uma opção: ')) return option option = menu() while option > 0 and option < 6: numero1 = float(input('Digite o primeiro número: ')) numero2 = float(input('Digite o segundo número: ')) if option == 1: resultado = soma(numero1, numero2) print(f"{resultado:.2f}") option = menu() elif option == 2: resultado = subtracao(numero1, numero2) print(f"{resultado:.2f}") option = menu() elif option == 3: resultado = divisao(numero1, numero2) print(f"{resultado:.2f}") option = menu() elif option == 4: resultado = multiplicacao(numero1, numero2) print(f"{resultado:.2f}") option = menu() else: print("Encerrando calculadora") break
false
f0c0022e2597c20e8c133a7d40347903ca6a48ca
SSalaPla/dynamical-systems-with-applications-using-python
/IDLE-files/Sum_Primes.py
246
4.15625
4
# Sum of primes to N. # Save file as sumP.py. print('What do you want to sum to?') N=input() N=int(N) sumP=0 for n in range(2,N+1): if all(n % i for i in range(2, n)): sumP += n print('The sum of the first',n,'primes is',sumP)
true
4e30dc3f096e7750894a2059b858a3b059024283
lasttillend/CS61A
/mentor/CSM3.py
1,557
4.21875
4
# Computer Science Mentors 3 # Mutation and Nonlocal # Mutation # 3. Given some list lst, possibly a deep list, mutable lst to have the # accumulated sum of all elements so far in the list. If there is a nested # list, mutate it to similarity reflect the accumulated sum of all elements # so far in the nested list. Return the total sum of lst. # Hint: the isinstance function returns True for isinstance(l, list) if l # is a list and False otherwise. def accumulate(lst): """ >>> l = [1, 5, 13, 4] >>> accumulate(l) 23 >>> l [1, 6, 19, 23] >>> deep_l = [3, 7, [2, 5, 6], 9] >>> accumulate(deep_l) 32 >>> deep_l [3, 10, [2, 7, 13], 32] """ total = 0 for i in range(len(lst)): el = lst[i] if isinstance(el, list): inside = accumulate(el) total += inside else: total += lst[i] lst[i] = total return total # Nonlocality # 2. Pingpong again... def has_seven(k): # Use this function for your answer below if k % 10 == 7: return True elif k < 10: return False else: return has_seven(k // 10) def make_pingpong_tracker(): """Returns a function that returns the next value in the pingpong sequence each time it is called. >>> output = [] >>> x = make_pingpong_tracker() >>> for _ in range(9): ... output += [x()] >>> output [1, 2, 3, 4, 5, 6, 7, 6, 5] """ index, current, add = 1, 0, True def pingpong_tracker(): nonlocal index, current, add if add: current += 1 else: current -= 1 if has_seven(index) or index % 7 == 0: add = not add index += 1 return current return pingpong_tracker
true