blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0ca94d662e3e9e12360d7281dc50ad1d385dad5e
nsimonova/GeekBrains
/Lesson_2/Task4.py
543
4.15625
4
# Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. # Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. new_string = input("Введите фразу ") split_string = new_string.split() for index, word in enumerate(split_string, 1): print(str(index) + '. ' + word[:10])
false
fafb8be85bcf0e322db418832143041eef35f29a
rahulcs754/Python-script-example
/code/removing_Vowels.py
237
4.375
4
vowels = ("a","e","i","o","u") message = input("Enter mesage: ") new_message = "" for letters in message: if letters not in vowels: new_message = new_message+letters print("message without vowels: {}".format(new_message))
false
d40f3551ef866c7253c8432d86d95cfd06e094ef
sup3r-n0va/Python-3-Tutorial
/WhileLoops.py
556
4.375
4
#!/bin/python3 import os import random import sys #This section is on while loops #To initialise a random number generator #This will generate a random number between 0 - 100 random_num = random.randrange(0, 100) #this loop will loop through all the numbers until 42 is displayed #while(random_num != 42) : # print(random_num) # random_num = random.randrange(0, 100) #print out all the even numbers i = 0 while(i <= 100) : if(i % 2 == 0) : print(i) elif( i == 88) : break else : i += 1 #which is the same as i = i + 1 continue i += 1
true
9ff96082847f94609d541f29483e9baaa113a6c5
prusso/thebizbaz
/Python/simeonfranklin.com/class2.py
450
4.25
4
names = ['John', 'Luke', 'Paul', 'Mark', 'Richard', 'Christopher', 'Dan', 'Sam'] # Print all names in the list for name in names: print "Hello " + name # Print last name print "Hello " + names[-1] # Print last two names for name in names[6:]: print "Hello " + name # Print every other name for name in names[::2]: print "Hello " + name # Reverse rev = names[:] rev.reverse() print rev # Alphabetical alpha = names[:] alpha.sort() print alpha
false
2ddf142a4b01904609fe6814f6803b8a08e7a82e
Compro-Prasad/GLUG
/workshops/gettingComfortableWithPython/doc.py
333
4.15625
4
def add(*args): """Add all numbers provided as arguments. Example: >>> add(1, 2, 3) 6 >>> add(*range(10)) 45 >>> add(1, '2') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +=: 'int' and 'str' """ s = 0 for num in args: s += num return s
true
947db1d5d90878c51fc83d11d338aad870f1243d
devashish89/PluralsightPythonIntermediate
/ClosureEx1.py
337
4.15625
4
#Closure: is a inner function(local function) that remembers or have access to local variables when it was created even when outer function has finished def outer(msg): message = msg def inner(): print(message) return inner f = outer("Hi") print(f) print(f.__name__) #inner() f() f() f1 = outer("Hello") f1() f1()
true
bf232d1dd9a62a42f633b8e9dd6b089da8dd0073
araghava92/comp-805
/labs/lab1.py
1,134
4.25
4
""" Jon Shallow UNHM COMP705/805 Lab 1 An Introduction to Python Jan 19, 2018 The purpose of this file is to learn BASIC python syntax and data structures. There is an accompanying test file. Place both files in the same directory, and then run: $ python tests.py You will see a print out of tests that are being run, and your result. Please see: https://www.python.org/dev/peps/pep-0008/ for style guidelines """ def give_me_a_string(): return "This function returns a string value." def give_me_an_integer(): return 1 def give_me_a_boolean(): return True def give_me_a_float(): return 1.0 def give_me_a_list(): return ["this", "is", "a", "list"] def give_me_a_dictionary(): return {"first": "entry"} def give_me_a_tuple(): return (1, ) def sum_numbers_one_to_ten(): return sum(range(1, 11)) def check_is_even(number): return number % 2 == 0 def check_is_less_than(number1, number2): return number1 < number2 # Additional method - 1 def check_is_odd(number): return number % 2 != 0 # Additional method - 2 def check_is_greater_than(number1, number2): return number1 > number2
true
c02f5beda0e255a9d7ff3a007923b808e7c8ccbb
lauirvin/algorithms-data-structures
/Week_3/Week3.py
1,454
4.1875
4
# 1. Write a program that reads n words from the standard input, separated by spaces and prints them mirrored (the mirroring function should be implemented recursively). What is the time complexity of the algorithm? Use the BigO notation to express it. import unittest import string def reverseString(string): if len(string) == 0: return string else: return reverseString(string[1:]) + string[0] def reverseOrder(): var = reverseString(a) stringList = [] var = var.split() for i in var: stringList.append(i) stringList.reverse() newString = " ".join(map(str, stringList)) return newString a = input("Please enter a string you want to mirror: ") print(reverseOrder()) # 2. Write a recursive version of linear search on an array of integers. What is the time complexity of the algorithm? Use the BigO notation to express it. def linearSearch(l, target): if len(l) == 0: return False if l[0] == target: return True return linearSearch(l[1:], target) #print(linearSearch([1,3,5,7,9], 21)) class IsAnagramTests(unittest.TestCase): def testTwo(self): self.assertTrue(reverseString("hello world")) def testThree(self): self.assertTrue(linearSearch("[1,3,5,7,9]","5")) def testFour(self): self.assertFalse(linearSearch("[1,3,5,7,9]","21")) def main(): unittest.main() if __name__ == '__main__': main()
true
570085ceb4647d2701d89d54d5d579ea1b97b8f7
kaustubhsingh/CodeSomething
/Algorithms/eulerian_tour.py
696
4.21875
4
# Find Eulerian Tour # # Write a function that takes in a graph # represented as a list of tuples # and return a list of nodes that # you would follow on an Eulerian Tour # # For example, if the input graph was # [(1, 2), (2, 3), (3, 1)] # A possible Eulerian tour would be [1, 2, 3, 1] graph = [(1, 2), (2, 3), (3, 1)] def find_eulerian_tour(graph): tour = [] find_tour(graph[0][0], graph, tour) return tour def find_tour(v, E, tour): for (a, b) in E: if v == a: E.remove((a, b)) find_tour(b, E, tour) elif v == b: E.remove((a, b)) find_tour(a, E, tour) tour.insert(0, v) return tour print "Find Eulerian Tour" print graph print find_eulerian_tour(graph)
false
f274b5e5e035d2a9f6adaf34a41b69b0211b3349
luishmcmoreno/project-euler
/0019.py
625
4.21875
4
starting_day = 2 day = 1 month = 1 year = 1901 sundays = 0 while (year < 2001): if (day == 1 and starting_day % 7 == 0): sundays += 1 day += 1 starting_day += 1 if (month == 2): if (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)): if (day == 30): day = 1 month = 3 else: if (day == 29): day = 1 month = 3 elif (month == 4 or month == 6 or month == 9 or month == 11): if (day == 31): day = 1 month += 1 else: if (day == 32): day = 1 month += 1 if (month == 13): month = 1 day = 1 year += 1 print sundays
false
d9837d605db1855343075007464824c9f33520cc
katyaryabova/HomeTask9
/Task4.py
358
4.1875
4
month = int(input('Choose a month: ')) def seasons(a): if a == 1 or a == 2 or a == 12: print('Winter') elif a == 3 or a == 4 or a == 5: print('Sping') elif a == 6 or a == 7 or a == 8: print('Summer') elif a == 9 or a == 10 or a == 11: print('Autumn') else: print('Error') print(seasons(month))
false
915d9f255868e7c96b73e01111b900bf57a4d315
gloria-aprilia/Exam-Purwadhika-JCDS10
/Exam 1/TimeConverter.py
1,037
4.125
4
import math #add math library def timeConverter(seconds): #define function if type(seconds) == int and seconds >= 0 and seconds < 359999: #condition if the input is integer hour = math.floor(seconds/3600) #calculate hour hr_rem = seconds%3600 #see remaining second minute = math.floor(hr_rem/60) #calculate minute min_rem = hr_rem%60 #this is remaining second return f"konversi: {hour if hour>=10 else '0'+str(hour)}:{minute if minute>=10 else '0'+str(minute)}:{min_rem if minute>=10 else '0'+str(min_rem)}" #output return else: #condition if the input is not integer return "Invalid input !" #output return print(timeConverter(36659)) #display the result of converting 3600 seconds print(timeConverter(400000)) #display the result of >359999 input print(timeConverter(-3665)) #display the result of negative input print(timeConverter(3665.2)) #display the result of float input print(timeConverter("seratus")) #display the result of string input
true
001d520959faf86ef7fb9aa64e9010de1d1cea4f
denis19973/sorting_algorithms
/bubble.py
1,680
4.375
4
from copy import copy def simple_bubble_sort(l: list): """ Max count of iterations for sorting all elements in list with n elements is n - 1. for example: sorting [2, 1] needs 1 iteration; [3, 2, 1] needs 2 iterations """ iterations = 0 for _ in range(len(l) - 1): for i in range(len(l) - 1): iterations += 1 a = l[i] b = l[i + 1] if b < a: l[i] = b l[i+1] = a print('num iterations: {}'.format(iterations)) return l def optimized_bubble_sort(l: list): """ • In first iteration biggest number moves to the end of list also in second iteration the biggest number from remainings moves to the end and stays before last element(from first iteration). This means that we can optimize our algorithm by not checking last k elements after each k iteration • Also we can add boolean variable(not_sorted) that will indicate that in current iteration wasn't sorting action and it means that there is no more numbers to move, sorting completed. """ iterations = 0 not_sorted = False for k in range(1, len(l)): if not_sorted: break for i in range(len(l) - k): iterations += 1 a = l[i] b = l[i + 1] if b < a: l[i] = b l[i+1] = a else: not_sorted = True print('num iterations: {}'.format(iterations)) return l rand_list = [2, 12, 3, 4, 1, 45, 67, 234, 33, 37, 76, 63, 93, 59, 17, 73, 35, 43, 21, 7] print(simple_bubble_sort(copy(rand_list))) # >> num iterations: 361 # >> [1, 2, 3, 4, 7, 12, 17, 21, 33, 35, 37, 43, 45, 59, 63, 67, 73, 76, 93, 234] print(optimized_bubble_sort(copy(rand_list))) # >> num iterations: 19 # >> [1, 2, 3, 4, 7, 12, 17, 21, 33, 35, 37, 43, 45, 59, 63, 67, 73, 76, 93, 234]
true
4f485dbe3f2c7be3e008790b3e04eecac6de6a2b
hippietilley/COMP-1800
/Scripts/(11-15) Building height calculator.py
626
4.53125
5
# This program computes the height of a building, given # the angle measure to the top and the horizontal distance # to the building's base. import math theta = float(input("Enter the angle measure to the top of the building (in degrees): ")) d = float(input("Enter the horizontal distance to the base of the building (in feet): ")) # convert theta from degrees into radians # (since Python expects arguments to the tan function to be expressed in radians) theta = theta*math.pi/180 # tan(theta) = h/d, so d = h*tan(theta) h = d*math.tan(theta) print("Your building is this tall: " + str(h) + " feet")
true
5922a8428f5b23e51d864c91d3026f751f51e539
hippietilley/COMP-1800
/Scripts/Class examples/(9-29) Pizza ordering program.py
705
4.25
4
# This program computes the final price of a pizza order. # Our store sells only three types of items: # pizzas for $15 each # side items for $7.50 each # drinks for $4.99 each # get user input numPizzas = int(input("How many pizzas do you want? ")) numSides = int(input("How many sides do you want? ")) numDrinks = int(input("How many drinks do you want? ")) # do some calculations subtotal = 15*numPizzas + 7.5*numSides + 4.99*numDrinks tax = 0.0925*subtotal total = subtotal + tax # show the results print("Subtotal = $" + str(round(subtotal, 2))) print("Tax = $" + str(round(tax, 2))) print("Total = $" + str(round(total, 2))) print(" T H A N K Y O U !!!!!!!!!")
true
b0117f55d35964678d2575781acc0176cdd7cc23
MoserMichael/pythoncourse
/09-functions.py
1,662
4.53125
5
# Our programs were a sequence of sequence of statements, what would happen if we have two sequences of identical statements in the program that are used twice? # Correct - we would have two copies of these sequences. This approach comes with its problems; if we find a bug in one instance, # then we have to fix it in the other one too, this means we have to remember where these identical sequence of statements are in the program. # All this gets very difficult to handle, as our programs grow larger. # The solution to this problem are functions, a function is a grouping of a common sequence of statements, that can be used from any point in the program. # We are actualy using functions already, when we print something on the screen - in this case the print function is called. # In this lesson we are learning, how to define our own functions. import math # now this defines a function that computes the length of the third side (hypotenuse) in a square triangle. # a function definition starts with def,followed by the name of the function. # the list of arguments that the function receives is listed between the ( and ) signs def square_triangle(side_a, side_b): # the code that is run when the funcion square_triangle is being called, again it is indented (like with if and while statements) # here we define a variable square_of_third_side that is only visible in the function square_triangle square_of_third_side = side_a*side_a+side_b*side_b return math.sqrt(square_of_third_side) # calling the function that we have just defined! side_c = square_triangle(2,3) print("the hypotenuse of the square triangle:", side_c)
true
c75e91bf9b13569d1941e88be09046252220f88d
Jimut123/code-backup
/python/coursera_python/FUND_OF_COMP_RICE/FUND_OF_COMPUTING_RICE2/week1/iter_lists.py
985
4.21875
4
def square_list1(numbers): """Returns a list of the squares of the numbers in the input.""" result = [] for n in numbers: result.append(n ** 2) return result def square_list2(numbers): """Returns a list of the squares of the numbers in the input.""" return [n ** 2 for n in numbers] print square_list1([4, 5, -2]) print square_list2([4, 5, -2]) def is_in_range(ball): """Returns whether the ball is in the desired range. """ return ball[0] >= 0 and ball[0] <= 100 and ball[1] >= 0 and ball[1] <= 100 def balls_in_range1(balls): """Returns a list of those input balls that are within the desired range.""" result = [] for ball in balls: if is_in_range(ball): result.append(ball) return result def balls_in_range2(balls): return [ball for ball in balls if is_in_range(ball)] print balls_in_range1([[-5,40], [30,20], [70,140], [60,50]]) print balls_in_range2([[-5,40], [30,20], [70,140], [60,50]])
true
03dd82e95bb0909e7dd5c25783d017d052b2ee3d
Jimut123/code-backup
/python/coursera_python/RICE/PPE/date_m.py
732
4.4375
4
""" Demonstration of some of the features of the datetime module. """ import datetime # Create some dates print("Creating Dates") print("==============") date1 = datetime.date(1999, 12, 31) date2 = datetime.date(2000, 1, 1) date3 = datetime.date(2016, 4, 15) # date4 = datetime.date(2012, 8, 32) # Today's date today = datetime.date.today() print(date1) print(date2) print(date3) print("") # Compare dates print("Comparing Dates") print("===============") print(date1 < date2) print(date3 <= date1) print(date2 == date3) print("") # Subtracting dates print("Subtracting Dates") print("=================") diff = date2 - date1 print(diff) print(diff.days) diff2 = date3 - date2 print(diff2) print(diff2.days) print("")
true
baa2722d280e1dae0866ccf297772f0cc81eb508
Jimut123/code-backup
/python/coursera_python/FUND_OF_COMP_RICE/FUND_OF_COMPUTING_RICE2/week2/particle_random1.py
1,426
4.125
4
# Particle class example used to simulate diffusion of molecules import simplegui import random # global constants WIDTH = 600 HEIGHT = 400 PARTICLE_RADIUS = 5 COLOR_LIST = ["Red", "Green", "Blue", "White"] DIRECTION_LIST = [[1,0], [0, 1], [-1, 0], [0, -1]] # definition of Particle class class Particle: # initializer for particles def __init__(self, position, color): self.position = position self.color = color # method that updates position of a particle def move(self, offset): self.position[0] += offset[0] self.position[1] += offset[1] # draw method for particles def draw(self, canvas): canvas.draw_circle(self.position, PARTICLE_RADIUS, 1, self.color, self.color) # string method for particles def __str__(self): return "Particle with position = " + str(self.position) + " and color = " + self.color # draw handler def draw(canvas): for p in particle_list: p.move(random.choice(DIRECTION_LIST)) for p in particle_list: p.draw(canvas) # create frame and register draw handler frame = simplegui.create_frame("Particle simulator", WIDTH, HEIGHT) frame.set_draw_handler(draw) # create a list of particles particle_list = [] for i in range(100): p = Particle([WIDTH / 2, HEIGHT / 2], random.choice(COLOR_LIST)) particle_list.append(p) # start frame frame.start()
true
cf3da63305700ddc1ae685d781c56fc97a35ed4f
Jimut123/code-backup
/python_gui_tkinter/Tkinter/TkinterCourse/33_sliders.py
824
4.3125
4
''' A slider is a Tkinter object with which a user can set a value by moving an indicator. Sliders can be vertically or horizontally arranged. A slider is created with the Scale method(). Using the Scale widget creates a graphical object, which allows the user to select a numerical value by moving a knob along a scale of a range of values. The minimum and maximum values can be set as parameters, as well as the resolution. We can also determine if we want the slider vertically or horizontally positioned. A Scale widget is a good alternative to an Entry widget, if the user is supposed to put in a number from a finite range, i.e. a bounded numerical value. ''' from tkinter import * master = Tk() w = Scale(master, from_=0, to=42) w.pack() w = Scale(master, from_=0, to=200, orient=HORIZONTAL) w.pack() mainloop()
true
6e6bccda0b771bb7f3c16e14a937687b7ed0aeea
Jimut123/code-backup
/python/python_new/Python 3/elif.py
213
4.40625
4
#Program checks if the number is positive or negative# And displays an appropriate message num=3.4 #num=0 #num=-4.5 if num>=0: print("Positive number") elif num==0: print("Zero") else: print("Negative number")
true
2b73effba297e3453d24fccfe6423e4f3fc80c92
Jimut123/code-backup
/python_gui_tkinter/Tkinter/TkinterCourse/34_sliders_1.py
655
4.1875
4
''' We have demonstrated in the previous example how to create sliders. But it's not enough to have a slider, we also need a method to query it's value. We can accomplish this with the get method. We extend the previous example with a Button to view the values. If this button is pushed, the values of both sliders is printed into the terminal from which we have started the script: ''' from tkinter import * def show_values(): print (w1.get(), w2.get()) master = Tk() w1 = Scale(master, from_=0, to=42) w1.pack() w2 = Scale(master, from_=0, to=200, orient=HORIZONTAL) w2.pack() Button(master, text='Show', command=show_values).pack() mainloop()
true
33f51afd4e3d5207a3c7ee1551f26d762a992658
Jimut123/code-backup
/python_gui_tkinter/Tkinter/TkinterCourse/51_gridm.py
1,569
4.28125
4
''' The first geometry manager of Tk had been pack. The algorithmic behaviour of pack is not easy to understand and it can be difficult to change an existing design. Grid was introduced in 1996 as an alternative to pack. Though grid is easier to learn and to use and produces nicer layouts, lots of developers keep using pack. Grid is in many cases the best choice for general use. While pack is sometimes not sufficient for changing details in the layout, place gives you complete control of positioning each element, but this makes it a lot more complex than pack and grid. The Grid geometry manager places the widgets in a 2-dimensional table, which consists of a number of rows and columns. The position of a widget is defined by a row and a column number. Widgets with the same column number and different row numbers will be above or below each other. Correspondingly, widgets with the same row number but different column numbers will be on the same "line" and will be beside of each other, i.e. to the left or the right. Using the grid manager means that you create a widget, and use the grid method to tell the manager in which row and column to place them. The size of the grid doesn't have to be defined, because the manager automatically determines the best dimensions for the widgets used. ''' from tkinter import * colours = ['red','green','orange','white','yellow','blue'] r = 0 for c in colours: Label(text=c, relief=RIDGE,width=15).grid(row=r,column=0) Entry(bg=c, relief=SUNKEN,width=10).grid(row=r,column=1) r = r + 1 mainloop()
true
de48fa8a397f50506934616e612f259f06c202a0
shiyaowww/checkers
/coordinate.py
2,720
4.25
4
''' Created by: Shiyao Wang Time: Nov 12, 2020 Purpose: To represent a two-dimensional coordinate ''' class Coordinate: ''' Class -- Coordinate Attributes: x -- an integer or a float, the X coordinate y -- an integer or a float, the Y coordinate Methods: increment_x, increment_y, add_x, add_y, add ''' def __init__(self, x = 0, y = 0): ''' Constructor -- creates a new instance of Coordinate. Parameters: self -- the current Coordinate object x -- an integer or a float, the X coordinate y -- an integer or a float, the Y coordinate ''' self.x = x self.y = y def __str__(self): ''' Method -- __str__ Creates a string representation of the Coordinate. Parameter: self -- The current Coordinate object Returns: A string representation of the Coordinate. ''' out = 'x: ' + str(self.x) + ' ' + 'y: ' + str(self.y) return out def __eq__(self, coord): ''' Method -- __eq__ Checks if two objects are equal. Parameters: self -- The current Coordinate object coord -- An object to compare self to. Returns: True if the two objects are equal, False otherwise. ''' return self.x == coord.x and self.y == coord.y def increment_x(self): ''' Method -- increment_x Increments x by 1. Parameters: N/A Returns: N/A. Increments x by 1. ''' self.x += 1 def increment_y(self): ''' Method -- increment_y Increments y by 1. Parameters: N/A Returns: N/A. Increments y by 1. ''' self.y += 1 def add_x(self, adder): ''' Method -- add_x Adds a value to x. Parameters: adder -- an integer or a float, to add to x Returns: N/A. Adds a value to x. ''' self.x += adder def add_y(self, adder): ''' Method -- add_y Adds a value to y. Parameters: adder -- an integer or a float, to add to y Returns: N/A. Adds a value to y. ''' self.y += adder def add(self, coord): ''' Method -- add Adds a coordinate to this coordinate. Parameters: coord -- an instance of Coordinate Returns: N/A. Adds a coordinate to this coordinate. ''' self.x += coord.x self.y += coord.y
true
fd511eaac15fb2beb7c8e25c1164d45f9c127f55
Saurabh-sabby/Assignment-3
/script_3/p2.py
642
4.28125
4
import math class Circle: def __init__(self,rd): self.radius = rd def circumference_of_circle(self): return 2 * math.pi * self.radius def compare_circles(): if no1>no2: print("Circle 1 is bigger than Circle 2") else: print("Circle 2 is bigger than Circle 1") no1=int(input("Enter radius of circle 1 : ")) no2=int(input("Enter radius of circle 2 : ")) obj1 = Circle(no1) obj2 = Circle(no2) print(f"Circumference if circle 1: {obj1.circumference_of_circle()}") print(f"Circumference if circle 2: {obj2.circumference_of_circle()}") Circle.compare_circles()
true
65040babaab00e760593f1b471783edc29907db1
ChuleHou/Python-Programming
/AnimalSubclass/animalGenerator.py
1,236
4.40625
4
import Animals # Create a list for Animal objects object_list = [] # Print a welcome message print("Welcome to the animal generator!") print("This program creates Animal objects") while True: # Ask the user for the animal's type print("\nWould you like to create a mammal or bird? \n1. Mammal \n2. Bird") type = input("Which would you like to create? ") if type == "1": animal_type = input("\nWhat type of mammal would you like to create? ") animal_name = input("What is the mammal’s name? ") hair_color = input("What color is the mammal’s hair? ") object_list.append(Animals.Mammal(animal_type,animal_name,hair_color)) else: animal_type = input("\nWhat type of bird would you like to create?") animal_name = input("What is the bird's name?") can_fly = input("Can the bird fly?") object_list.append(Animals.Bird(animal_type,animal_name,can_fly)) choice = input("\nWould you like to add more animals (y/n)? ") if choice != "y": break # Print a header print("\nAnimal List:") # Loop through the list for animals in object_list: print(animals.get_name() + " the " + animals.get_animal_type() + " is " + animals.check_mood())
true
1970c693259781b0dfdf49667cad4ac4c2be9655
Mponsubha/.guvi
/codekata/vow.py
237
4.15625
4
alpha=input() alpha=alpha.lower() if(alpha=='$' or alpha=='%' or alpha=='*' or alpha=='#'): print("invalid") elif(alpha=='a' or alpha=='e' or alpha=='i' or alpha=='o' or alpha=='u'): print("Vowel") else: print("Consonant")
false
68e4ce941970536975cc767278d16fd2b4e46448
moufil/opp-practice-2
/2.py
891
4.15625
4
class TriangleChecker: def __init__(self, a, b, c): self.a, self.b, self.c = a, b, c def is_triangle(self): if self.a <= 0 or self.b <= 0 or self.c <= 0: print("С отрицательными числами ничего не выйдет!") else: sides = sorted((self.a, self.b, self.c), key = lambda x : -x) print("Ура, можно построить треугольник!") if sides[0] < sides[1] + sides[2] else print("Жаль, но из этого треугольник не сделать.") a=int(input("Проверить треугольник")) tri1 = TriangleChecker(-1, 4, 5) tri2 = TriangleChecker(17, 2, 2) tri3 = TriangleChecker(2, 3, 4) if a==1: tri1.is_triangle() elif a==2: tri2.is_triangle() elif a==3: tri3.is_triangle()
false
6cb1780c11f9e9ca1baa10d5db36ff9af957a93b
simsekonur/Python-exercises
/exercise/examples/num_bet.py
224
4.1875
4
# this function takes two integers and generates an ordered list of the numbers in between them lst = [] def number_between(x,y): for i in range (x+1,y): lst.append(i) return lst print (number_between(3,10))
true
84d6a7438b540f210e1c46cb7d511e87e1886e59
simsekonur/Python-exercises
/exercise/prime.py
677
4.21875
4
print ("********************") print ("Is Prime Or Not?") print ("To quit program , please press q ...") print ("********************") def IsPrime (number ): for i in range (2,number): if (number % i == 0 ): return 0 return 1 while (True): number = raw_input ("Enter the number :") if (number == "q"): print ("Exiting program...") break number = int (number) if (number== 1 or number == 0): print ("{} is not a prime number...".format(number)) elif (IsPrime (number) == 1): print ("{} is a prime number...".format(number)) else : print ("{} is not a prime number...".format(number))
true
6dfdf91ffb157d4ee704d4ca63c9065a69cd9768
simsekonur/Python-exercises
/exercise/examples/find_number.py
357
4.125
4
#This function takes a list and return the index of first number in it. if not found, returns -1. def find_the_first_number (lst): i=0 index = -1 while (i<len(lst)): if (type(lst[i])==int or type(lst[i])==float): index = i break i+=1 return index print (find_the_first_number(["a","Onur","*",9,7.6]))
true
61af9a4a4bc10f5302eccb7c6970ad4ae661cdc0
simsekonur/Python-exercises
/exercise/examples/fibonacci_recursion.py
265
4.3125
4
print ("fibonacci sequence : 1 1 2 3 5 ...") number = int (raw_input ("Enter the number:")) def fibonacci (number): if (number == 1 or number == 2): return 1 else : return fibonacci(number-1)+fibonacci (number-2) print (fibonacci (number))
false
0e2c32c19aee4916d1d16505e2d32c7eae2ad2ca
simsekonur/Python-exercises
/breakAndContinue/break.py
356
4.125
4
print ("Before break") for i in range (0,11): print (i) print ("After break") for i in range (0,11): if (i==5): break print (i) lst =[1,2,3,4,5] print ("The list before break") for i in range (0,len (lst)): print (lst[i]) print ("the list after break") for i in range (0,len(lst)): if (i==2): break print (lst[i])
false
174a2dd5e7d251704e7caa3f87637e100fe027ad
DrHIROMU/DataStructure
/Sorting/bubble_sort.py
519
4.1875
4
# Time Complexity: O(n^2) def bubble_sort(numbers): for i in range(len(numbers)-1, 0, -1): for j in range(0, i, 1): if numbers[j] > numbers[j+1]: swap(numbers, j, j+1) return numbers def swap(num_array, index_a, index_b): temp = num_array[index_a] num_array[index_a] = num_array[index_b] num_array[index_b] = temp def main(): nums = [3,4,8,2,1] sorted_numbers = bubble_sort(nums) print(sorted_numbers) if __name__ == '__main__': main()
false
1493c56771300b7432515b186cf62f80cd48bc13
shyam192/project2
/task2.py
406
4.28125
4
#printing positive number in a list List1=[12,-7,5,64,-14] #input list #printing positive numbers: print("POSITIVE NUMBERS IN LIST 1 : ") for number in List1: if number>0: #COMPARING NUMBERS print(number) #list 2 List2=[12,14,-95,3] #input list #printing positive numbers: print("POSITIVE NUMBERS IN LIST 2 : ") for number in List2: if number>0: print(number)
true
c31706e51f25f392ea07fb6329e1dec5132de85f
ianmkinney/python-car
/car.py
2,345
4.21875
4
class car: def __init__(self,company,car,mpg,gasTank): self.company = company self.car = car self.mpg = mpg self.gasTank = gasTank self.milesDriven = 0 self.fill = 0 def takeTrip(self,miles): if(miles > (self.fill * self.mpg)): print("Too far to drive with current gas, please fill up!") else: self.milesDriven = self.milesDriven + miles self.fill = self.fill - (int(miles/mpg)) print(f"Successfully drove {miles} miles. You have {self.milesDriven} on your car.") def fillUp(self, amount): if(amount > (self.gasTank - self.fill)): print("That is too much gas! You overflowed!!") else: self.fill = self.fill + amount print(f"You now have {self.fill} gallons in your tank! You can travel up to {self.mpg * self.fill} miles!") def display(self): print(f"Your {self.company} {self.car} gets {self.mpg} mpg. It can hold up to {self.gasTank} gallons! You have currently driven {self.milesDriven} miles.") if(self.fill == 0): print("You are on empty! Time to fill up!") else: print(f"You have {self.fill} gallons in the tank. You can travel a maximum of {self.fill * self.mpg} miles") company = input("What is the company that made your car?") carModel = input("What is your car model?") mpg = int(input("How many miles per gallon does your car get?")) gasTank = int(input("How many gallons can your tank hold?")) carObj = car(company,carModel,mpg,gasTank) carObj.display() cont = 0 while(cont == 0): print("What would you like to do?") print("1: Check car") print("2: Take Trip") print("3: Fill up") print("4: Stop program") userInput = int(input("Please enter the number of your option:")) if(userInput == 1): carObj.display() if(userInput == 2): print(f"You can travel up to {carObj.mpg * carObj.fill} miles.") distance = int(input("How far would you like to go? (in miles): ")) carObj.takeTrip(distance) if(userInput == 3): amount = int(input("How many gallons would you like to add to the tank?: ")) carObj.fillUp(amount) if(userInput == 4): print("Ok, have a nice day!") cont = 1
true
b4fedf70cc76039262ac96905b6404e448a5dd7a
hussainrifat/Python-Practise
/if else1.py
352
4.15625
4
age=int(input("Enter your age: ")) if age>13 and age<18: print("You are too young") print("Why are you here?") elif age>30 and age<40: print("You are middle age army") elif age==18: print("Perfect! ") elif age<13: print("You are kid") else: print("Hi Grandpa!") age=None print("Value of age is now",age) print(age)
false
d541951232c207a623de7e946bfaa931b5297f24
priyankapatki/D04
/HW04_ch08_ex05.py
1,419
4.125
4
#!/usr/bin/env python # HW04_ch08_ex05 # Structure this script entirely on your own. # See Chapter 8: Strings Exercise 5 for the task. # Please do provide function calls that test/demonstrate your # function. ############################################################################### # Find the ord('a') and ord('z') based on the case of the character c def limit(c): if c.islower(): a = ord('a') z = ord('z') else: a = ord('A') z = ord('Z') return (a, z) def round_off(r): if r < 0: return ((abs(r) % 26) * -1) return (abs(r) % 26) def rotate_word(word, num): new_word = '' num = round_off(num) for c in word: (a, z) = limit(c) nc = ord(c) + num if nc < a: # rotate left nc = z - (a - nc) + 1 elif nc > z: # rotate right nc = a + (nc - z) - 1 new_word += chr(nc) return new_word def main(): print(rotate_word('cheer', 7)) print(rotate_word('melon', -10)) print(rotate_word('CHEER', 7)) print(rotate_word('MELON', -10)) print(rotate_word('abc', 3)) print(rotate_word('abc', -29)) print(rotate_word('ABC', -52)) print(rotate_word('abc', 2)) print(rotate_word('abc', -3)) print(rotate_word('abc', 26)) print(rotate_word('abc', 52)) if __name__ == '__main__': main()
true
6e27999a74e944e99eb83262e45e538124292ace
madhank93/python_code_academy
/Find_odd_one_out.py
1,139
4.53125
5
'''Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number. ! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0) Examples : iq_test("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even iq_test("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd''' #Solution: def iq_test(numbers): res = numbers.split() list = map(int, res) even_flag = 0 odd_flag =0 for num in list: if num % 2 == 0: even_flag += 1 even_pos = list.index(num) + 1 else: odd_flag +=1 odd_pos = list.index(num) + 1 if even_flag == 1: return even_pos else: return odd_pos
true
1ec2a390b5df4bccbcc4589fab4151d76144aa24
chitradhak/Python-code
/exercises.py
1,851
4.1875
4
# Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. from datetime import date ''' x = raw_input("Enter your name: ") y = input("Enter your age: ") z = input("Enter current age year: ") actualyear = (x + ' will turn 100 in year ' + str( z + 100 - y) + '\n' ) print actualyear ''' ############################################################################################ # even / odd number ''' num1 = input("Enter num 1: ") def even_odd(num1): if num1 % 4 == 0: print ("Number is divisble by 4") elif num1 % 2 == 0: print ("Number is not prime") else: print("This is a prime number") even_odd(num1) ''' ############################################################################################ # write a program that prints out all the elements of the list that are less than 5. ''' l1 = [56,1,3,8,3,4,10,16,17,80,0.5,5] l2 = [] l1_len = len(l1) print l1_len for i in l1: if i <= 5: l2.append(i) print l2 ''' ############################################################################################ # palindrome or not. ''' def palindrom_string(): x = raw_input("Enter string: ") z = x[::-1] if x == z: print "String is palindrome" else: print "String is not palindrome" def palindrom_number(): num = input("Enter num: ") sum1=0 n=num while num!=0: rem=num%10 sum1=sum1*10+rem num=num/10 if sum1==n: print "Number is palindrome" else: print "Number is not palindrome" palindrom_string() palindrom_number() ''' ############################################################################################ #append tuple indirectly a = ('2',) items = ['o', 'k', 'd', 'o'] l = list(a) for x in items: l.append(x) print tuple(l)
true
428d708c8394181c863374547677b57489fcc3d8
Zoogster/python-class
/Lab 3/Lab03P3.py
747
4.125
4
delivery_type = input( 'Please enter the type of shipping you would like. For standard please enter put an "S". For express please enter an "E". ') delivery_type = delivery_type.upper() weight = float(input('Please enter weight of package in pounds: ')) if delivery_type == 'S': if weight > 4 and weight <= 8: rate = 1.05 elif weight > 8 and weight <= 15: rate = 0.85 elif weight > 15: rate = 80 if delivery_type == 'E': if weight <= 2: rate = 3.25 elif weight > 2 and weight <= 5: rate = 2.95 elif weight > 5 and weight <= 10: rate = 2.75 elif weight > 10: rate = 2.55 shipping_charge = rate * weight print('The shipping charge will be: $', shipping_charge)
true
068b2ceee247c1790fdbdf9d3dc9464d58a30b36
shreyasabharwal/Data-Structures-and-Algorithms
/Trees/4.4CheckBalanced.py
1,242
4.1875
4
'''4.4 Check Balanced: Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. ''' import math from TreesBasicOperations import Node def checkHeight(root): # base case if root is None: return -1 leftHeight = checkHeight(root.left) rightHeight = checkHeight(root.right) heightDiff = abs(leftHeight-rightHeight) if heightDiff > 1: return math.inf else: return max(leftHeight, rightHeight)+1 def checkBalanced(root): if checkHeight(root) != math.inf: return True else: return False if __name__ == "__main__": # check for balanced tree new_node = Node(40) new_node.insert(60) new_node.insert(10) new_node.insert(5) new_node.insert(15) new_node.insert(45) print(checkBalanced(new_node)) # check for unbalanced tree node1 = Node(1) node1.left = Node(2) node1.left.left = Node(3) node1.left.left.left = Node(4) node1.right = Node(2) node1.right.right = Node(3) node1.right.right.right = Node(4) print(checkBalanced(node1))
true
c51551bad30d058c4c9836e68c24db8f06904fb1
shreyasabharwal/Data-Structures-and-Algorithms
/Sorting/10.5SparseSearch.py
1,896
4.21875
4
'''10.5 Sparse Search: Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string. EXAMPLE Input: ball, ['at', '', '', '', '', 'ball', '', '', 'car', '', '', 'dad', '', ''] Output: 4 ''' '''Approach: With empty strings interspersed, we can implement a simple modification of binary search. All we need to do is fix the comparison against mid, in case mid is an empty string. We simply move mid to the closest non-empty string. Careful consideration should be given to the situation when someone searches for the empty string. Should we find the location (which is an O( n) operation)? Or should we handle this as an error? ''' def search(l_string, string): # if string is empty, return -1. Ask interviewer if this is to be considered as an eror. if not string: return -1 return sparseSearch(l_string, string, 0, len(l_string)-1) def sparseSearch(l_string, string, first, last): mid = (first+last)//2 if string == l_string[mid]: return mid if last < first: return -1 if not l_string[mid]: left = mid-1 right = mid+1 while(True): if right <= last and l_string[right]: mid = right break elif left >= first and l_string[left]: mid = left break else: return -1 right += 1 left -= 1 if string == l_string[mid]: return mid elif string < l_string[mid]: # search left return sparseSearch(l_string, string, first, mid-1) else: return sparseSearch(l_string, string, mid+1, last) if __name__ == "__main__": l_string = ['at', '', '', '', '', 'ball', '', '', 'car', '', '', 'dad', '', ''] string = 'dad' print(search(l_string, string))
true
341087e1d6ee4615944a3875d945152fd72c50a0
shreyasabharwal/Data-Structures-and-Algorithms
/Trees/104.maxDepthOfTree.py
905
4.125
4
'''104. Maximum Depth of Binary Tree Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3.''' from TreesBasicOperations import Node class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 depth = 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) return depth if __name__ == "__main__": new_node = Node(3) new_node.left = Node(9) new_node.right = Node(20) new_node.right.left = Node(15) new_node.right.right = Node(7) obj = Solution() print(obj.maxDepth(new_node))
true
1b553feabb6716007fff893cb537511e128cf37d
shreyasabharwal/Data-Structures-and-Algorithms
/Arrays and Strings/1.6stringCompression.py
1,028
4.5625
5
''' 1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters(a - z). ''' import sys def string_compression(string): compressed = [] count = 1 for i in range(len(string)-1): if string[i] == string[i+1]: count += 1 else: compressed.append(string[i]+str(count)) count = 1 # appending last character compressed.append(string[-1] + str(count)) compressed = ''.join(compressed) # if counts of all characters are one, len(compressed)=2*len(string) if len(compressed) == 2*len(string): return string return compressed if __name__ == "__main__": string = sys.argv[1] print(string_compression(string))
true
74377e208b8fbcdeda031f15187c3cb0feabcbaa
shreyasabharwal/Data-Structures-and-Algorithms
/Arrays and Strings/CaesarCipher.py
1,149
4.5625
5
'''A Caesar Cipher is a simple and ancient encryption technique. It works by taking the a string of text and "rotating" each letter a fixed number of places down the alphabet. Thus if the "rotation" number is "3", then a A (the 1st letter) would become a D (the 4th), a B would become a E, and a Z would wrap around to become a C. Define a method rotate_text() that takes in two arguments: a string to encrypt and a number of places to shift each letter. The method should return an "encrypted" version of the string, with each letter shifted the appropriate amount. Note that this method can also be used to "decrypt" text by shifting in the opposite direction (e.g., a negative amount).''' def rotate_text(string, num): res = "" for char in string: if char.isalnum(): if char.isupper(): res += (chr((ord(char)+num-65) % 26+65)) else: res += (chr((ord(char)+num-97) % 26+97)) else: res += char return res if __name__ == "__main__": print(rotate_text('This is a programming class', 5)) print(rotate_text('YMNX NX F UWTLWFRRNSL HQFXX', -5))
true
9a608ee9f7632e06a129d6f8736588f52e539733
shreyasabharwal/Data-Structures-and-Algorithms
/LinkedList/2.6Palindrome.py
1,256
4.34375
4
'''2.6 Palindrome: Implement a function to check if a linked list is a palindrome. ''' # Node Insertion from NodeInsertion import Node, LinkedList def printElements(current): "Print elements of the linked list" while current: print(current.data, end='\t') current = current.next def reverse(node): head = None while(node): newNode = Node(node.data) newNode.next = head head = newNode node = node.next return head def isEqual(nodel1, nodel2): while nodel1 and nodel2: if nodel1.data != nodel2.data: return False nodel1 = nodel1.next nodel2 = nodel2.next return True def isPalindrome(headNode): reversed = reverse(headNode) return isEqual(headNode, reversed) if __name__ == "__main__": # Creating nodes node1 = Node("3") node2 = Node("5") node3 = Node("8") node4 = Node("9") node5 = Node("8") node6 = Node("5") node7 = Node("3") node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.next = node7 # Creating Linkedlist ll = LinkedList(node1) ll.printElements() print('\n') print(isPalindrome(ll.head))
true
fc9ca462b12da7ee144f8e2b62e950ce9d13f664
skimaiyo16/andela-bc-5
/listtest.py
600
4.28125
4
def find_missing(n, m): ''' find which elements are missing from a list ''' # check if both are empty if m == [] and n == []: return 0 #sort first to allow index comparison m.sort() n.sort() if len(m) > len(n): lst = [ x for x in m for y in n if x not in n] return lst[0] else: lst = [ x for x in n for y in m if x not in m] return lst[0] print find_missing([],[]) print '----------------------------------' print find_missing([1,2,3],[1,3,5,2]) print '----------------------------------' print find_missing([1,3,5,2], [1,2,3])
false
b06ceb8811ce508995dda589ff7e6c428a7fe79c
akmalist/Turtle_Racing_Game
/main.py
1,508
4.21875
4
from turtle import Turtle, Screen import random screen = Screen() screen.setup(500, 400) user_bet = screen.textinput(title = 'Make your bet', prompt='Which turtle will win the race? Enter Color: ') colors = ['red', 'yellow', 'blue', 'green', 'purple', 'pink'] all_turtles = [] start = -70 for each_turtle in range(0, 6): new_turtle = Turtle('turtle') new_turtle.penup() new_turtle.goto(-230, start) start += 30 new_turtle.color(colors[each_turtle]) all_turtles.append(new_turtle) if user_bet: gameOn = True while gameOn: for each_turtle in all_turtles: if each_turtle.xcor() > 230: gameOn = False winning_color = each_turtle.pencolor() if winning_color == user_bet: print(f"You've won! The {winning_color} turtle is the winner") else: print(f"You've lost! The {winning_color} turtle is the winner") random_move = random.randint(0, 10) each_turtle.forward(random_move) # def move_forward(): # tim.forward(15) # # # def move_backwards(): # tim.backward(20) # # def move_counter(): # tim.left(20) # # def move_clock(): # tim.right(20) # # def clean(): # tim.clear() # tim.reset() # tim.home() # # screen.listen() # screen.onkey(key="w", fun=move_forward) # screen.onkey(key='s', fun=move_backwards) # screen.onkey(key="a", fun=move_counter) # screen.onkey(key='d', fun=move_clock) # screen.onkey(key='c', fun=clean) screen.exitonclick()
true
1ad193d77376d1506bf45c17890af109dff3020e
TheTonyKano/Side-Projects
/palindrome.py
328
4.28125
4
def isPalindrome(string): revString = ''.join(reversed(string)) if string.replace(" ", "") == revString.replace(" ", "") and string.replace(" ", "") != "": print("It's a Palindrome") else: print("It's not a Palindrome") isPalindrome(str(input("Enter a word to see if it is a palindrome: ")).lower())
true
b3fb1f82e9974d7729616adbdcb1c5d8b970b08e
TheTonyKano/Side-Projects
/improved_caesar_cypher.py
1,226
4.125
4
data = str(input("Enter text to be encrypted: ")) def encryptdata(string, shift): code = "" cypher = '' for char in string: code = ord(char) + shift if char.isalpha(): if ord(char) <= 90 and ord(char) >= 65: if code > 90 and code < 121: phase = 64 + (shift - (90 - (code - shift))) cypher += chr(phase) else: cypher += chr(code) elif ord(char) <= 122 and ord(char) >= 97: if code > 122: phase = 96 + (shift - (122 - (code - shift))) cypher += chr(phase) else: cypher += chr(code) else: cypher += chr(code) elif char == chr(32): cypher += chr(32) elif char.isdigit(): cypher += char else: cypher += char return cypher def shiftVerification (): shift = int(input("Enter value to shift by (1 to 25): ")) if shift > 0 and shift < 26: return shift else: shiftVerification() print(encryptdata(data, shiftVerification ()))
false
660bb04aed0a39f5188c37663f585c9c9059cc0a
trent-hodgins-01/ICS3U-Unit4-02-Python
/multiplication_loop.py
978
4.53125
5
# !/user/bin/env python3 # Created by Trent Hodgins # Created on 09/29/2021 # This is the Multiplication Loop program # The user enters in a positive integer # The program tells the user the product the numbers from 1 to the number typed in import math def main(): # this function uses a while loop and calculates the product loop_counter = 0 answer = 1 # input number_as_string = input("Enter in a positive integer: ") print("") # process and output try: number_as_integer = int(number_as_string) while loop_counter < number_as_integer: loop_counter = loop_counter + 1 answer = answer * loop_counter print( "The product of all the positive numbers from 1 to {0} is {1}".format( number_as_string, answer ) ) except Exception: print("You didn’t enter in a positive integer.") print("\nDone") if __name__ == "__main__": main()
true
0fd3628568032188eed79355e8af4a725e2a5aee
NickStrick/Code-Challenges
/lambda/LinkedListMap.py
2,479
4.125
4
# https://gist.github.com/seanchen1991/a151368df32b8e7ae6e7fde715e44b78 # reduce takes a data structure and either finds a key piece of data or # be able to restructure the data structure # 1. Reduce usually takes a linear data structure (99% we use reduce on an array) # 2. Reduce "aggregates" all of the data in the data structure into one final value # 3. Reduce is extremely flexible with how the reduction actually happens # 3a. Reduce doesn't care how the reduction happens # 4. The "reducer" function that's passed in as input is how we specify how the reduction happens # what's the deal with the anonymous function's parameters? # 1. An aggregator value # 2. The current list node # 3. An optional value the aggregator is initialized with # what happens on a single call of the anonymous function? # how many times does the reducer function get called? Once for every element in our data structure # does the anonymous function do the work of iterating over our data structure? # no, the anonymous function itself doesn't do the work of iterating # Steps for our reduce function # How do all of these calls get aggregated into a single value? # The anonymous function needs to update the aggregated value somehow # where is the state set and how is it defaulted to the head? def linked_list_reduce(head, reducer, init=None): # where/when do we initialize the state? # initialize state before we start looping state = None # what do we do when the init value is set? if init != None: state = init # what do we do when the init value is None? elif state is None: # set the state to be the first value in our list state = head.value # move the head to the next list node head = head.next # 1. Loop over the data structure current = head while current: # 2. Call our anonymous function on the current iteration value # 3. Update our state to be the result of the anonymous function state = reducer(state, current.value) # update our current pointer current = current.next # 4. Return the final aggregated state return state class Node: def __init__(self, value, next=None): self.value = value self.next = next l1 = Node(4) l2 = Node(7) l3 = Node(15) l4 = Node(29) l5 = Node(5) l1.next = l2 l2.next = l3 l3.next = l4 l4.next = l5 def reducer(x, y): return x - y print(linked_list_reduce(l1, reducer, 100))
true
8988fd0eeeefa808228835e53227c88e312e2549
OrlandoMatteo/ProgrammingForIot
/Training/Intro/solutions/exercise7.py
631
4.125
4
import random if __name__=="__main__": #Create a vector of random numbers (just to avoid to insert the numbers manually) numbers=[random.randint(1,20) for i in range(16)] #Set the value of the sum to 0 and max and min to the first number of the array sum_of_n=0 l=len(numbers) maximum=numbers[0] minimum=numbers[0] #Add each number to the sum and check if it's the max or the min for n in numbers: sum_of_n+=n if n>maximum: maximum=n if n<minimum: mimnimum=n print(f"The list of numbers is {numbers}") print(f"Average : {sum_of_n/len(numbers)}") print(f"Max : {maximum}") print(f"min : {minimum}")
true
91158a9ac64975fefee6ce03cc9744237e727cd3
abrantesandreza/Exerc-cio-L-gica-de-Programa-o-Construir-triangulos-em-Python
/main.py
744
4.15625
4
print('Vamos representar um triângulo? ') print('Obs: Nenhum valor pode ser 0, tá bom?') lado1 = int(input('Escreva um valor para um lado do triângulo: ')) lado2 = int(input('Escreva um valor para um lado do triângulo: ')) lado3 = int(input('Escreva um valor para um lado do triângulo: ')) if (lado1 == lado2 == lado3): print('Acabamos de construir um Triângulo Equilátero!! Parabéns!!') elif (lado1 == lado2) or (lado2 == lado3) or (lado1 == lado3): print('Acabamos de construir um Triângulo Isósceles!!Uhuuu!') elif (lado1 != lado2 != lado3): print('Acabamos de construir um Triângulo Escaleno!! Uhuuu!') else: print('Não conseguimos construir um triângulo por enquanto, vamos tentar novamente!!')
false
4dc4228940deda83f59940020dfbd84b3848cc9a
mileidicabezas/python-scripting
/multiples-of-a-number/multiples_of_a_number.py
485
4.15625
4
#!/usr/bin/env python3 # permisopns to run the script: chmod u+x multiples_of_a_number.py # run script: ./multiples_of_a_number.py ''' Task: Write a script that prints the multiples of 7 between 0 and 100. Print one multiple per line and avoid printing any numbers that aren't multiples of 7. Remember that 0 is also a multiple of 7. ''' def multiples_of_a_number(): for x in range(0,100): if x % 7 == 0 and x < 100: print(x) multiples_of_a_number()
true
256ed42c812e891d977a0fdcfc2f76427aea48db
pedroschmid/three-ways-external-merge-sort
/src/sorts.py
1,185
4.125
4
def merge_sort(array): if len(array) > 1: left_array = array[:len(array) // 2] right_array = array[len(array) // 2:] merge_sort(left_array) merge_sort(right_array) left_array_element = 0 right_array_element = 0 merged_array_element = 0 while left_array_element < len(left_array) and right_array_element < len(right_array): if left_array[left_array_element] < right_array[right_array_element]: array[merged_array_element] = left_array[left_array_element] left_array_element += 1 else: array[merged_array_element] = right_array[right_array_element] right_array_element += 1 merged_array_element += 1 while left_array_element < len(left_array): array[merged_array_element] = left_array[left_array_element] left_array_element += 1 merged_array_element += 1 while right_array_element < len(right_array): array[merged_array_element] = right_array[right_array_element] right_array_element += 1 merged_array_element += 1
false
45ac177301fc72b07d41f833f7992aea1589f64c
expoashish/Data-structure-with-python
/bubble.py
392
4.25
4
# Bubble Sort is a simple algorithm which is used to sort a given # set of n elements provided in form of an array with n number of # elements. Bubble Sort compares all the element one by one and sort # them based on their values. data=[3,5,2,0,4] for i in range(len(data)): for j in range(0,len(data)-1): if (data[j]>data[j+1]): (data[j],data[j+1])=(data[j+1],data[j]) print(data)
true
d17b8c9f674bf72ba05ffd3228b095a2f9b4625c
AaronEvanovich/practicepythonPractices
/reverse_word_order.py
983
4.34375
4
#==================== #Input a sentence and reverse it as the output #==================== sentenceList = [] reverseSentenceList = [] #function to split a string into a list of words def splitSentence(oriSentence): global sentenceList sentenceList = oriSentence.split(" ") #function to reverse the list def reverse(sentenceList): global reverseSentenceList #for i in range(len(sentenceList)-1,-1,-1): #reverseSentenceList.append(sentenceList[i]) #OR for i in reversed(sentenceList): reverseSentenceList.append(i) #main function #reveive a sentence as a string from user oriSentence = raw_input("Please enter a sentence:") ###DEBUGGING### oriSentence = "This is freaking awesome" splitSentence(oriSentence) ###DEBUGGING### print sentenceList reverse(sentenceList) ###DEBUGGING### print reverseSentenceList #convert the list back to a string reverseSentence = " ".join(reverseSentenceList) print reverseSentenceList print reverseSentence
true
3a3a089a365ddafaab4b342faca7d84bb601366f
ningmengpian/algorithm
/plus_one.py
1,382
4.15625
4
""" question: 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。 你可以假设除了整数 0 之外,这个整数不会以零开头。 链接:https://leetcode-cn.com/problems/plus-one example: 输入: [1,2,3] 输出: [1,2,4] 解释: 输入数组表示数字 123。 输入:[999] 输出:[1000] 解释:输入数组表示数字 999。 """ class Solution(object): def plusOne(self, digits): """ :param digits: List[int] :return: List[int] """ # 注意最高位满十需自行添加数组空间并置一 digits_len = len(digits) carry_flag = 0 for index in range(digits_len-1, -1, -1): now_digits_val = digits[index] + 1 if now_digits_val == 10: digits[index] = 0 carry_flag = 1 else: digits[index] = now_digits_val carry_flag = 0 if carry_flag == 0: break if carry_flag == 1 and index == 0: return [1] + digits return digits if __name__ == "__main__": test_digits = [9] solution = Solution() result = solution.plusOne(test_digits) print(result)
false
2d4fea4fae212d82d9caae12fd0dfc3163c428d3
ningmengpian/algorithm
/order_linked_list.py
1,676
4.21875
4
""" 合并有序链表 question: 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 examples: 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 """ class ListNode: def __init__(self, x): self.val = x self.next = None def create_link_list(list_number): link_list = ListNode(0) now_node = link_list for temp in list_number: new_node = ListNode(temp) now_node.next = new_node now_node = new_node return link_list.next class Solution: def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: l1_now_node = l1 l2_now_node = l2 result = ListNode(0) now_node = result while (l1_now_node is not None) and (l2_now_node is not None): if l1_now_node.val < l2_now_node.val: now_node.next = l1_now_node now_node = l1_now_node l1_now_node = l1_now_node.next else: now_node.next = l2_now_node now_node = l2_now_node l2_now_node = l2_now_node.next if l1_now_node is None: now_node.next = l2_now_node else: now_node.next = l1_now_node return result.next if __name__ == '__main__': l1 = [1, 2, 3, 4] l2 = [2, 3, 4, 5, 6, 7] l1_link_list = create_link_list(l1) l2_link_list = create_link_list(l2) link_list = Solution() re = link_list.merge_two_lists(l1_link_list, l2_link_list) now_node = re while now_node: print(now_node.val) now_node = now_node.next
false
3da0e973cb58a2625b015ac9a0389f7a489326b8
mitcns/python
/sequence-chapter6/uniFile.py
419
4.125
4
# coding=utf-8 # !/usr/bin/env python ''' An example of reading & writing Unicode strings: Writes a Unicode string to afile in utf-8 & reads it back in. ''' CODEC = 'utf-8' FILE = 'unicode.txt' helloOut = u"你好,小马!\n" bytesOut = helloOut.encode(CODEC) f = open(FILE, "w") f.write(bytesOut) f.close() f = open(FILE, 'r') bytesIn = f.read() f.close() helloIn = bytesIn.decode(CODEC) print helloIn,
true
335f2429dd0229d921ce8689ec009891c6860f68
Hammad214508/Quarantine-Coding
/30-Day-LeetCoding-Challenge/September/Week2/9-CompareVersionNumbers.py
2,254
4.25
4
""" Given two version numbers, version1 and version2, compare them. Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1. Return the following: If version1 < version2, return -1. If version1 > version2, return 1. Otherwise, return 0. Example 1: Input: version1 = "1.01", version2 = "1.001" Output: 0 Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1". Example 2: Input: version1 = "1.0", version2 = "1.0.0" Output: 0 Explanation: version1 does not specify revision 2, which means it is treated as "0". Example 3: Input: version1 = "0.1", version2 = "1.1" Output: -1 Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2. Example 4: Input: version1 = "1.0.1", version2 = "1" Output: 1 Example 5: Input: version1 = "7.5.2.4", version2 = "7.5.3" Output: -1 Constraints: 1 <= version1.length, version2.length <= 500 version1 and version2 only contain digits and '.'. version1 and version2 are valid version numbers. All the given revisions in version1 and version2 can be stored in a 32-bit integer. """ class Solution: def compareVersion(self, version1, version2): s1 = [int(i) for i in version1.split(".")] s2 = [int(i) for i in version2.split(".")] l1, l2 = len(s1), len(s2) if l1 < l2: s1 += [0]*(l2-l1) else: s2 += [0]*(l1 - l2) return (s1 > s2) - (s1 < s2)
true
58c9a05a936f62ad8cf6d552880268738ee23019
Hammad214508/Quarantine-Coding
/30-Day-LeetCoding-Challenge/August/Week1/1-DetectCapital.py
1,462
4.34375
4
""" Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital, like "Google". Otherwise, we define that this word doesn't use capitals in a right way. Example 1: Input: "USA" Output: True Example 2: Input: "FlaG" Output: False Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. """ class Solution: def detectCapitalUse(self, word: str) -> bool: n = len(word) match1, match2, match3 = True, True, True # case 1: All capital for i in range(n): if not word[i].isupper(): match1 = False break if match1: return True # case 2: All not capital for i in range(n): if word[i].isupper(): match2 = False break if match2: return True # case 3: All not capital except first if not word[0].isupper(): match3 = False if match3: for i in range(1, n): if word[i].isupper(): match3 = False if match3: return True # if not matching return False
true
50fbe087f52cd05c43e5df3b8d30f989ea751870
maverick317/python-projects
/Guess_The_Number.py
719
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 13 11:06:57 2019 @author: Maverick """ #Guess The Number #import the necessary libraries import random as rd #generate random numbers choice = rd.randint(1,10) #ask the user for their input number = int(input("Please enter a random number between 1 and 10: ")) if number > 10: print("Please enter a number between 1 and 10") else: print("This is the number you have entered: ",number) #compare the number with the random numner if choice == number: print("You have guessed the correct number !!!") else: print("You have guessed the wrong number !!!") #print both the numbers print("You have guessed:",number) print("The correct choice is:",choice)
true
158eb7e628e612813380d86bac95160c7628eea1
Jenychen1996/Basic-Python-FishC.com
/File/write_file.py
398
4.1875
4
#!/usr/local/bin/env python3 """ 1. Type the file name 2. Type the content """ def write_file(file_name): f = open("file_name", 'w') print("Please type the content, and type the ':w' to save and exit.") while True: content = input() if content != ":w": f.write('%s\n' % content) else: f.close() break file_name = input("Please type the file name:") write_file(file_name)
true
56b903d82840931f50aca4f2b2df7feef9e3c839
LiliiaPav/learnPython
/Queue.py
1,069
4.40625
4
class Queue(object): """ Queues are a fundamental computer science data structure. A queue is basically like a line at Disneyland - you can add elements to a queue, and they maintain a specific order. When you want to get something off the end of a queue, you get the item that has been in there the longest (this is known as 'first-in-first-out', or FIFO).""" def __init__(self): """ initialize Queue """ self.values = [] def insert(self, elem): """inserts one element in your Queue""" self.values.append(elem) def remove(self): """removes (or 'pops') one element from your Queue and returns it. If the queue is empty, raises a ValueError.""" try: return self.values.pop(0) except: raise ValueError('Queue is empty') def __str__(self): """Returns a string representation of self""" return '{' + ','.join([str(e) for e in self.values]) + '}' queue = Queue() queue.insert(5) queue.insert(6) print queue queue.remove() print queue
true
4c87149ce7a6196a161e5e50240f39341518761b
momentum-cohort-2019-05/w2d1-house-hunting-radfordalex
/house_hunting.py
564
4.25
4
annual_salary = float(input("What is your annual salary?")) portion_saved = float(input("What portion of your salary are you saving")) total_cost = float(input("What is the cost of your house")) monthly_salary = annual_salary/12 r = 0.04 current_savings = 0 months = 0 portion_down_payment = total_cost*0.25 while current_savings < portion_down_payment: monthly_additions = portion_saved*monthly_salary + current_savings*r/12 current_savings = current_savings + monthly_additions months += 1 print(current_savings) print(months)
true
a7f94c1f3c546691c9bd7706d694fe537b2a9a42
python-code-assignment/Aastha-Vidushi
/recursive.py
609
4.15625
4
def removeNone(dictionary): for k, v in dictionary.items(): if isinstance(v, dict): removeNone(v) elif (v==None): dictionary.pop(k) return dictionary Dict = { 'Dict1': {'name': 'Ali', 'age': 19,'mob':123456}, 'Dict2': {'name': 'Bob', 'age': 22,'mob':123789}, 'Dict3':{'name': 'Cam', 'age': 41,'mob':None}, 'Dict4':{'name': 'Dan', 'age': 44,'mob':None}, 'Dict5':{'name': 'Eak', 'age': 15,'mob':456987}, 'Dict0':[] } if __name__=='__main__': res=removeNone(Dict) print (res)
false
537f22d10d805b252c0a8075902f84c337325d43
JeniMercy/code
/Nov21Task3.py
959
4.25
4
#NOV-21 #Task3: #collect one string from user, check whether the string is palindrome or not a = str(input("Please enter your string : ")) reversed_string = a[::-1] if a == reversed_string: print(" The string {} is a palindrome".format(a)) else: print("The string {} is not a palindrome".format(a)) """OUTPUT: = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21Task3.py Please enter your string : MoM The string MoM is a palindrome = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21Task3.py Please enter your string : Mom The string Mom is not a palindrome = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21Task3.py Please enter your string : niralya The string niralya is not a palindrome = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21Task3.py Please enter your string : 1234321 The string 1234321 is a palindrome"""
false
ab264107d88e3acbb02db59d459d21c008c9576e
JeniMercy/code
/November18-Tasks(Tuple).py
1,336
4.15625
4
#November Tasks-18 #Tuple #Create two tuples (1,4,5,6,7,8) (5,6,7,8,9) tuple1 = (1,4,5,6,7,8) tuple2 = (5,6,7,8,9) print(tuple1) print(tuple2) #Find the common elements between two tuples #tuple1 = (1,4,5,6,7,8) #tuple2 = (5,6,7,8,9) set1 = set(tuple1) set2 = set(tuple2) set_inter = set1.intersection(set2) print(tuple(set_inter)) '''OUTPUT = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/November18-Tasks.py (8, 5, 6, 7) ''' #Concatenate both tuples and remove duplicates from tuple #tuple1 = (1,4,5,6,7,8) #tuple2 = (5,6,7,8,9) tup = (tuple1 +tuple2) print(tup) print(tuple(set(tup))) '''OUTPUT = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/November18-Tasks.py (1, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9) (1, 4, 5, 6, 7, 8, 9)''' #Find the index value of 9 (after concatenation) #tup = (1, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9) print(tup.index(9)) '''OUTPUT = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/November18-Tasks.py 10''' #multiply above elements 3 times #tup = (1, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9) newtuple = tup*3 print(newtuple) '''OUTPUT = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/November18-Tasks.py (1, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9, 1, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9, 1, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9)'''
true
ded442ef12dcde0edd0429098374343ebb6af376
JeniMercy/code
/Nov21task5.py
891
4.3125
4
#Nov21 #Task5: #Get one string from user #Find the middle letter #find ascii value for the middle letter #check whether ascii value is odd or even a = input("Please enter your string : ") middle_letter = len(a) // 2 print("The middle letter is {}".format(a[middle_letter])) ascii_value = ord(a[middle_letter]) #print("The ascii value of middle_letter is {}".format(ascii_value)) print("The middle letter of {} is {} and its ascii_value {} " .format(a,a[middle_letter],ascii_value)) '''OUTPUT: = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21task5.py Please enter your string : niralya The middle letter is a The ascii value of middle_letter is 97 = RESTART: C:/Users/Admin/AppData/Local/Programs/Python/Python310/Nov21task5.py Please enter your string : mercy The middle letter is r The ascii value of middle_letter is 114 '''
true
01a97c6b3e39d19d0f22e1e213cfe8865f1a6566
MagneeR/CursoLeonEoiPythonDjango
/python/7_listas.py
1,210
4.53125
5
"""Ejemplos para trabajar con listas ctrl+f2 sobre un nombre me deja cambiar ese nombre en todo el documento """ #En minuscula no se puede poner list porque es una palabra reservada de python LIST = [1, 2, 3, 4, 5, "seis"] #Las listas son como arrays y en la consola se ve como array print(LIST) print(LIST[0]) #Asi muestra lo que hay en la posicion que le de print(LIST[4]) print(LIST[2:5]) #Muestro los valores desde la posicion 2 hasta la 5 sin incluirla #pero se ve como un array print(LIST[:3]) print(LIST[2:]) size = len(LIST) print('Tamaño de la lista:', size) del LIST[2] #Borro el elemento de la lista que yo diga print(LIST) LIST[2] = 'tres' #Modifico un valor de la lista print(LIST) #Concatenar dos listas LIST2 = ['siete', 8 , True, False] LIST += LIST2 print(LIST) #Añadir elemento a la lista LIST.append('elemento nuevo') print(LIST) LIST.remove('seis') #Borro un elemento segun su valor print(LIST) LIST.reverse() #Da la vuelta a la lista (lo del final al principio) print(LIST) LIST.insert(1, 'PC') #Crea un elemento que yo le pase en la posicion que elija #insert(posicion en la que quiero meter el valor, valor que quiero añadir) print(LIST)
false
4d580db7d455b1a5b4e79049e765751ebf245695
farah-ehsan-alyasari/Problem-Solving
/is_palindrome.py
1,447
4.25
4
''' Scenario Do you know what a palindrome is? It's a word which look the same when read forward and backward. For example, "kayak" is a palindrome, while "loyal" is not. Your task is to write a program which: asks the user for some text; checks whether the entered text is a palindrome, and prints result. Note: assume that an empty string isn't a palindrome; treat upper- and lower-case letters as equal; spaces are not taken into account during the check - treat them as non-existent; there are more than a few correct solutions - try to find more than one. Test your code using the data we've provided. Test data Sample input: Ten animals I slam in a net It's a palindrome Sample input: Eleven animals I slam in a net It's not a palindrome ''' def is_palindrome_v1(strng): n = len(strng) is_palindrome = True for i in range(n): if strng[i] != strng[n-1-i]: is_palindrome = False return is_palindrome def is_palindrome_v2(strng): is_palindrome = False # check if the word is equal to its reversed if strng.lower() == strng[::-1].lower(): is_palindrome = True return is_palindrome try: strng = input("Give me a string: ") strng = strng.replace(" ", "").upper() print(is_palindrome_v1(strng)) print(is_palindrome_v2(strng)) except BaseException as e : print("Note: ", e)
true
0ea06231dcc71065d5574582bb4c554b524595b2
adamabusamra/python_prep
/python_prep/OOP/classes+instances.py
1,146
4.34375
4
# Defining a class class Employee: # This is a constructor in Python & it's called once an object is instantiated from this class. def __init__(self,name,age): # The self keyword is a refrence to (this) specific Object like this in other langs. self.name = name self.age = age # These are just like getters and setters in other OOP langs. def get_name(self): # Instead of | employee1 = Employee() ; ## employee1.name ## we say ## employee1.get_name() ## return self.name def set_name(self,name): # Instead of | employee1 = Employee() ; ## employee1.name = adam ## we say ## employee1.set_name("adam") ## return self.name def get_age(self): return self.age def set_age(self,age): return self.age # Instantiating an object from our Employee class employee1= Employee("Adam",19) # Setting using 2 ways / 1- Setting the attribute / 2- Using the setter method employee1.name = "Abusamra" employee1.set_name("Abusamra") # Getting using 2 ways / 1- accessing the attribute / 2- using the getter method print(employee1.get_name()) print(employee1.name)
true
df2e672c2797b2133e6272709c6bfa0c42d36575
kdockman96/CS0008-f2016
/Ch2-Ex3/ch2-ex3.py
366
4.21875
4
# This program calculates the number of acres in a tract of land # Get the number of square meters in a tract of land square_feet = int(input("How many square meters are in this tract of land? ")) # Calculate the size of the land in acres land_size = square_feet/4046.8564224 # Display the result print ("That's equal to " + format(land_size, '.2f') + " acres.")
true
df47e940dfc3b48f172226274ce226f37a1cb05e
kdockman96/CS0008-f2016
/Ch3-Ex/ch3-ex2.py
666
4.40625
4
# Ask the user for the lengths and widths of two rectangles length_1 = int(input('Enter the length of rectangle 1: ')) width_1 = int(input('Enter the width of rectangle 1: ')) length_2 = int(input('Enter the length of rectangle 2: ')) width_2 = int(input('Enter the width of rectangle 2: ')) # Display the formula for the area of a rectangle area_1 = length_1 * width_1 area_2 = length_2 * width_2 # Create an IF-ELSE statement that tells the user which # rectangle has the greater area or if the areas are the same. if area_1 > area_2: print('Rectangle 1 has a greater area than rectangle 2.') else: print('The areas of both rectangles are the same.')
true
a2d1083c502e430a975a80190666b3ade660b45b
kdockman96/CS0008-f2016
/Ch2-Ex7/ch2-ex7.py
688
4.34375
4
# Get the number of miles driven on last tank of gas miles = input('How many miles did you drive on the last tank of gas? ') # Get the number of the gallons of gas used gallons = input('How many gallons did you use to fill the gas tank? ') # Calculate MPG where MPG = miles driven/gallons of gas used miles_per_gallon = float(miles)/float(gallons) # Display the result print("You will have gotten", miles_per_gallon, "mpg on your last tank of gas.") # 1 mile = 1.60934 kilometers # Convert miles to kilometers kilometers = miles * 1.60934 #1 gallon = 3.78541 liters # Convert gallons to liters liters = gallons * 3.78541 #Calculate L per 100 km L_per_km = 100 * (liters/kilometers)
true
cf6920019e138bb580c52cd7aeb3db163dc204d8
kdockman96/CS0008-f2016
/ch4-ex/ch4-ex3.py
800
4.25
4
# Ask the user to enter the budget for the month budget = float(input('Enter the amount budgeted for the month: ')) # Initialize an accumulator to keep a running total total_expenses = 0 # Create a variable that will eventually terminate the loop keep_going = 'y' while keep_going == 'y': expense = float(input('How much was the expense? $')) total_expenses += expense keep_going = input('Are there any more expenses? (Enter y for yes.) ') # Display the amount that the user is over or under budget if expense < budget: difference = format(budget - expense, ',.2f') print('You were $', difference, 'under budget.') elif expense > budget: difference = format(budget-expense, ',.2f') print('You were $', difference, 'over budget.') else: print('You are on budget.')
true
ce33cd22609d9e91608005b2fd2ecb0ecfb6f13f
PoisonWater/class-work
/CSC1001/Integration.py
1,269
4.1875
4
from math import sin from math import cos from math import tan try: funcType = input('Which kind of function do you want to integrate? (sin, cos, tan)') while funcType != 'sin' and funcType != 'cos' and funcType != 'tan': print('Please input the correct form of function name!') funcType = input('Which kind of function do you want to integrate? (sin, cos, tan)') nEval = eval(input('Please input an n as the number of sub-intervals into which the interval [a, b] will be divided:')) n = int(nEval) while type(nEval) is float or n <= 0: nEval = eval(input('Please input a positive integer as your n!\nEnter here: ')) n = int(nEval) a = float(input('Please input the lower bond:')) b = float(input('Please input the upper bond:')) sums = 0 if funcType == 'sin': for i in range(1, n+1): sums += (b-a)/n * sin(a + (i-0.5)*(b-a)/n) elif funcType == 'cos': for i in range(1, n+1): sums += (b-a)/n * cos(a + (i-0.5)*(b-a)/n) elif funcType == 'tan': for i in range(1, n+1): sums += (b-a)/n * tan(a + (i-0.5)*(b-a)/n) print('The approximated integral is',sums) except: print('Please input the correct form of inputs.')
true
c90c584e96d35a73f6944c10400b132a1bc4bfc3
Vykstorm/numpy-examples
/printing.py
701
4.5625
5
''' This example shows a few ways to print a numpy ndarray ''' import numpy as np if __name__ == '__main__': # 1D arrays are printed like lists print(np.arange(0, 9)) # 2D arrays are printed as matrices print(np.arange(0, 9).reshape([3,3])) # To print a 2D array as a flat vector... print(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).reshape(9)) print(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).reshape(9, order='F')) # When printing huge arrays, only few items are shown print(np.arange(0, 2500).reshape(50, 50)) # To disable this behaviour, you can do the next: # np.set_printoptions(threshold=np.nan) print(np.arange(0, 2500).reshape(50, 50))
true
f32428eb6c59c9e627541b0dc007c335aa3f8d22
Vykstorm/numpy-examples
/creation.py
2,184
4.21875
4
''' This script shows different ways to create an numpy ndarray object ''' import numpy as np if __name__ == '__main__': # Create an array from a iterable np.array([3,1,4,1,5]) # dtype is guessed from value types np.array([3,1,4,1,5], dtype=np.float64) # dtype can be specified as an argument. # You can create an array from a previous one with different element type... a = np.array([3,1,4,1,5], dtype=np.float64) np.array(a, dtype=np.uint8) a.astype(dtype=np.uint8) # when a list of sublists is specified, the array will have 2 dimensions... np.array([[1,0,0], [0,1,0], [0,0,1]]) # if its a list of sublists of sublits it will have 3, and so on np.array([[ [1,0,0], [0,1,0], [0,0,1]], [ [0,0,1], [0,1,0], [1,0,0] ]]) # This array creation syntax is wrong... try: np.array(1,2,3,4,5) except: pass # You can create your own method to generate a 1D array with that syntax easily... def vector(*args): return np.array(args) assert (vector(1,2,3) == np.array([1,2,3])).all() np.zeros([3,3], dtype=np.uint64) # 3x3 array of zeros np.ones([3,3], dtype=np.uint64) # 3x3 array of ones np.empty([3,3], dtype=np.uint64) # 3x3 array of empty values np.arange(0, 20, dtype=np.uint64) # 1D array with all numbers in [0, 20) np.arange(1, 20, 2, dtype=np.uint64) # 1D array with eveny numbers in [0, 20) # Creates a 1D array with 8 elements equally spaced between the range [0, 7/4 * pi] np.linspace(0, 7 / 4 * np.pi, 8) # = ( 0, pi/4, pi/2, 3pi/4, pi, 5pi/4, 3pi/2, 7pi/4) # Creates a 3x3 array with random values between [0, 1) using a uniform distribution np.random.rand(3, 3) # Creates a 3x3 array with random samples of the normal distribution. np.random.randn(3,3) # Saves an array to a file with open('data.csv', 'w') as file: np.arange(0, 10, dtype=np.uint64).tofile(file, sep=',') # Read array from file with open('data.csv', 'r') as file: np.fromfile(file, sep=',', dtype=np.uint64)
true
95a66e64fc30c2248c60e233b3b3b8b8feba5393
fbreversg/checkio
/Dropbox/the-most-frequent-weekdays.py
851
4.1875
4
from datetime import datetime from calendar import day_name def most_frequent_days(year): """ List of most frequent days of the week in the given year """ firstweek = set(range(datetime(year, 1, 1).weekday(), 7)) # weekday 0..6 lastweek = set(range(datetime(year, 12, 31).isoweekday())) # isoweekday 1..7 return [day_name[day] for day in sorted((firstweek & lastweek) or (firstweek | lastweek))] if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert most_frequent_days(2399) == ['Friday'], "1st example" assert most_frequent_days(1152) == ['Tuesday', 'Wednesday'], "2nd example" assert most_frequent_days(56) == ['Saturday', 'Sunday'], "3rd example" assert most_frequent_days(2909) == ['Tuesday'], "4th example"
true
e9ea7e76b99b19250e38dcd62a21ea64897c9ffd
blsoko/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,404
4.3125
4
#!/usr/bin/python3 '''4-square.py: class square''' class Square: """ Prototype of a square """ def __init__(self, size=0): """[summary] Args: size (int, optional): [size of square]. Defaults to 0. """ '''Define Square instance in size''' self.__size = size def area(self): """[return area of square] Returns: [type]: [int] """ return (self.__size * self.__size) def my_print(self): """ print a square """ if self.__size == 0: print() for j in range(self.__size): for k in range(self.__size): print("#", end='') print() @property def size(self): """[return area of square] Returns: [type]: [int] """ return self.__size @size.setter def size(self, value): """[summary] Args: value (int, optional): [size of square]. Defaults to 0. Raises: TypeError: [size must be >= 0] TypeError: [size must be an integer] """ '''Define Square instance in size''' if (type(value) is int): if (value < 0): raise ValueError("size must be >= 0") else: raise TypeError("size must be an integer") self.__size = value
true
40bd91519789aa478b655afb491c5f327d127265
blsoko/holbertonschool-higher_level_programming
/0x0B-python-input_output/100-append_after.py
747
4.15625
4
#!/usr/bin/python3 """ Write a function that inserts a line of text to a file """ def append_after(filename="", search_string="", new_string=""): """ Write a function that inserts a line of text to a file Args: filename (str): [description]. Defaults to "". search_string (str): [description]. Defaults to "". new_string (str): [description]. Defaults to "". """ with open(filename, "r+", encoding='utf-8') as f: emptystr = "" while True: line = f.readline() emptystr = emptystr + line if not line: break if search_string in line: emptystr = emptystr + new_string f.seek(0) f.write(emptystr)
true
42839964e03f3c355f7a040e86c3e12867921a41
blsoko/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
399
4.125
4
#!/usr/bin/python3 """ Append a file, create a file if it doesn't exist """ def append_write(filename="", text=""): """ Append a file, create a file if it doesn't exist Args: filename (str): file read in mode utf-8. Defaults to "". text (str): text to be written. Defaults to "". """ with open(filename, "a+", encoding="utf-8") as f: return(f.write(text))
true
2c15008df2b04d7c930b3d188238cc9b13dc3e03
jeffreybergman/sql
/sqle.py
319
4.1875
4
# SELECT statement import sqlite3 # create the database connection with sqlite3.connect("new.db") as connection: # create the cursor c = connection.cursor() # use a for loop to iterate the database and print results for row in c.execute("SELECT firstname, lastname FROM employees"): print row
true
3560f0d31ec285d5148ab4472369b9e061055f50
micro-hawk/DevelopersHuntWork
/girish/vowels removing.py
492
4.21875
4
def removevowel(newstr,string): vowels=('a','e','i','o','u','A','E','I','O','U') for c in string: if c in vowels: newstr= newstr.replace(c,'') print("the new string without the vowels is " + newstr) return newstr print("enter any string ou wish to remove the vowels of") string=input("enter any string you want:") if string == "x": exit() else: newstr=string print("we are removing the vowels.........") newstr=removevowel(newstr,string)
false
1ad8d767ef69651ffb1b51c9d7ee19552d369f23
wafindotca/pythonToys
/leetcode/rotate_image.py
1,152
4.125
4
# https://leetcode.com/problems/rotate-image/ # You are given an n x n 2D matrix representing an image. # # Rotate the image by 90 degrees (clockwise). # # Follow up: # Could you do this in-place? # THOUGHTS: neither seems that bad. # Let's start with not-in-place class Solution(object): def rotate(self, matrix): matrix[1][1] = 7 def rotatePixel(i, j): # Split it out by quadrants, do the math return 1,1 # Init matrix newMatrix = [0] * len(matrix) for i in range(len(matrix)): newMatrix[i] = [0] * len(matrix) # Rotate for i in range(len(matrix)): for j in range(len(matrix)): x, y = rotatePixel(i, j) newMatrix[i][j] = matrix[x][y] # Copy over for i in range(len(matrix)): for j in range(len(matrix)): matrix[i][j] = newMatrix[i][j] """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ sol = Solution() matrix = [[1,2],[3,4]] sol.rotate(matrix) print(matrix)
true
93d120d51386895a7e431ced6e84cd670babec98
Lennoard/ifpi-ads-algoritmos2020
/Fabio02_Parte02a/q19_imc.py
664
4.125
4
#19. Leia a altura (em metros) e peso (em Kg) de uma pessoa, em seguida calcule o # índice de massa corpórea (IMC = peso / altura2). # Ao final, escreva se a pessoa está com peso normal (IMC abaixo de 25), # obeso (IMC entre 25 e 30) ou obesidade mórbida (IMC acima de 30). def calcular_imc(h, w): return w / h**2 def main(): altura = float(input('Insira a sua altura (em metros): ')) peso = float(input('Insira o seu peso (em KG): ')) imc = calcular_imc(altura, peso) print(f'\n{imc}') if (imc > 30): print('Obesidade mórbida') elif (imc >= 25): print('Obeso') else: print('Peso normal') main()
false
cce78aed2ce9a025126ad53543a2fba8c64c5b9b
ssharm02/100_days_of_python
/dictionary comprehension/main.py
1,779
4.1875
4
import random import pandas # how to use dictionary comprehension def dictionary_comprehension_test(): names = ["Sarthak", "Buddy", "Sakshi", "Bal", "Neelu", "Dofus"] students_score = {student: random.randint(1, 101) for student in names} print(students_score) def dictionary_comprehension_if_condition(): full_dict = {'Sarthak': 39, 'Buddy': 52, 'Sakshi': 22, 'Bal': 9, 'Neelu': 23, 'Dofus': 77} passed_students = {student: score for (student, score) in full_dict.items() if score > 60} print(passed_students) def dictionary_comprehension_count_letters(): sentence = "What is the Airspeed Velocity of an Unladen Swallow?" count_words = {word: len(word) for word in sentence.split()} print(count_words) def dictionary_temp_conversion(): weather_c = { "Monday": 12, "Tuesday": 14, "Wednesday": 15, "Thursday": 14, "Friday": 21, "Saturday": 22, "Sunday": 24, } converted_temps = {day: (temp * 9/5) + 32 for (day, temp) in weather_c.items()} print(converted_temps) def pandas_dictionary_comprehension(): student_dict = { "student": ["Sarthak", "Buddy", "Sakshi", "Bal", "Neelu", "Dofus"], "score": [99, 93, 64, 77, 98, 0] } student_data_frame = pandas.DataFrame(student_dict) # print(student_data_frame) # Loop through a data frame # for (key, value) in student_data_frame.items(): # print(key, value) # better pandas loop iter rows for (index, row) in student_data_frame.iterrows(): # print(row.student) # print(row.score) if row.student == "Sarthak": print(row.score) pandas_dictionary_comprehension()
false
4d73f8eaa9380e4a23e26a4bcb5ecd938ba3e8d0
emon93/UCD-Work-
/PythonBasics.py
819
4.1875
4
# Create a variable savings savings = 100 # Print out savings print(savings) # Create a variable savings savings = 100 # Create a variable growth_multiplier growth_multiplier = 1.1 # Calculate result result = savings*growth_multiplier**7 # Print out result print(result) # Print type of variable print(type(result)) # Addition, Subtraction print(5 + 5) print(5 - 5) # Multiplication, division, modulo, and exponentiation print(3 * 5) print(10 / 2) print(18 % 7) print(4 ** 2) # How much is your $100 worth after 7 years? print(100*1.1**7) # Sentence with conversion of integer to string print("I started with $" + str(savings) + " and now have $" + str(result) + ". Awesome!") # Definition of pi_string pi_string = "3.1415926" # Convert pi_string into float: pi_float float(pi_string) pi_float = 3.1415926
true
ab86d1898cf79c6a8d5fc8b44c2f07df73fbc779
nileshsinhasinha/Algorithms_and_Datastructure
/Heap.py
2,426
4.125
4
"""Heap is a data structure which is almost complete tree (Either binary or ternary) For Min heap implementation we can directly use heapq library of python Here, we will be implementing Max Heap implementation""" def max_heapify(Arr,node): """It will heapify the tree or subtree of which node will be provided""" #[1,5,6,8,12,14,16] #Indices of array is starting from 0 left_node,right_node=2*node+1,2*node+2 #To find the largest between parent node and left node if (left_node <= len(Arr)-1) and (Arr[left_node]>Arr[node]): largest= left_node else: largest=node #To find out the largest between largest node determined above and right node if (right_node <= len(Arr)-1) and (Arr[right_node]>Arr[largest]): largest= right_node #Swapping between the largest and parent node and calling #max_hapify again to determine the changes in below subtrees if largest != node: Arr[node],Arr[largest]=Arr[largest],Arr[node] max_heapify(Arr,largest) #return Arr def build_max_heap(Arr): heap_size=(len(Arr)-1)//2 for i in range(heap_size,-1,-1): max_heapify(Arr,i) def delete_max_heap_value(Arr): """To delete maximum value from max heap with keeping intact heap property""" if len(Arr)<2: raise ValueError('Head underflow') max,Arr[0] = Arr[0],Arr[len(Arr)-1] Arr.pop() max_heapify(Arr,0) return max def increase_heap_node_value(Arr,node,value): import math """To update the value of a node to the higher value""" if value<Arr[node]: raise ValueError("Value entered is lower than the present index value") Arr[node]=value #print(Arr) while (node>0) and (Arr[math.ceil(node/2)-1]<Arr[node]): Arr[math.ceil(node/2)-1],Arr[node]=Arr[node],Arr[math.ceil(node/2)-1] node=math.ceil(node/2)-1 def insert_heap_node(Arr,value): import math """To insert the new node""" new_node=len(Arr) Arr.append(value) #print(Arr) while (new_node>0) and (Arr[math.ceil(new_node/2)-1]<Arr[new_node]): Arr[math.ceil(new_node/2)-1],Arr[new_node]=Arr[new_node],Arr[math.ceil(new_node/2)-1] new_node=math.ceil(new_node/2)-1 l=[100,99,88,98,97,79,92,96,95,94,93,49,48,39,38] #max_heapify(l,0) build_max_heap(l) # print(l) # #print(delete_max_heap_value(l)) # #increase_heap_node_value(l,5,100) # insert_heap_node(l,35) print(l)
true
e243ad75c09aba332864590b11bb21e91dd8ac0b
nileshsinhasinha/Algorithms_and_Datastructure
/TowerOfHanoi.py
1,182
4.1875
4
"""Tower Of Hanoi:- Here we have to move n discs from source to target using intermediate. Rules to follow:- 1st disc is lightest it can be put on any other disc anytime Last disc is heaviest can be put on base only anytime""" class toh: movements=0 fn_calls=1 def __init__(self,discs,source,target,intmdt): self.discs=discs self.source=source self.target=target self.intmdt=intmdt def tower_of_hanoi(self,discs,source,target,intmdt): if discs>=1: self.fn_calls+=1 self.tower_of_hanoi(discs-1,source,intmdt,target) self.movements+=1 target.append(source.pop()) self.fn_calls+=1 self.tower_of_hanoi(discs-1,intmdt,target,source) if __name__ == "__main__": import random source=[random.randint(1,100) for _ in range(1,11)] source.sort(reverse=True) print(source) discs=len(source) target=[] intmdt=[] toh_3=toh(discs,source,target,intmdt) toh_3.tower_of_hanoi(toh_3.discs,toh_3.source,toh_3.target,toh_3.intmdt) print(target,toh_3.movements,toh_3.fn_calls)
true
03cda6541781523fa4e9b4dbed46f373741a80d2
lxyshuai/target-at-offer
/68.树中连个节点的最低公共祖先.py
1,861
4.21875
4
# coding=utf-8 """ 树种的两个节点的最低公共祖先 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None """ 二叉树是BST """ class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ """ 手画出BST,可以得到规律第一个节点p<=val<=q就是结果 """ def process(root): if root is None: return if p <= root.val <= q: return root else: if root.val < p: return process(root.right) elif root.val > q: return process(root.left) """ 二叉树是普通二叉树 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def __init__(self): # Variable to store LCA node. self.result = None def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ """ 利用先序遍历遍历,在每个节点判断left,right,middle """ def process(root): if root is None: return False left = process(root.left) right = process(root.right) middle = root is p or root is q if left + right + middle == 2: self.result = root return left or right or middle process(root) return self.result
false
1ff42b25a1d604ddb6ec23bb4cb481eec20407b4
EladioDeveloper/ArtificialIntelligence
/Practica 2/Part_I/1.1.py
466
4.34375
4
# 1. Write a Python program to count the number of characters (character frequency) in a string. Sample String : google.com'. Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1} def character_frequency(input): dictionary = {} for n in input: keys = dictionary.keys() if n in keys: dictionary[n] += 1 else: dictionary[n] = 1 return dictionary print(character_frequency('google.com'))
true
f28145e5e3bb9e068961908c68dd04d420bc8c6a
EladioDeveloper/ArtificialIntelligence
/Practica 2/Part_IV/4.47.py
525
4.5
4
# 47. Write a NumPy program to compute the inner product of vectors for 1-D arrays (without complex conjugation) and in higher dimension. import numpy as np a = np.array([1,2,5]) b = np.array([2,1,0]) print("Original 1-d arrays:") print(a) print(b) result = np.inner(a, b) print("Inner product of the said vectors:") x = np.arange(9).reshape(3, 3) y = np.arange(3, 12).reshape(3, 3) print("Higher dimension arrays:") print(x) print(y) result = np.inner(x, y) print("Inner product of the said vectors:") print(result)
true
8fa797f8fe4c032561eb59f7dca525824df51434
oliver-hilder/CP1404_practicals
/prac_02/exceptions_demo.py
1,023
4.5
4
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? A ValueError will occur if either the variable "numerator" or "denominator" receive input that is not an integer. 2. When will a ZeroDivisionError occur? A ZeroDivisionError will occur if the user enters the value "0" into the variable "denominator" 3. Could you change the code to avoid the possibility of a ZeroDivisionError? By changing the "denominator" input to a small while loop to avoid "0" input, the ZeroDivisionError can be avoided. """ try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) while denominator == 0: print("Error. Denominator value cannot be zero.") denominator = int(input("Enter the denominator: ")) fraction = numerator / denominator print(fraction) except ValueError: print("Numerator and denominator must be valid numbers!") except ZeroDivisionError: print("Cannot divide by zero!") print("Finished.")
true
5bb9f5fbeee4b12f3601c61317387e13f62a0e90
Ahmet-Kirmizi/Fibbonaci-sequence
/fibonacci.py
695
4.40625
4
# lets create a input variable that ask for the sequence nth_term = int(input('please enter the number of sequences you want to see: ')) # count variable that will be used to break the while loop count = 0 # everytime the loop starts over it will update count # it will have 2 numbers number1, number2 = 0, 1 if nth_term <= 0: print('Please enter a positive integer!') elif nth_term == 1: print('this is your sequence',nth_term,':') print(number1) else: print('The Fibbonaci sequence:') while count < nth_term: print(number1) nth = number1 + number2 number1 = number2 number2 = nth count = count + 1
true
3053cfa29d6edc0db1f28bba3f84df8ca7cb1b82
SIMELLI25/esercizi_python
/es7.py
820
4.15625
4
input("ES 7") #Elenca proprietà e metodi della classe "Monociclo" class Monociclo(): def __init__(self, template, color, price, max_speed): self.template = template self.color = color self.price = price self.max_speed = max_speed def info(self): print("Modello:", self.template) print("Colore:", self.color) print("Prezzo:", self.price, "€") print("Velocità massima:", self.max_speed, "km/h") def main(): modello = input("Inserisci il modello del monociclo: ") colore = input("Inserisci il colore del monociclo: ") prezzo = int(input("Inserisci il prezzo del monociclo: ")) max_velocita = int(input("Inserisci la massima velocità del monociclo: ")) m1 = Monociclo(modello, colore, prezzo, max_velocita) m1.info() main()
false