blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
5c7b1098dcfd64a60e4f92a793317e8558cbf84e
Tabed23/Rock_Paper_Secissor
/rps.py
1,145
4.15625
4
from random import randint def draw(player, computer): return player == computer def is_win(player, computer): if player == 'r' and computer == 'p': return 'computer' elif player == 'p' and computer == 's': return 'computer' elif player == 's' and computer == 'r': return 'computer' elif player == 'r' and computer == 's': return 'Player' elif player == 'p' and computer == 'r': return 'Player' elif player == 's' and computer == 'p': return 'Player' else: return 'DRAW' def main(): player = input("rock(r) , paper(p) , scissor (s):") print(player + ' vs') while player != 'q': if player == 'q': exit() chosen = randint(1, 3) print(chosen) if chosen == 1: computer = 'r' elif chosen == 2: computer = 'p' else: computer = 's' winner = is_win(player, computer) print("Winner of this game is " + str(winner)) player = input("rock(r) , paper(p) , scissor (s)") main()
false
19760386a0ab964d8bd37d8edb421a72f52c6fbe
kyeeh/holbertonschool-interview
/0x09-utf8_validation/0-validate_utf8.py
1,247
4.34375
4
#!/usr/bin/python3 """ Write a method that determines if a given data set represents a valid UTF-8 encoding. Prototype: def validUTF8(data) Return: True if data is a valid UTF-8 encoding, else return False A character in UTF-8 can be 1 to 4 bytes long The data set can contain multiple characters The data will be represented by a list of integers Each integer represents 1 byte of data, therefore you only need to handle the 8 least significant bits of each integer """ def validUTF8(data): """ Determines if a given data set represents a valid UTF-8 encoding. data: will be represented by a list of integers Returns: True if data is a valid UTF-8 encoding, else return False """ bytes_counter = 0 for n in data: byte = format(n, '#010b')[-8:] if bytes_counter == 0: if int(byte[0]) == 1: bytes_counter = len(byte.split('0')[0]) if bytes_counter == 0: continue if bytes_counter == 1 or bytes_counter > 4: return False else: if byte[:2] != '10': return False bytes_counter -= 1 if bytes_counter == 0: return True return False
true
9d967f528151f408f84ff63ca8866ff204e7cfcf
wakoliVotes/Sorting-Elements-Python
/SortListElementsPython.py
2,284
5
5
# In python, we can adopt proper statements and tools that can help sort values # One can sort values in ascending or sort them in descending order # In this short example, we are demonstrating sorting items in ascending order print("|-----------------------------------------------------------------------------------|") print("Hello world ") print("This lesson shows value sorting in Ascending and Descending order") # Below is the list to work with, called theList, with 28 elements theList = [2,3,5,9,3,4,6,8,4,8,3,2,6,2,9,2,7,2,5,0,20,4,16,8,12,1] # This is the list for demonstration print("The Size of the list is: ", len(theList), "Items") # This helps us get the size of the list # To sort the values/elements, we use the sorted statement in python theList = sorted(theList, reverse=False) # This returns the sorted list in Ascending order # That is, from smallest to largest print("|------------------------The list in Ascending order is:----------------------------|") print(theList) theList = sorted(theList, reverse=True) # This returns the sorted list in Descending order # That is, from largest to smallest print("|----------------------The list in Descending order is:-----------------------------|") print(theList) theList = sorted(theList) # This returns the sorted list in Descending order # That is, from largest to smallest print("|--------Order goes to default of Ascening if true/false is not specified):---------|") print(theList) #------------OUTPUTS------------ # |-----------------------------------------------------------------------------------| # Hello world # This lesson shows value sorting in Ascending and Descending order # The Size of the list is: 26 Items # |------------------------The list in Ascending order is:----------------------------| # [0, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 8, 9, 9, 12, 16, 20] # |----------------------The list in Descending order is:-----------------------------| # [20, 16, 12, 9, 9, 8, 8, 8, 7, 6, 6, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2, 2, 1, 0] # |--------Order goes to default of Ascening if true/false is not specified):---------| # [0, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 8, 9, 9, 12, 16, 20]
true
6adfdb3b77ea3fa1eca8ff303de96769616696e2
Mguer07/script
/Dice game.py
325
4.125
4
import random min = 1 max = 12 roll_again = "yes" while roll_again == "yes" or roll_again == "y": print ("Rolling the dices") print ("The values are....") print ("person 1:",random.randint(min, max)) print ("person 2:",random.randint(min, max)) roll_again = input("Roll the dices again?")
true
5eeea32a4c607db336cecd278854c5f5f7ac53ed
FCHSCompSci/dictionaryinaction-Marsh14-Eric
/Dict Project.py
2,117
4.25
4
#setting up dictionary off = { 'QB' : '', 'RB' : '', 'WR_1': '', 'WR_2': '', 'WR_3': '', 'TE_1': '', 'LT': '', 'LG': '', 'C': '', 'RG': '', 'RT':'', } #setting up functions to make more user freindly def printdict(a_dict): for key, value in a_dict.items(): print("%s: %s" %(key , value)) def updateoff(position, player): off[position] = player #Start of program name = input("What is your name? ") print("Hello %s, you are going to see postions pop up on you screen, \n" "please type out who you would like to put in that position." %name) for key, value in off.items(): print(key, value) playerInput = input() off[key] = playerInput print("Here is your offensive line up as of now:") print(printdict(off)) #main while True: cmd = input("Now, do you want to [u]pdate a postion,[c]reate a postion,\n" "[d]elte a position, or [e]xit with the final team? ") if cmd == "u": updatePO = input("What postion would you like to change the player playing? ") updatePA = input("What player would you like to put in that positon? ") updateoff(updatePO, updatePA) print("This is now your team: ") printdict(off) elif cmd == "c": createPO = input("What postion would you like to create, \n " "remember to type '' around that postion. ") createPA = input("What player would you like to put in that postion? ") updateoff(createPO, createPA) print("This is now your team: ") printdict(off) elif cmd == "d": deletePO = input("What postion would you like to delete? ") map(off.pop, [deletePO]) print("This is now your team: ") printdict(off elif cmd == "e": print("Here is your final team: ") printdict(off) print("Thanks for making an offensive line up %s!" %name) break else: print("Please enter a valid action speified by [] around the letter in the /n" "action specified")
false
2a9729d52e06fc08d9fd0a08053ec2aa2f14bdf1
yckfowa/codewars_python
/6KYU/Count characters in your string.py
442
4.21875
4
""" count the number of times a character shows up in the string and output it as a dictionary """ def count(string): new_dict = {} for ch in string: if ch not in new_dict: new_dict[ch] = 1 else: new_dict[ch] += 1 return new_dict ------------------------------- # 2nd solution from collections import Counter as count def count(string): return {i: string.count(i) for i in string}
true
b4e07f1cebe20358900ad5b98e2276b405ff98c8
ugiriwabo/Password-Locker
/user.py
1,924
4.40625
4
class User: """ Class to create user accounts and save their information """ users_list = [] #Empty users def __init__(self,user_name,password): # instance variables self.user_name = user_name self.password = password def save_user(self): User.users_list.append(self) def delete_user(self): ''' delete_contact method deletes a saved contact from the contact_list ''' User.users_list.remove(self) @classmethod def find_user_by_user_name(cls,user_name): ''' Method that takes in a number and returns a contact that matches that number. Args: number: Phone number to search for Returns : Contact of person that matches the number. ''' for user in cls.users_list: if user.user_name == user_name: return user @classmethod def user_exist(cls,user_name): ''' Method that checks if a contact exists from the contact list. Args: number: Phone number to search if it exists Returns : Boolean: True or false depending if the contact exists ''' for user in cls.users_list: if user.user_name == user_name: return True return False @classmethod def display_user(cls): ''' method that returns the contact list ''' return cls.users_list class Credentials: """ Class to create user accounts and save their information """ credentials_list = [] #Empty users @classmethod def check_user(cls,user_name,password): ''' Method that checks if the name and password entered match entries in the users_list ''' current_user = '' for user in User.users_list: if (user.user_name == user_name and user.password == password): current_user = user.user_name return current_user def __init__(self,user_name,password): # instance variables self.user_name = user_name self.password = password def save_user(self): Credentials.credentials_list.append(self)
true
4a232f2117c1618a546d67c0be4b9841944d2d6f
rlpmeredith/cn-python-programming
/labs/06_classes_objects_methods/06_01_car.py
823
4.4375
4
''' Write a class to model a car. The class should: 1. Set the attributes model, year, and max_speed in the __init__() method. 2. Have a method that increases the max_speed of the car by 5 when called. 3. Have a method that prints the details of the car. Create at least two different objects of this Car class and demonstrate changing the objects attributes. ''' Tested 31-07-2019 class Car: def __init__(self, model, year, max_speed): self.model = model self.year = year self.max_speed = max_speed def inc_max_speed(self): self.max_speed += 5 def __str__(self): return f"The car model name is {self.model}, the car year is {self.year} and the max speed is {self.max_speed}" my_car = Car("VW", 2017, 155) my_car.inc_max_speed() my_car.year = 2015 print(my_car)
true
5936e432e417828c89003a9293e519367d2f7e12
ashmin123/data-science
/Reshaping array.py
631
4.5
4
# numpy.reshape(array, shape, order = ‘C’) : Shapes an array without changing data of array. # Python Program illustrating numpy.reshape() method import numpy as geek array = geek.arange(8) print("Original array : \n", array) # shape array with 2 rows and 4 columns array = geek.arange(8).reshape(2, 4) print("\narray reshaped with 2 rows and 4 columns : \n", array) # shape array with 2 rows and 4 columns array = geek.arange(8).reshape(4, 2) print("\narray reshaped with 2 rows and 4 columns : \n", array) # Constructs 3D array array = geek.arange(8).reshape(2, 2, 2) print("\nOriginal array reshaped to 3D : \n", array)
true
3ec34394f0f0143d42ba868e6755755cdfc30401
ashmin123/data-science
/Array Creation using functions.py
1,126
4.75
5
# Python code to demonstrate the working of array() # importing "array" for array operations import array # initializing array with array values # initializes array with signed integers arr = array.array('i', [1, 2, 3]) #array(data type, value list) print(arr) # printing original array print("The new created array is : ", end="") for i in range(0, 3): print(arr[i], end=" ") print("\n") # Python Programming illustrating numpy.empty method #numpy.empty(shape, dtype = float, order = ‘C’) #function is used to create an array with data type and value list specified in its arguments. import numpy as np b = np.empty(2, dtype=int) print("Matrix b : \n", b) a = np.empty([2, 2], dtype=int) print("\nMatrix a : \n", a) c = np.empty([3, 3]) print("\nMatrix c : \n", c) # Python Program illustrating numpy.zeros method #numpy.zeros(shape, dtype = None, order = ‘C’) #Return a new array of given shape and type, with zeros. import numpy as np b = np.zeros(2, dtype = int) print("Matrix b : \n", b) a = np.zeros([2, 2], dtype = int) print("\nMatrix a : \n", a) c = np.zeros([3, 3]) print("\nMatrix c : \n", c)
true
82feb24ae8a9cbb9f8a663cf6eb901415770529a
nadavperetz/python_newtork
/chapter_1/machine_info.py
446
4.1875
4
import socket def print_machine_inf(): """ Pretty self explained, it will print the host name and ip address :return: """ host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) # Returns the host IP print "Host name: " + str(host_name) print "IP address: " + str(ip_address) if __name__ == '__main__': # If you are running this file, the statement return TRUE print_machine_inf()
true
290ef7dc080563fb975d50229e7741588711a356
OpenLake/Introduction_Python
/BFS.py
753
4.1875
4
# python3 implementation of breadth first search algo for a # given adj matrix of a connected graph def bfs(graph, i): visited = [] queue = [i] while queue: node = queue.pop(0) if node not in visited: visited.append(node) neighbours = graph[node] for neighbour in neighbours: if neighbour not in visited: queue.append(neighbour) return visited if __name__ == '__main__': graph = {'A': ['B', 'C', 'E'], 'B': ['A','D', 'E', 'C'], 'C': ['A', 'F', 'B', 'G'], 'D': ['B'], 'E': ['A', 'B','D'], 'F': ['C'], 'G': ['C']} print(bfs(graph,'A'))
true
d2a4058cff3826230088a75ab5bca53385aa36df
beingajharris/MPG-Python-Script
/3-5-3.py
614
4.40625
4
# Calculate the Miles Per Gallon print("This program loves to calculate MPG!") # Get miles driven from the user miles_driven = input("Please Enter the miles driven:") # The next line Converts the text entered into a floating point number miles_driven = float(miles_driven) #Next is where we receive the gallons used from the user gallons_used = input("Please Enter the gallons used:") # And now we can proceed to convert the given text entered into a floating point number gallons_used = float(gallons_used) # Calculate and print the answer mpg = miles_driven / gallons_used print("Miles per gallon:", mpg)
true
5809d2933fd0b2d894ec1451b9a5da48431e78a9
neternefer/codewars
/python/is_palindrome.py
1,419
4.34375
4
def is_palindrome1(s): """(str) -> bool Return True if and only if s is a palindrome. >>> is_palindrome1('noon') True >>> is_palindrome1('racecar') True >>> is_palindrome1('dented') False """ return reverse(s) == s def is_palindrome2(s): """(str) -> bool Return True if and only if s is a palindrome. >>> is_palindrome2('noon') True >>> is_palindrome2('racecar') True >>> is_palindrome2('dented') False """ n = len(s) #Compare the first half of the string to the reverse of the second half. #Omit the middle character of an odd-length string. return s[:n//2] == reverse(s[n-n//2:]) def is_palindrome3(s): """(str) -> bool Return True if and only if s is a palindrome. >>> is_palindrome3('noon') True >>> is_palindrome3('racecar') True >>> is_palindrome3('dented') False """ i = 0 j = len(s) - 1 while i < j and s[i] == s[j]: i += 1 j -= 1 #In palindrome i and j will either be equal at the end(odd number) #or j will be smaller than i -> the middle of the string has been reached. #If s == '', i = 0 and j = -1. return j <= 1 def reverse(s): """(str) -> str Return the reversed version of s. >>> reverse('hell') 'lleh' >>> reverse('a') 'a' """ rev = '' for ch in s: rev = ch + rev return rev
false
36f2ccfa2c1b84229e6602553078186ce714f903
neternefer/codewars
/python/adjacent_element_product.py
389
4.28125
4
def adjacent_element_product(array): '''Find largest product of adjacent elements.''' #Product of first two elements first = array[0] * array[1] product = first for i in range(len(array)- 1): first = array[i] * array[i + 1] if (first > product): product = first return product def adjacent_element_product(array): return max(a * b for a, b in zip(array, array[1:]))
true
65d52e82d90fb475fd02c6f1c21007cf0287420f
vholley/Random-Python-Practice
/time.py
767
4.40625
4
''' time.py This program takes an input for the current time and an input for a number of hours to wait and outputs the time after the wait. ''' # Take inputs for the current time and the number of hours to wait current_time_str = input('What is the current time (in 24 hour format)? ') wait_time_str = input('How many hours do you have to wait? ') # Cast the inputs from strings to integers current_time_int = int(current_time_str) wait_time_int = int(wait_time_str) # Calculate the sum of the current time and the wait total_hours = current_time_int + wait_time_int # Calculate the time after the wait using the remainder after dividing by 24 output_time = total_hours % 24 # Output the time in 24 hours format print(output_time)
true
a4d0ffdfb5fab128aeb7c8c5f921f37d9c92ec92
roman-4erkasov/coursera-data-structures-algorithms
/prj01_algorithmic_toolbox/week05wrk01_change_dp.py
1,174
4.1875
4
# Uses python3 """ As we already know, a natural greedy strategy for the change problem does not work correctly for any set of denominations. For example, if the available denominations are 1, 3, and 4, the greedy algorithm will change 6 cents using three coins (4 + 1 + 1) while it can be changed using just two coins (3 + 3). Your goal now is to apply dynamic programming for solving the Money Change Problem for denominations 1, 3, and 4. """ def change(money, verbose=None): """ :return: """ min_num = [0] + [None] * money coins = [1, 3, 4] for m in range(1, money + 1): for coin in coins: if verbose: print("m={} c={}".format(m, coin)) if m >= coin: n_coins = min_num[m - coin] + 1 if (min_num[m] is None) or n_coins < min_num[m]: min_num[m] = n_coins if verbose: print("min[m]={} min[{}]={} n_coins={}".format(min_num[m], m - coin, min_num[m - coin], n_coins)) return min_num[m] if __name__ == '__main__': # print(change(5,verbose=False)) m = int(input()) print(change(m, verbose=False))
true
06c96be1b6641b5395a51bcf0c742980ec45c192
Meta502/lab-ddp-1
/lab2/trace_meong.py
2,840
4.1875
4
''' DDP-1 - WEEK 2 - LAB 2: MEONG BROSSS BY: ADRIAN ARDIZZA - 2006524896 - DDP1 CLASS C This project was made as a demonstration of branching and looping in Python. For this lab project, I decided to use a single class to centralize all of the variables (since coordinate of player can be stored in a class) and methods. I have defined a Player() class that will hold all the variables and methods, the summary of which can be seen below: [VARIABLES] On being instantiated, a Player object will have variables x and y assigned to itself by the __init__ function. [METHODS] - The move method takes in commands from the user and translates it into movement by manipulating the coordinate variables of the Player object. For the purpose of this challenge, after every step the method will store the coordinates of the Player. - The getLocation method returns the current position of the Player, this is useful for when we need to print the object's location when the program ends. When the number of inputs is equal to the expected number of input (or if a HOME command is given), the program will get the value of Player.steps and prints it on the console. ''' class Player(): def __init__(self): # Initialize x and y values for Player (meong) object. self.x = 0 self.y = 0 self.steps = [] def move(self, command): # Move function takes commands given by user, and manipulates the object's coordinate. if command == "U": self.y += 1 elif command == "S": self.y -= 1 elif command == "T": self.x += 1 elif command == "B": self.x -= 1 self.steps.append((self.x, self.y)) def getLocation(self): return (self.x, self.y) def main(): meong = Player() # Instantiates "meong" as a Player() object. num_of_args = int(input("Banyak Perintah: ")) i = 0 while i < num_of_args: command = input("Masukkan Perintah ") if command in ['U', 'S', 'T', 'B']: # Checks if command is defined, if so then it is passed to "meong" object. meong.move(command) i += 1 elif command == "HOME": # HOME command prints the current location of "meong", and breaks out of loop. break else: # If command is not defined, then counter will increase to reflect that a command has been inputted, but meong will not move. i += 1 steps = "Jalur yang ditempuh meong bross adalah " print(steps, end = '') print(*meong.steps, sep="-") # Print all the steps that the "meong" object has taken. (used *args to return meong.steps as arguments) print("Distance from start = %f" % ((meong.x**2 + meong.y**2)**0.5)) if __name__ == "__main__": main()
true
b4864c7d4277b01b67e6e807285ba42eb2e0c904
arbwasisi/CSC120
/square.py
881
4.15625
4
""" Author: Arsene Bwasisi Description: This program returns a square 2d list from the function square, which takes in as arguments, the size of the list, that starting value, and how much to increment. """ def square(size, start, inc): ''' Function wil return 2d list of lenght size by size.''' second_list = [] count_1 = 0 while count_1 < size: first_list = [] count_2 = 0 while count_2 < size: first_list.append(start) start += inc count_2 += 1 second_list.append(first_list) start = first_list[1] count_1 += 1 return second_list def main(): size = int(input()) start = int(input()) inc = int(input()) square(size, start, inc) if __name__ == "__main__": main()
true
a0ec1fc89bf7ae53b7a60fa252fdc4a29a674652
arbwasisi/CSC120
/puzzle_match.py
1,148
4.125
4
""" Author: Arsene Bwasisi Description: This program will compare two values in lists left and right, top and bottom to check for any matches. it specifically looks for the reversed value in the other list. """ def puzzle_match_LR(left,right): """ Fucntion looks at value in the left list and checks whether its the same as the reversed version of a value in right list. """ if left[1] == right[3][::-1]: # [::-1] returns the reversed value return True return False def puzzle_match_TB(top,bot): """ Fucntion looks at value in the top list and checks whether its the same as the reversed version of a value in bot list. """ if top[0] == bot[2][::-1]: return True return False def main(): left = ['asd', '123', 'foo', 'bar'] right = ['frd', 'wlm', 'bny', '321'] top = ['xyz', 'az1', 'xxA', 'pyt'] bot = ['xxA', 'cpp', 'lup', 'har'] bool_2 = puzzle_match_LR(left,right) bool_2 = puzzle_match_TB(top,bot) if __name__ == "__main__": main()
true
60b81f2e02dda3d6426982bb83892e619e725182
CruzanCaramele/Python-Programs
/biggest_of_three_numbers.py
1,030
4.5625
5
# this procedure, biggest, takes three # numbers as inputs and returns the largest of # those three numbers. def biggest(num1, num2, num3): if num2 < num1: if num3 < num1: return num1 if num1 < num2: if num3 < num2: return num2 if num1 < num3: if num2 < num3: return num3 if num1 == num2 or num1 == num3: return num1 if num2 == num3: return num3 # this procedure, print_numbers, that takes # as input a positive whole number, and prints # out all the whole numbers from 1 to the input # number. # Make sure your procedure prints "upwards", so # from 1 up to the input number. def print_numbers(input): numbers = 0 while numbers < input: numbers += 1 print numbers print_numbers(3) #>>> 1 #>>> 2 #>>> 3 print biggest(3, 6, 9) #>>> 9 print biggest(6, 9, 3) #>>> 9 print biggest(9, 3, 6) #>>> 9 print biggest(3, 3, 9) #>>> 9 print biggest(9, 3, 9) #>>> 9
true
59a02bd70ce78ee8b8963954c6b62d5446aa185e
elmotecnologia/Curso_Python
/mostrarmaiorde3.py
323
4.125
4
nota1 = input("Digite a primeira nota: ") nota2 = input("Digite a segunda nota:" ) nota3 = input("Digite a terceira nota: ") if nota1 > nota2 and nota1 > nota3: print ("A maior nota é : ",nota1) elif nota2 > nota3 and nota2 > nota1: print ("A maior nota é: ", nota2) else: print ("A maior nota é: ", nota3)
false
fea42a4b4fbd017a085e48cb8c9b132a92c53d43
anaelleltd/various
/PYTHON/flower.py
713
4.15625
4
import turtle def draw_triangle (some_turtle): for i in range(1,5): some_turtle.forward(80) some_turtle.right(120) def draw_art(): window = turtle.Screen() window.bgcolor("white") #Create the flower-turtle flower = turtle.Turtle() flower.shape("circle") flower.color("blue") flower.speed(10) #Draw the stem flower.right(275) flower.forward(200) #Shift the flower-turtle angle for i in range (1,38): flower.color("blue", "yellow") flower.begin_fill() draw_triangle(flower) flower.end_fill() flower.right(10) flower.forward (80) window.exitonclick() draw_art()
true
801fd049aec6b79ee3dc915808c319cb5119b670
jonathanpglick/practice
/get_highest_product_from_three_ints.py
1,646
4.46875
4
# -*- coding: utf-8 -*- """ Given a list of integers, find the highest product you can get from three of the integers. The input list_of_ints will always have at least three integers. @see https://www.interviewcake.com/question/python/highest-product-of-3 """ from __future__ import unicode_literals from functools import partial def get_highest_product_from_three_v1(arr): """ Only works with positive numbers. """ sorted_arr = sorted(arr, reverse=True) return sorted_arr[0] * sorted_arr[1] * sorted_arr[2] def get_highest_product_from_three_On(arr): """ """ highest_int = max(arr[0], arr[1]) highest_product_of_2 = arr[0] * arr[1] lowest_int = min(arr[0], arr[1]) lowest_product_of_2 = arr[0] * arr[1] highest_product = arr[0] * arr[1] * arr[2] for i in arr: highest_product = max(highest_product, i * highest_product_of_2, i * lowest_product_of_2) highest_product_of_2 = max(highest_product_of_2, i * highest_int) lowest_product_of_2 = min(lowest_product_of_2, i * lowest_int) highest_int = max(highest_int, i) lowest_int = max(lowest_int, i) return highest_product # get_highest_product_from_three = get_highest_product_from_three_v1 get_highest_product_from_three = get_highest_product_from_three_On def main(): arr = [1, 5, 7, 4, 2, 9] answer = 315 result = get_highest_product_from_three(arr) print(result == answer) print(result) arr = [-10, -10, 1, 3, 2] answer = 300 result = get_highest_product_from_three(arr) print(result == answer) print(result) if __name__ == '__main__': main()
true
17b797398202b61e8c8fcc08c120650cd547eec1
NLGRF/Course_Python
/10-5.py
294
4.125
4
try: Val1 = int(input('Type the first number: ')) Val2 = int(input('Type the second number: ')) ans = Val1/Val2 except ValueError: print('You must type a whole number!') except ZeroDivisionError : print('Can not divide by zero') else : print(Val1, '/', Val2, ' = ',ans)
true
44c14d997476b896ccba854408a05af6b9130af6
favuur/Aptech_Python
/class.py
1,752
4.1875
4
"""class Aptech: name="oloruntoba favour" obi=Aptech() print(obi.name) class Aptech: name="oloruntoba favour" obi=Aptech() obi1=Aptech() print(obi.name) print(obi1.name) #INITIALIZE A CLASS class Aptech: def __init__(self,name,age): self.nameee=name self.ageeee=age ob2=Aptech("favour",29) print("my name is",ob2.nameee) print(ob2.ageeee) #OR class Aptech: def __init__(self,name,age): self.nameee=name self.ageeee=age def printout(self): print("my name is",self.nameee,"i am ",self.ageeee) obi1=Aptech("favour",28) obi1.printout() class book: def __init__(self,author,title,pages,price): self.aut=author self.tit=title self.pag=pages self.pri=price info=book("Chinua Achebe","There was a country",590,"$100") print("The author of this book is",info.aut) print("The title of the book is",info.tit) print("It has",info.pag,"pages") print("Its selling price is",info.pri) price=int(input("book price")) discount=price*0.1 print(discount) import math class circle: def __init__(self,radius,pi): self.pi = pi self.radi=radius other=circle(3,5) print(other.pi*other.radi)""" #INHERITANCE class Aptech: def __init__(self, name, age): self.nameee = name self.ageeee = age def printout(self): print("my name is", self.nameee, "i am ", self.ageeee) obi1 = Aptech("favour", 28) obi1.printout() class course(Aptech): def __init__(self,name,age,subject): Aptech.__init__(self,name,age) self.sub=subject def pr(self): print("the student is studing",self.sub) cou=course("Remi",50,"python") cou.printout() """str="my string" r=list(str) print(r)"""
false
c4c7e3665bb9e69bf5e970b73513fc4db37e7555
lancelote/algorithms_part1
/week1/quick_union.py
1,884
4.15625
4
"""Quick Union algorithm (weighted)""" class QuickUnion: """Object sequence represented as a list of items Item value corresponds to a root of object """ def __init__(self, n): """ Args: n (int): Number of objects """ self.data = list(range(n)) self.size = [1]*n # Objects height in the tree def union(self, obj1, obj2): """Add connection between obj1 and obj2 objects Weighted algorithm (avoiding too height trees) Args: obj1 (int): First object obj2 (int): Second object Returns: None """ root_obj1 = self.root(obj1) root_obj2 = self.root(obj2) if root_obj1 != root_obj2: if self.size[root_obj1] < self.size[root_obj2]: self.data[root_obj1] = root_obj2 self.size[root_obj2] += self.size[root_obj1] else: self.data[root_obj2] = root_obj1 self.size[root_obj1] += self.size[root_obj2] def connected(self, obj1, obj2): """Are obj1 and obj2 in the same component? Args: obj1 (int): First object obj2 (int): Second object Returns: bool: True or False """ return self.root(obj1) == self.root(obj2) def root(self, obj): """Find root of obj Args: obj (int): Object to find root Returns: int: Object root """ while obj != self.data[obj]: # Uncomment to enable simple path compression # self.data[obj] = self.data[self.data[obj]] obj = self.data[obj] return obj def __repr__(self): return ' '.join(map(str, self.data)) __str__ = __repr__
true
0e985e0b7d2396bba1a5ce0d0f02625a999dec5e
fffk3045167/desktop_WSL
/python/insertionSort.py
430
4.125
4
# 插入排序 def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while arr[j] > key and j >= 0: arr[j+1] = arr[j] arr[j] = key j = j - 1 return arr def showArr(arr): for i in range(len(arr)): print(arr[i], end = ' ') print('\n') # 测试数组 arr = [12, 11, 34, 13, 1, 5, 25, 19, 6] showArr(insertionSort(arr))
false
833dda99119ffc1f39c309f3d4c188a5516a65c2
daniel-tok/oldstuff
/hangman.py
2,654
4.125
4
import random lines = open("words").read() # reads all the text in the 'words' file line = lines[0:] # sets all the lines starting from the first to 'line' variable words = line.split() # splits the string of 'line' into separate words myWord = random.choice(words) # makes a random choice from split string def dashes(numOfLetters): # creates list 'dash' where a dash is added for every letter so word looks like ['_','_',...] dash = [] for i in range(1, len(numOfLetters) + 1): dash.append('_') return dash def dashConverter(dashList): # converts the list form from dashes() into a more readable string '_____' dashi = '' for j in dashList: dashi += j return dashi guesses = 10 # limit on number of guesses print('Welcome to Hangman.\nYou have ' + str(guesses) + ' guesses.\nThe word is: ' + str(dashConverter(dashes(myWord))) + '\nIt has ' + str(len(myWord)) + ' letters.') # intro # TODO: print('developer hack: ' + myWord) string = [] # i used a list so that i could iterate over each letter/element one by one for i in dashConverter(dashes(myWord)): string += i # adds all the dashes to the 'string' variable to be printed as '____' index = 0 # set to 0 before iterations while '_' in string: # continuously checks if there are still dashes in the 'string' (word not finished) attempt = input() # asks for input from user attempt = attempt.lower() # converts capitalised letters to lowercase subtract = True # boolean variable used to check if guesses should be subtracted (only if attempt wrong) for i in myWord: # for loop iterates over every letter in the randomly chosen word if attempt == i: # 'if the guessed letter is in the random word:' del string[index] # delete the dash in the position where the word should be in string.insert(index, i) # insert the attempt into the position where the word should be in subtract = False # 'don't subtract from guesses as attempt is correct' index += 1 # moves onto consequent letter so that each letter is iterated over index = 0 # once for loop finished, index set to 0 so that new attempt iterates from the beginning print(dashConverter(string)) # prints the new appended string of dashes e.g: __a__a if subtract is True: # checks if the guesses needs to be subtracted guesses -= 1 print(str(guesses) + ' guesses left.') if guesses == 0: break if '_' not in string: print('You win! The word was ' + myWord + '.') else: print('You lose. Ran out of guesses.\nThe word was ' + myWord + '.')
true
fba058525aeeae5aa3062b2b75d28f8e49962668
rohanmukhija/programming-challenges
/project-euler/euler04.py
996
4.3125
4
#!/usr/bin env python2.7 # determine the largest palindrome product of two 3-digit numbers upper = 999 lower = 100 limit = (upper - lower) / 2 def is_palindrome(seq): ''' determines if a sequence is a palindrome by matching from ends inward ''' seq = str(seq) length = len(seq) depth = 0 if length % 2 == 0: target = length / 2 while seq[depth] == seq[-(depth+1)] and depth < target: depth += 1 if depth == target: return True else: target = (length-1) / 2 while seq[depth] == seq[-(depth+1)] and depth < target: depth += 1 if depth == target: return True return False upper = 999 lower = 100 max_palindrome = 0 low_term = upper while low_term >= lower: high_term = upper while high_term >= low_term: if high_term*low_term <= max_palindrome: break if is_palindrome(high_term*low_term): max_palindrome = high_term*low_term high_term -= 1 low_term -=1 print max_palindrome
true
87b452a9c96fae96245b0a41ed50faa8c97a4d29
cygarxtin/python
/for_loops.py
691
4.53125
5
#for loop statement with range for i in range(1,11): #print out [1,2,3,4,5,6,7,8,9,10] print i #for loop statement without range for j in [1, 2, 3]: #print out [1,2,3] print j #for loop statement with three arguments for a in range(0, 20, 2): #print out [0,2,4,6,8,10,12,14,16,18] print a #for loop statement printing out in asterisks for i in range(1, 5): #print out '****' #'****' #'****' #'****' print "****" for i in range(1, 5): print "*" * i for i in range(3, 0, -1): print "*" * i print ("Pattern C") for e in range (11,0,-1): print((11-e) * ' ' + e * '*') print ('') print ("Pattern D") for g in range (11,0,-1): print(g * ' ' + (11-g) * '*')
false
89c22ac70d948852aa4703f18cf56e0a31ce66d6
XVXVXXX/leetcode
/0125.py
1,121
4.125
4
# 125. 验证回文串 # 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 # 说明:本题中,我们将空字符串定义为有效的回文串。 # 示例 1: # 输入: "A man, a plan, a canal: Panama" # 输出: true # 示例 2: # 输入: "race a car" # 输出: false # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/valid-palindrome # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 class Solution: def isPalindrome(self, s: str) -> bool: if not s: return True left = 0 right = len(s)-1 while left < right: while left < right and not s[left].isalnum(): left+=1 while left < right and not s[right].isalnum(): right-=1 if s[left].lower() != s[right].lower(): return False left+=1 right-=1 return True solu = Solution() s = "A man, a plan, a canal: Panama" o = solu.isPalindrome(s) o
false
18797636607257baf1cb465a801524c36abe3990
AliceSkilsara/python
/tasks/task7.py
1,040
4.375
4
# Проверьте, является ли введённое пользователем с клавиатуры натуральное число — простым. # Постарайтесь не выполнять лишних действий (например, после того, как вы нашли хотя бы один # нетривиальный делитель уже ясно, что число составное и проверку продолжать не нужно). # Также учтите, что наименьший делитель натурального числа n, если он вообще имеется, # обязательно располагается в отрезке [2; √n]. import math number = int(input("Input your number: ")) d = 2 if (number > 2): while (d <= math.sqrt(number)): if number % d == 0: print("It is composite number") break d += 1 else: print("It is a prime number") else: print("Your number is too small")
false
d8ef648b1f3a7df5a4612f79f6af7b32a9e9690f
AliceSkilsara/python
/tasks/task18.py
414
4.21875
4
#Создать программу, которая будет проверять попало ли случайно выбранное из отрезка [5;155] целое число в интервал # (25;100) и сообщать результат на экран. import random a=random.randint(5,155) print("Random number is ",a) if a<25 or a>100: print("Out of range") else: print("In range")
false
a3177f2b22aaef2589ffed4da3935da8e6a602b7
GeeksIncorporated/playground
/554.brick-wall.py
1,496
4.28125
4
# https://leetcode.com/problems/brick-wall/description/ # There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks. # The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right. # If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks. # You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. # # @lc app=leetcode id=554 lang=python # # [554] Brick Wall # from collections import defaultdict # @lc code=start class Solution: def leastBricks(self, wall): wall_length = len(wall) counter = defaultdict(int) for row in wall: c = 0 for brick in row: c += brick counter[c] += 1 first_max = second_max = 0 for v in counter.values(): if v > first_max: second_max = first_max first_max = v elif v > second_max: second_max = v return wall_length - second_max # @lc code=end s = Solution() r = s.leastBricks([[1],[1],[1]]) print(r)
true
07f2c03cfcde68f89bbfce8b6b4cf246e95d6e50
GeeksIncorporated/playground
/2d_matrix_pretty_pattern.py
1,852
4.15625
4
# https://www.interviewbit.com/problems/prettyprint/ # Print concentric rectangular pattern in a 2d matrix. # Let us show you some examples to clarify what we mean. # # Example 1: # # Input: A = 4. # Output: # # 4 4 4 4 4 4 4 # 4 3 3 3 3 3 4 # 4 3 2 2 2 3 4 # 4 3 2 1 2 3 4 # 4 3 2 2 2 3 4 # 4 3 3 3 3 3 4 # 4 4 4 4 4 4 4 # # Example 2: # # Input: A = 3. # Output: # # 3 3 3 3 3 # 3 2 2 2 3 # 3 2 1 2 3 # 3 2 2 2 3 # 3 3 3 3 3 # # The outermost rectangle is formed by A, then the next outermost is formed by A-1 and so on. # # You will be given A as an argument to the function you need to implement, and you need to return a 2D array. from pprint import pprint class Solution: # @param A : integer # @return a list of list of integers def prettyPrint(self, A): # M is going to be a 2d zeros array with size 2Ax2A M = list(map(list, ((0,) * (2 * A - 1),) * (2 * A - 1))) A -= 1 # Going to fill the M by quarter # 1:1 for x in range(A + 1, -1, -1): for i in range(x): M[A + i][A + x - 1] = x for j in range(x): M[A + x - 1][A + j] = x # 1:-1 for x in range(A + 1, -1, -1): for i in range(x): M[A + i][A - (x - 1)] = x for j in range(x): M[A + x - 1][A - j] = x # -1:1 for x in range(A + 1, -1, -1): for i in range(x): M[A - i][A + x - 1] = x for j in range(x): M[A][A + j] = x M[A - (x - 1)][A + j] = x # -1:-1 for x in range(A + 1, -1, -1): for i in range(x): M[A - i][A - (x - 1)] = x for j in range(x): M[A - (x - 1)][A - j] = x return M s = Solution() pprint(s.prettyPrint(9))
true
1927df5434f4ae609363d4e5f3b7f3ac6372c5fe
easulimov/py3_learn
/ex03.py
469
4.28125
4
print('I will count the animals') print("Chicken", 25+30/6) print("Roosters", 100-25*3%4) print('And now I will count the eggs:') print(3+2+1-5+4%2-1/4+6) print('Is it true that 3+2<5-7') print(3+2<5-7) print("How much will 3+2", 3+2) print("And how much will 5-7?", 5-7) print("Oh I think I'm confused. Why False?") print("I will count again...") print('Is it greater?', 5>-2) print("And is it greater or equal?", 5>=-2) print("And is it less or equal?", 5<=-2)
true
c04061d832c99c18afe11ebe9277434d2626170d
meheboob27/Demo
/Hello.py
240
4.1875
4
#Calculate Persons age based on year of Birth name=str(input("Please enter your Good name:")) year=int(input("Enter your age:")) print(year) Currentage=2019-year print(Currentage) print ("Hello"+name+".your are %d years old."% (Currentage))
true
4eabea62ef072aca451b042f4bcd9d7a888e33ac
dimitar-daskalov/SoftUni-Courses
/python_OOP/labs_and_homeworks/08_iterators_and_generators_exercise/06_fibonacci_generator.py
213
4.25
4
def fibonacci(): previous, current = 0, 1 while True: yield previous previous, current = current, previous + current generator = fibonacci() for i in range(5): print(next(generator))
true
a991abf55ca012b8253cea08d6bccf80cc35f8d5
dimitar-daskalov/SoftUni-Courses
/python_basics/labs_and_homeworks/03_conditional_statements_advanced_exercise/08_on_time_for_the_exam.py
1,686
4.15625
4
exam_hour = int(input()) exam_minute = int(input()) hour_of_arrival = int(input()) minute_of_arrival = int(input()) exam_time_minutes = (exam_hour * 60) + exam_minute minutes_of_arrival = (hour_of_arrival * 60) + minute_of_arrival minutes_late = minutes_of_arrival - exam_time_minutes minutes_left = exam_time_minutes - minutes_of_arrival if exam_time_minutes < minutes_of_arrival and minutes_late <= 59: print("Late") print(f"{minutes_late} minutes after the start") elif exam_time_minutes < minutes_of_arrival and minutes_late > 59: late_hours = minutes_late // 60 late_minutes = minutes_late % 60 if late_minutes > 9: print("Late") print(f"{late_hours}:{late_minutes} hours after the start") else: print("Late") print(f"{late_hours}:0{late_minutes} hours after the start") if exam_time_minutes > minutes_of_arrival and minutes_left > 30: left_hours = minutes_left // 60 left_minutes = minutes_left % 60 if left_minutes > 9 and left_hours != 0: print("Early") print(f"{left_hours}:{left_minutes} hours before the start") elif minutes_left <= 59 and left_minutes != 0: print("Early") print(f"{minutes_left} minutes before the start") elif left_minutes == 0: print("Early") print(f"{left_hours}:00 hours before the start") else: print("Early") print(f"{left_hours}:0{left_minutes} hours before the start") elif exam_time_minutes >= minutes_of_arrival and minutes_left <= 30: if exam_time_minutes == minutes_of_arrival: print("On time") else: print("On time") print(f"{minutes_left} minutes before the start")
false
f1e5e9a302b3e1b34d304174453e6a107bfaa24e
dimitar-daskalov/SoftUni-Courses
/python_advanced/labs_and_homeworks/02_tuples_and_sets_lab/02_average_student_grades.py
517
4.125
4
number_of_students = int(input()) student_grades_dict = {} for student in range(number_of_students): student_name, grade = input().split() grade = float(grade) if student_name not in student_grades_dict: student_grades_dict[student_name] = [grade] else: student_grades_dict[student_name].append(grade) for key, value in student_grades_dict.items(): average_grade = sum(value) / len(value) print(f"{key} -> {' '.join(f'{el:.2f}' for el in value)} (avg: {average_grade:.2f})")
true
f7b5ae11c0125dc50500b6042e5cc5f4f7f6243c
yuansiang/Demos
/python demos/oop/bankaccount.py
1,841
4.21875
4
#bankaccount.py class Account(): """ Bank account super class """ def __init__(self, account_no, balance): """ constructor method """ #something to store and process self.__account_no = account_no self.__balance = balance #stuff that starts with _underscore is private def get_account_no(self): """accessor method to retrieve account number """ return self.__account_no def get_account_balance(self): """accessor method to retrieve account number """ return self.__balance ## def set_balance(self, new_balance): ## """ modifier/mutator method to update balance """ ## self.__balance = new_balance def deposit(self, amount): self.__balance += amount def withdrawal(self,amount): self.__balance -= amount def display(self): """ helper/supprt method to show account info """ print("Account No:", self.__account_no) print("Balance:", self.__balance) class SavingsAccount(Account): """Savings account subclass """ def __init__(self, account_no, balance, interest): """subclass constructor method""" super().__init__(account_no, balance) self.__interest = interest def calc_interest(self): """helper/support method to show savings account info""" self.deposit class CurrentAccount(Account): def __init__(self, account_no, balance, overdraft): """subclass constructor method""" super().__init__(account_no, balance) self.__overdraft = overdraft def withdraw(self, amount): #overrides superclass withdrawn """helper/support method """ #main acct1 = Account("C01", 0) ##print(acct1.get_account_no()) ##print(acct1.get_account_balance()) acct1.deposit(500) acct1.display()
true
c3f53c6ca3ef11b9add05c8a25ccdfe47b9911ec
fyzbt/algos-in-python
/implementations/merge_sort.py
2,051
4.125
4
""" count number of inversions in list inversion: for a pair of indices in list 1 <= i < j <= n if A[i] > A[j] in a sorted array number of inversions is 0 input: list size list elements as string separated by whitespace """ import sys num_inversions = 0 def recursive_merge_sort(data): """ recursively merge sort array takes list of numerical elements as input """ if len(data) <= 1: return data mean_el = len(data) // 2 left_data = recursive_merge_sort(data[:mean_el]) right_data = recursive_merge_sort(data[mean_el:]) return merge(left_data, right_data) def merge(left_data, right_data): i_left, i_right = 0, 0 merged_data = [] global num_inversions while i_left < len(left_data) and i_right < len(right_data): if left_data[i_left] <= right_data[i_right]: merged_data.append(left_data[i_left]) i_left += 1 else: merged_data.append(right_data[i_right]) # upfating global counter variable num_inversions += len(left_data) - i_left i_right += 1 merged_data += left_data[i_left:] merged_data += right_data[i_right:] return merged_data def main(): data_size = int(sys.stdin.readline()) data = list(map(float, sys.stdin.readline().split())) recursive_merge_sort(data) print(num_inversions) def test(n_iter=100): from random import randint for _ in range(n_iter): # to drop global counter variable for each test iteration global num_inversions num_inversions -= num_inversions n = randint(1, 3) data = [randint(0, 5) for _ in range(n)] recursive_merge_sort(data) print(data) print(num_inversions) def test_man(): data = [7, 6, 5, 4, 3, 2, 1] data = [1, 2, 3, 5, 4] data = [6, 4, 5, 0, 0, 2] data = [2, 3, 9, 2, 9] data = [10, 8, 6, 2, 4, 5] data = [10, 9, 3, 8, 3, 10] recursive_merge_sort(data) print(num_inversions) if __name__ == '__main__': main()
true
873a3ddb6047fa6d5b6723d9705cebbb0f823665
skwirowski/Python-Exercises
/Basics/textual_data.py
1,591
4.5
4
my_message = 'Hello World' multiple_lines_message = """Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!""" print(my_message) print(multiple_lines_message) # Get length of the string print(len(my_message)) # Get specific index character from string (indexes start from 0) print(my_message[0]) # SLICING # First index is inclusive and last one is not print(my_message[0:5]) # Leaving first value (index) empty means "start from the beginning" print(my_message[:5]) # Leaving last value (index) empty means "go all the way to the end" print(my_message[6:]) # Lower/Upper Case print(my_message.lower()) print(my_message.upper()) # Count specific characters in the string print(my_message.count('l')) # Find index where certain characters can be found (if character doesn't exist returns -1) print(my_message.find('World')) # Replace some characters in our string with some other characters # 1 - creating new variable my_new_message = my_message.replace('World', 'Universe') print(my_new_message) # 2 - setting the same variable again my_message = my_message.replace('World', 'Universe') print(my_message) # STRINGS CONCATENATIONS greeting = 'Hello' name = 'Paul' # 1 message = greeting + ', ' + name + '. Welcome!' print(message) # 2 message = '{}, {}. Welcome!!'.format(greeting, name) print(message) # 3 - F strings message = f'{greeting}, {name.upper()}. Welcome!!!' print(message) # DIR - it shows us all of the attributes and methods that we have access to with variable we passed as an argument print(dir(name)) print(help(str)) print(help(str.lower))
true
52836e9caa916dff14b3b248bcb74b3ad1144f7b
aileentran/practice
/stack.py
485
4.21875
4
# Implementing stack w/list # Last in, first out # Functions: push, pop, peek class Stack(object): def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] pancakes = Stack() print(pancakes.items) pancakes.push('blueberry') pancakes.push('strawberry') pancakes.push('matcha') print(pancakes.items) print(pancakes.pop()) print(pancakes.items) print(pancakes.peek())
true
6aec7f774ca59acb2471454001be7e56202273b8
aileentran/practice
/daysinmonth.py
941
4.3125
4
""" input: integer == month, integer == year output: integer - number of days in that month Notes: leap year happens % 4 == 0 years --> feb has 29 instead of 28 EXCEPT year % 100 = NOT leap year EXCEPT year % 400 = IS leap year Pseudocode: empty dictionary = months (nums) key: days (value) check to see if looking for feb. if looking at feb = leap year check return diction[month] = value """ def days_in_month(month, year): num_of_days = { 1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 } if year % 100 == 0 and year % 400 != 0: return num_of_days[month] if month == 2 and year % 4 == 0: return 29 return num_of_days[month] month1 = 1 month2 = 2 print(days_in_month(month1, 1980)) #31 print(days_in_month(month2, 400)) #29 print(days_in_month(2, 1000)) #28
true
b84872de8d43bf1251f0a6015741db80dfdcbbdb
aileentran/practice
/queue.py
1,337
4.3125
4
# Functions - enqueue, dequeue, peek # Implement with list # Assumptions: Start of Queue @ idx 0; End of list at the back class Queue(object): def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): return self.items.pop(0) def peek(self): return self.items[0] # Implement with linked list # Assumptions: Start of Queue at head node; End of queue at tail class Node(object): def __init__(self, data): self.data = data self.next = None class Queue_ll(object): def __init__(self): self.front = None self.back = None def enqueue(self, item): if self.front == None: self.front = Node(item) self.back = Node(item) else: self.back.next = Node(item) self.back = Node(item) # Test1 - List implementation # line = Queue() # print(line.items) # line.enqueue('a') # line.enqueue('b') # line.enqueue('c') # line.enqueue('d') # print(line.items) # print(line.dequeue()) # print(line.peek()) # Test2 - Linked List implementation line = Queue_ll() # print(line) # print(line.front) # print(line.back) line.enqueue('a') line.enqueue('b') # line.enqueue('c') print(line.front.data) print(line.front.next.data) # print(line.back.data)
true
b1df355d842c1f5db5d2302f8a7810228c6ffe7f
chu83/python-basics
/03/operator-logical.py
474
4.125
4
#논리연산자(NOT, OR, AND) a = 30 b1 = a <= 30 b2 = not b1 #논리합 or b3 = a <= 30 or a >= 100 #논리곱 and b4 = a <= 30 and a>=100 print(b1, b2) print(not a <= 10) print(b3) print(b4) print(True or 'logical') print(False or 'logical') print([] or 'logical') print([19, 20] or 'logical') print('operator' or 'logicla') print(None or 'logical') s = 'Hello world' #if s is not '': # print(s) s and print(s) s = '' s and print(s) print('------------------')
false
a3a2cd79919713788df58da9f220ac26bc16a9d1
prakashmngm/Lokesh-Classes
/Factorial-Series.py
601
4.25
4
''' Consider the series : = 0! + 1! + 2! + 3! = 1 + 1 + 2 + 6 = 10 Input : 3 Output : 10 Input : 5 Output : 154 (0! + 1! + 2! + 3! + 4! + 5! ) Use the def Factorial(num): function that we have written before. ''' def Factorial(num): if(num == 0): return 1 else: fact = 1 index =1 while(index <= num): fact *= index index = index+1 return fact num = 5 series = 0 index = 0 while(index <= num): series += Factorial(index) #print(num,series,index) index = index+1 print("The value of Factorial series is :",series)
true
8ad6dded879cf4e788f57a2f9d6d86de1dde5f6a
prakashmngm/Lokesh-Classes
/Harmonic_Mean.py
709
4.1875
4
''' Problem : Harmonic Mean of ‘N’ numbers. Pseudo code: 1. Input the list of numbers 2. Initiate a variable called ‘sum’ to zero to store the sum of the elements of the list 3.iterate through each element of the list using for loop and reciprocate the item and add it to the sum 4.calculate the Harmonic Mean by reciprocating the sum which is calculated by the reciprocals of the items of the list 5.print the value of the Harmonic Mean ''' list = [1,2,4] sum = 0 length = len(list) if(length>1): for item in list: sum += (1/item) HM = length/sum print("The Harmonic Mean of the elements in the list:",HM) else: print("There has to be minimum 2 elements to perform the sum of the list")
true
484cb297a1ef0c8a4bcabdf33bcd175a09fd3f9e
prakashmngm/Lokesh-Classes
/Exponential-Function.py
977
4.3125
4
''' Problem : Implement exponential function. Input only +ve integers. def exponential( base, index ) Input : (2,5) Output : 32 Possible VALID inputs : (0,3),(5,0),(0,0),(4,4), (12, 12) If base and index is 0 , then the value of the exponent is undefined. if base == 0 print 0. Go to step 4. If index == 0 print 1. Go to step 4. 1. Take base and exponent values as input 2. Product = 1 2. Iterate base value to the exponent number of times and multiply the base with product in each iteration. 3. Print the value of the exponent. 4.End. ''' def exponent(base,index): if((index and base) == 0): print("The value of the exponent is undefined") elif(index == 0): print("The value of the exponent is 1") elif(base == 0): print("The value of the exponent is 0") else: product = 1 for indices in range(index): product *= base print("The value of the exponent is :",product) exponent(5,3)
true
996bc5aa6ce1db7254ad71d326de11bb795cf206
pzeiger/aspp_day2_exercises
/exc1_creating_python_package/animals/dangerous/fish.py
309
4.125
4
class Fish: ''' ''' def __init__(self): ''' ''' self.members = ['Shark', 'Cod', 'Hering'] def printMembers(self): ''' ''' print('The members of the class "Fish" are:') for member in self.members: print('\t %s' %member)
false
a2fc3078df459d96f9842c9fdaafed2caab159ef
lacecheung/class-projects2
/shoppinglist.py
1,540
4.40625
4
#default shopping list shopping_list = ["milk", "bread", "eggs", "quinoa"] #function definitions: def remove_item(item): shopping_list.remove(item) shopping_list.sort print shopping_list #options print "Select a choice:" print "Type 1 to add a item" print "Type 2 to remove an item" print "type 3 to replace an item" print "type 4 to show total number of items on list" choice = int(raw_input()) #add an item if choice ==1: new_item = raw_input("What do you want to add?") if new_item in shopping_list: print "you already have this item in your list" else: shopping_list.append(new_item) shopping_list.sort() print shopping_list #remove an item if choice == 2: show_list = str.lower(raw_input("Do you want to see your existing list?")) if show_list == "yes": print shopping_list delete_item = raw_input("What item would you like to remove?") if delete_item not in shopping_list: print "This item is not in the list" print "Your shopping list currently has", shopping_list else: remove_item(delete_item) #replace an item if choice == 3: old_item = raw_input("What item do you want to replace?") new_item = raw_input("What item do you want to replace it with?") if old_item not in shopping_list: print "This item is not in the list" print "Your shopping list currently has", shopping_list else: shopping_list[shopping_list.index(old_item)]=new_item shopping_list.sort() print shopping_list #total items in list if choice == 4: print "Your shopping list has", len(shopping_list), "items"
true
b9cbca91633f7dc2ec9e3e0c81faad2f230269b6
CompThinking20/python-project-Butterfly302
/Pythonproject.py
722
4.15625
4
def main(): print "What is your favorite food?" food_answer = raw_input("Enter your food") print "Hello" + str(food_answer) + " What is your favorite desert?" desert_answer + raw_input ("Enter your desert") if str(desert_answer) != "Brownies.": print "What you like is not availible" return print "What is your favorite dish?" food_answer = raw_input("seafood lasagna") if str(color_answer) != "seafood lasagna": print "What you like is not availible" return print "When is the last time you cooked?" swallow_answer = raw_input("12pm today") if str(swallow_answer) != "ckicken" or "fish": print "What you like is not availible" main()
true
242864a5ab2f75766073615addea7b4a18b3a644
CC-SY/practice
/Desktop/BigData SU2018/Lesson 1/pythoncourse-master/code_example/02-circleCalc/example2.py
542
4.5
4
# wfp, 5/30/07, wfp: updated 9/5/11; rje 5/14/12 # prompt user for the radius, give back the circumference and area import math radius_str = input("Enter the radius of your circle:") radius_float = float(radius_str) circumference_float = 2 * math.pi * radius_float area_float = math.pi * radius_float * radius_float # also, area = math.pi * math.pow(radius_float,2) # also, area = math.pi * radius_float ** 2 print() print("The cirumference of your circle is:",circumference_float,\ ", and the area is:",area_float)
true
0b1b2edf5b67b0151c3d624b99141d506dfb33c6
karsonk09/CMSC-150
/Lab 06 - Text Adventure/lab_06.py
2,998
4.34375
4
# This is the list that all of the rooms in the game will be appended to room_list = [] # List of all rooms in the game room = ["You are in a dark, cryptic room with a door to the north and a door to the east.", 3, 1, None, None] room_list.append(room) room = ["You walk out into a long hallway. There are doors to the north, east, and south.", 4, 2, None, 0] room_list.append(room) room = ["You enter a Sun Room. There are doors to the north and west.", 5, None, None, 1] room_list.append(room) room = ["You enter a kitchen. The floor is littered with cooking utensils and there are scratch marks on the floor." " There are doors to the east and south.", None, 4, 0, None] room_list.append(room) room = ["You enter someone's bedroom. There are doors to the north, east, south, and west.", 6, 5, 1, 3] room_list.append(room) room = ["You enter a basement. There are sets of stairs accompanied by doors to the south and to the west.", None, None, 2, 4] room_list.append(room) room = ["You walk out of the house and onto a pattio. There is a door to the south.", None, None, 4, None] room_list.append(room) # Starting Room current_room = 0 done = False # Traveling throughout the house while not done: print(room_list[current_room][0]) print() room_choice = input("Which direction would you like to travel? ") print() # These dictates where the player wants to travel and where they cannot travel. if room_choice.upper() == "N" or room_choice.upper() == "NORTH": next_room = room_list[current_room][1] print() if next_room == None: print("You cannot go that direction. There is no door there!") print() else: current_room = next_room elif room_choice.upper() == "E" or room_choice.upper() == "EAST": next_room = room_list[current_room][2] print() if next_room == None: print("You cannot go that direction. There is no door there!") print() else: current_room = next_room elif room_choice.upper() == "S" or room_choice.upper() == "SOUTH": next_room = room_list[current_room][3] print() if next_room == None: print("You cannot go that direction. There is no door there!") print() else: current_room = next_room elif room_choice.upper() == "W" or room_choice.upper() == "WEST": next_room = room_list[current_room][4] print() if next_room == None: print("You cannot go that direction. There is no door there!") print() else: current_room = next_room # If player would like to quit the game elif room_choice.upper() == "Q" or room_choice.upper() == "QUIT": print("You have quit the game.") done = True # If player chooses to travel somewhere that they cannot travel else: print("That is not a direction you can travel!") print()
true
6472112759639ba52f6b1a995d07b7735546bf6e
Focavn/Python-100-Days
/Day01-15/code/Day12/str1.py
976
4.125
4
""" 字符串常用操作 Version: 0.1 Author: 骆昊 Date: 2018-03-19 """ import pyperclip # 转义字符 print('My brother\'s name is \'007\'') # 原始字符串 print(r'My brother\'s name is \'007\'') str = 'hello123world' print('he' in str) print('her' in str) # 字符串是否只包含字母 print(str.isalpha()) # 字符串是否只包含字母和数字 print(str.isalnum()) # 字符串是否只包含数字 print(str.isdecimal()) print(str[0:5].isalpha()) print(str[5:8].isdecimal()) list = ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡'] print('-'.join(list)) sentence = 'You go your way I will go mine' words_list = sentence.split() print(words_list) email = ' jackfrued@126.com ' print(email) print(email.strip()) print(email.lstrip()) # 将文本放入系统剪切板中 pyperclip.copy('老虎不发猫你当我病危呀') # 从系统剪切板获得文本 # print(pyperclip.paste())
false
573e89d5ffa71f7b477ebe165a2d1755cdcb4f8e
chjaju/ssss
/ex110.py
395
4.25
4
#if문이 참이므로 아래있는 else : print("4")는 필요없고 if False: print("1") print("2") else: print("3")으로 간후 참이므로 false문으로 가지않고 #else로 가서 3이 출력된다. if True : if False: print("1") print("2") else: print("3") else : print("4") #if문이 끝났으므로 5가 또 출력된다. print("5") #정답=3,5
false
66c2d50408a5846a0a4e8e3dc22c1bced2f28345
namuthan/codingChallenges
/longestWord.py
629
4.3125
4
""" Using the Python language, have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. """ import re def LongestWord(sen = ""): words = re.sub('[^A-Za-z0-9]+', ' ', sen).split(" ") longest_word = words[0] for word in words: if len(word) > len(longest_word): longest_word = word return longest_word # keep this function call here print(LongestWord("I love dogs"))
true
7c5ca6ea977f11f8f1e144255c34b765a7b2c6ae
BillZong/CorePythonProgrammingDemos
/11/11.7.py
924
4.5
4
#!/usr/bin/env python """Answer for 11.7 in chapter 11.""" def two_list_to_tuple_list(list1, list2, mapper=map): """Using mapper function to 'zip' two lists into one.""" if len(list1) != len(list2): return None else: if mapper == map: return mapper(None, list1, list2) else: return mapper(list1, list2) print two_list_to_tuple_list([1, 2, 3], ['abc', 'def', 'ghi']) print two_list_to_tuple_list([1, 2, 3], ['abc', 'def', 'ghi'], zip) print '' # def my_zip(list1, list2): # """My implemetation of zip function.""" # return [(list1[i], list2[i]) for i in range(len(list1))] # print two_list_to_tuple_list([1, 2, 3], ['abc', 'def', 'ghi'], my_zip) connect = two_list_to_tuple_list print connect([1, 2, 3], ['abc', 'def', 'ghi'], lambda list1, list2: [(list1[i], list2[i]) for i in range(len(list1))])
false
c1031fce78974833bd1212b04233affa2e938091
hevalenc/Python-Complete-Course-For-Beginners
/global_local_nonlocal.py
638
4.15625
4
print('Alterando a variável Global com uma função') x = 'global' def function1(): global x y = 'Local' x = x * 2 print('x: ', x) print('y: ', y) print('Global x: ', x) function1() print('Global x: ', x) #a função alterou a variável x print('\nGlobal e Local sem alterações') a = 5 def function2(): a = 10 print('Local a: ', a) print('Global a: ', a) function2() print('Global a: ', a) print('\nCriando e usando uma variável NonLocal') def outer(): x = 'Local' def inner(): nonlocal x x = 'nonlocal' print('Inner: ', x) inner() print('Outer: ', x) outer()
false
8dab6a432c805ee78c8d27de9be80511ffb40712
hevalenc/Python-Complete-Course-For-Beginners
/inheritance.py
1,332
4.3125
4
print('Herança em Python') '''Criando um classe e um objeto em Python''' class myBird: def __init__(self): print('... myBird class constructor is executing ...') def whatType(self): print('I am a Bird ...') def canSwim(self): print('I can swim ...') '''A classe myPenguin herdando os atributos da classe myBird''' class myPenguin(myBird): def __init__(self): super().__init__() print('... myPenguin class constructor is executing ...') def whoisThis(self): print('I am a Penguin ...') def canRun(self): print('I can run faster ...') print('\nAcessando os atributos da classe filha (herança)') pg1 = myPenguin() pg1.whatType() pg1.whoisThis() pg1.canSwim() pg1.canRun() print('\nPoliformismo') class myParrot: def canFly(self): print('Parrot can fly ...') def canSwin(self): print('Parrot can´t swim ...') class myPenguin: def canFly(self): print('Penguin can´t fly ...') def canSwin(self): print('Penguin can swim ...') '''Interface comum''' def flying_bird_test(bird): bird.canFly() bird.canSwin() '''instanciando os objetos''' bird_parrot = myParrot() bird_penguin = myPenguin() '''passando os objetos''' flying_bird_test(bird_parrot) print() flying_bird_test(bird_penguin)
false
410b303b9d8a44a616ee54369759ff11676e2849
Indiana3/python_exercises
/wb_chapter7/exercise155.py
1,378
4.46875
4
## # Compute and display the frequencies of words in a .txt file # import sys import re # Check if the user entered the file name by command line if len(sys.argv) != 2: print("File name missing...") quit() try: # Open the file fl = open(sys.argv[1], "r", encoding="utf-8") # Dict to store words/freqs words_freq = {} # Chars to remove from lines to_remove = "[.,;!?':\"\n0123456789]" # Start with the first line line = fl.readline() # For each line while line != "": # Remove the set of chars line = re.sub(to_remove, "", line) # Split the line in a list of words words = line.split() # Traverse the list and count the occurences of # each word for word in words: word = word.lower() if word not in words_freq: words_freq[word] = 1 else: words_freq[word] += 1 # Move to the next line line = fl.readline() # Display letters with their frequencies print("Word\t\tFrequence") for word, freq in words_freq.items(): print(word.ljust(10), "\t", freq) # Close the file fl.close() # Display an error message if the file can't be opened except FileNotFoundError: print("The file you entered could have been typed uncorrectly or could not exist")
true
070f8b715723c85a202de9d328558cb2b72ed597
Indiana3/python_exercises
/wb_chapter4/exercise95.py
1,730
4.15625
4
## # Capitalize letters in a string typed uncorrectly # ## Capitalize all the letters typed uncorrectly # @param s a string # @return the string with the letters capitilized correctly # def capitilizeString(s): # Create an empty string where adding # each character of s, capitilized or not capitilized cap_char_s = "" # Set the position of chars in s equal to 0 position = 0 # Check each character in s while position < len(s): # Capitilize the first non-space character in s # Capitilize the first non-space character after ".", "!", "?" # Capitilize "i" if preceded by " " and followed by " ", "!", "?", "'" if position == 0 or \ s[position-2] == "." and s[position-1] == " " or \ s[position-2] == "!" and s[position-1] == " " or \ s[position-2] == "?" and s[position-1] == " " or \ s[position] == "i" and s[position-1] == " " or \ s[position] == " " and s[position-1] == "i" or \ s[position] == "." and s[position-1] == "i" or \ s[position] == "!" and s[position-1] == "i" or \ s[position] == "?" and s[position-1] == "i" or \ s[position] == "'" and s[position-1] == "i": cap_char_s += s[position].upper() else: # Add the lowercase character cap_char_s += s[position] # Move position in s position = position + 1 return cap_char_s # Read a string from the user def main(): s = input("Please, type any string you want: ") # Display the capitilize string calling capitilizeString function print(capitilizeString(s)) # Call the main function main()
true
0a748aad2adcad109c20284b89a28db46dd014fd
Indiana3/python_exercises
/wb_chapter5/exercise134.py
846
4.28125
4
## # Display all the possible sublists of a list # ## Compute all the sublists in a list of elements # @param t a list # @return all the possible sublists # def sublists(t): # Every list has a default empty list as sublist sublists = [] sublists.append([]) # Find all the sublists of the list for i in range(len(t)): for j in range(len(t), i, -1): sublists.append(t[i:j]) return sublists # Show the sublists of the following lists def main(): print(sublists(["casa", "albero", "giardino", "legnaia", "orto"])) print(sublists([1, 2, 3, 4, 5])) print(sublists([23.3, 12.1, 18.7, 90.2])) print(sublists(["studio", "lavoro", "amore", "relazioni", "sport", "meditazione", "hobbies"])) print([]) print(["olistico"]) # Call the main function if __name__ == "__main__": main()
true
9bfedd8151a9f2906f702f67cdcdde63996464b1
Indiana3/python_exercises
/wb_chapter5/exercise128.py
1,498
4.28125
4
# Determine the number of elements in a list greater than # or equal to a minimum value and lower than a maximum value # ## Determine the number of elements in a list that are # greater than or equal a min value and less than # a max value # @param t a list of value # @param min a minimum value # @param max a maximum value # @return an integer greater than or equal to 0 # def countRange(t, min, max): counter = 0 for i in range(len(t)): if t[i] >= min and t[i] < max: counter += 1 return counter # Store some values in a list and determine how many values # are greater than or equal to a min value and less than # a maximum value def main(): values = [] # Read a value from user until a blank string is entered num = input("Please, enter a number (blank to stop): ") while num != "": # Add num to values values.append(float(num)) num = input("Please, enter a number (blank to stop): ") # Enter a minimum value min_value = float(input("Please, enter a minimum value: ")) # Enter a maximum value max_value = float(input("Please, enter a maximum value: ")) # Check how many elements in the list are greter than or equal to min_value # and less than max_value counter = countRange(values, min_value, max_value) # Display the occurrences print("There are %i elements between %.2f and %.2f" %(counter, min_value, max_value)) # Call the main function if __name__ == "__main__": main()
true
2edb1fe95a4245ad15af957212ad5e915c34fa4a
Indiana3/python_exercises
/wb_chapter2/exercise48.py
1,453
4.5625
5
## # Determine the astrological sign that matches the user's birth date # # Read the date of birth month = input("Please, enter your month of birth: ") day = int(input("And now the day: ")) # Determine the astrological sign that matches the birth date if month == "December" and day >= 22 or month == "January" and day <= 19: sign = "Capricorn" elif month == "January" and day >= 20 or month == "February" and day <= 18: sign = "Acquarius" elif month == "February" and day >= 19 or month == "March" and day <= 20: sign = "Pisces" elif month == "March" and day >= 21 or month == "April" and day <= 19: sign = "Aries" elif month == "April" and day >= 20 or month == "May" and day <= 20: sign = "Taurus" elif month == "May" and day >= 21 or month == "June" and day <= 20: sign = "Gemini" elif month == "June" and day >= 21 or month == "July" and day <= 22: sign = "Cancer" elif month == "July" and day >= 23 or month == "August" and day <= 22: sign = "Leo" elif month == "August" and day >= 23 or month == "September" and day <= 22: sign = "Virgo" elif month == "September" and day >= 23 or month == "October" and day <= 22: sign = "Libra" elif month == "October" and day >= 23 or month == "November" and day <= 21: sign = "Scorpio" elif month == "November" and day >= 22 or month == "December" and day <= 21: sign = "Sagittarius" # Display the result print("Your astrological sign is", sign)
true
9bfdcb6fd86a453a9a4267d3e03c0be44b45582c
Indiana3/python_exercises
/wb_chapter5/exercise115.py
707
4.375
4
## # Read a positive integer and compute all its proper divisors # ## Find the proper divisors of a positive integer # @param n a positive integer # @return a list with all the positive integers def proper_divisors(n): divisors = [] for i in range (1, n): if n % i == 0: divisors.append(i) return divisors # Read a positive integer from user and display its proper divisors def main(): num = int(input("Please, enter a positive integer: ")) if num <= 0: print("You didn't enter a positive number") else: print("The proper divisors of {} are: {}".format(num, proper_divisors(num))) # Call the main function if __name__ == "__main__": main()
true
56d8bec45b39efe200f98f8223cfd525ae98aa32
Indiana3/python_exercises
/wb_chapter8/exercise174.py
792
4.3125
4
## # Compute the greatest common divisor of 2 positive integers # ## Compute the greatest common divisor of 2 positive integers # @param a the first positive integer # @param b the second positive integer # @return the greatest common divisor # def greatestCommonDivisor(a, b): # Base case if b == 0: return a # Recursive case c = a % b return greatestCommonDivisor(b, c) # Read 2 positive integers from user # Display the greatest common divisor def main(): a = int(input("Please, enter a positive integer: ")) b = int(input("Please, enter another positive integer: ")) divisor = greatestCommonDivisor(a, b) print("The greatest common divisor of %d and %d is %d" % (a, b, divisor)) # Call the main function if __name__ == "__main__": main()
true
6dd3a8df69d2504b38ad061533604419703443ba
Indiana3/python_exercises
/wb_chapter1/exercise14.py
422
4.5
4
## # Convert height entered in feet and inches into centimeters # IN_PER_FT = 12 CM_PER_INCH = 2.54 # Read a number of feet and a number of inches from users print("Please, enter yout height: ") feet = int(input(" Number of feet: ")) inches = int(input(" Number of inches: ")) # Compute the equivalent in centimeters cm = (feet * IN_PER_FT + inches) * CM_PER_INCH # Display the output print("Your height is", cm, "cm")
true
240b19450b6a93c65f5fbe9fff922fdbb930a733
Indiana3/python_exercises
/wb_chapter7/exercise157.py
2,007
4.34375
4
## # Convert grade points to letter grade and viceversa # # Create a dictionary with letter grades as keys # and grade points as values letter_points = { "A+" : 4.1, "A" : 4.0, "A-" : 3.7, "B+" : 3.3, "B" : 3.0, "B-" : 2.7, "C+" : 2.3, "C" : 2.0, "C-" : 1.7, "D+" : 1.3, "D" : 1.0, "F" : 0.0 } # Read the first grade from the user grade = input("Please, enter a grade point or letter grade: ") # Until the user doesn't enter a blank line while grade != "": try: # If the grade is a float value, convert it # to its corrisponding letter grade grade = float(grade) if grade > 4.0: print("A+") elif grade >= 3.8 and grade <= 4.0: print("A") elif grade >= 3.5 and grade < 3.8: print("A-") elif grade >= 3.2 and grade < 3.5: print("B+") elif grade >= 2.9 and grade < 3.2: print("B") elif grade >= 2.5 and grade < 2.9: print("B-") elif grade >= 2.2 and grade < 2.5: print("C+") elif grade >= 1.9 and grade < 2.2: print("C") elif grade >= 1.5 and grade < 1.9: print("C-") elif grade >= 1.2 and grade < 1.5: print("D+") elif grade >= 0.5 and grade < 1.2: print("D") elif grade >= 0.0 and grade < 0.5: print("F") # Display an error message if the float number is negative else: print("There's no negative scores") except: # If the grade is a letter, convert it # to its corresponding grade points try: grade = grade.upper() print(letter_points[grade]) except: # Display an error message if the letter isn't in the dictionary print("The supplied input is invalid") # Ask to the following grade grade = input("Please, enter another grade point or letter grade: ")
true
87a7b85c749279065e38f94e7d9454216a3208bd
Indiana3/python_exercises
/wb_chapter4/exercise94.py
812
4.46875
4
## # Determine if three lengths can form a triangle # # Check if three lengths form a triangle # @param a the length 1 # @param b the length 2 # @param c the length 3 # return True if a, b, c are sides of a valid triangle # return False if they are not def isATriangle(a, b, c): if a <= 0 or b <= 0 or c <= 0: return False if a >= b + c or b >= c + a or c >= a + b: return False return True # Read three lengths from the user def main(): a = float(input("Please, enter the first length: ")) b = float(input("Please, enter the second length: ")) c = float(input("Please, enter the third length: ")) # Display the result calling isATriangle function print("{},{},{} can form a triangle? {}".format(a, b, c, isATriangle(a, b, c))) # Call the main function main()
true
d714ad0bb8fe99a43d296e83f2791351bf9e6d38
Indiana3/python_exercises
/wb_chapter5/exercise121.py
698
4.1875
4
## # Generates 6 numbers from 1 to 49 with no duplicates # Display them in ascending order # from random import randint # Each ticket has 6 numbers NUMBERS_FOR_TICKET = 6 # Numbers drawn are between 1 and 49 FIRST_NUMBER = 1 LAST_NUMBER = 49 # Start with an empty list ticket_numbers = [] # Generate 6 random numbers between 1 and 49 # Add each number to the list only if it's not already there while len(ticket_numbers) < NUMBERS_FOR_TICKET: num = randint(FIRST_NUMBER, LAST_NUMBER) if num not in ticket_numbers: ticket_numbers.append(num) # Sort the numbers in ascending order ticket_numbers.sort() # Display the numbers for number in ticket_numbers: print(number)
true
9ef996f50bfb3c0ec5fc60eb9ca597d8b05c17fb
Indiana3/python_exercises
/wb_chapter3/exercise68.py
1,630
4.21875
4
## # Convert a sequence of letter grades into grade points # and compute its avarage # A = 4.0 A_MINUS = 3.7 B_PLUS = 3.3 B = 3.0 B_MINUS = 2.7 C_PLUS = 2.3 C = 2.0 C_MINUS = 1.7 D_PLUS = 1.3 D = 1.0 F = 0.0 # Initialize to 0 the sum of grade points # Initialize to 0 the number of letter grades entered total_points = 0 grades_entered = 0 # Read the first letter grade from the user letter_grade = input ("Please, enter a letter grade: ") # Convert into grade points while letter_grade != "": # Convert lowercase chars (if any) in uppercase chars letter_grade = letter_grade.upper() if letter_grade == "A+" or letter_grade == "A": points = A elif letter_grade == "A-": points = A_MINUS elif letter_grade == "B+": points = B_PLUS elif letter_grade == "B": points = B elif letter_grade == "B-": points = B_MINUS elif letter_grade == "C+": points = C_PLUS elif letter_grade == "C": points = C elif letter_grade == "C-": points = C_MINUS elif letter_grade == "D+": points = D_PLUS elif letter_grade == "D": points = D elif letter_grade == "F": points = F # Sum the converted points to the previous points total_points = total_points + points # Increment of 1 the number of letter grades entered grades_entered = grades_entered + 1 letter_grade = input ("Please, enter the next letter grade: ") # Compute the avarage of grade points points_avarage = total_points / grades_entered # Display the result print("The avarage of grade points is %.2f" % points_avarage)
true
a7990f956d2ae393b4a92180de64a25341560c70
Indiana3/python_exercises
/wb_chapter2/exercise39.py
379
4.5
4
## # Display the number of days in a month # # Read the month month = input("Please, enter the name of a month: ") # Compute the number of days in a month days = 31 if month == "april" or month == "june" or month == "september" or month == "november": days = 30 elif month == "february": days = "28 or 29" # Display the result print(month, "has", days, "days in it")
true
8d24e50857024702e28bf41c258d9c0be6f75ee0
Indiana3/python_exercises
/wb_chapter2/exercise45.py
627
4.40625
4
## # Display if the day and month entered match one of # the fixed-date holiday # # Read the month and the day from the user print("Please, enter: ") month = input("the name of a month (like January): ") day = int(input("a day of the month: ")) # Determine if month and day match a fixed-date holiday if month == "January" and day == 1: print(month, day, "is New Year's Day" ) elif month == "July" and day == 1: print(month, day, "is Canada Day" ) elif month == "December" and day == 25: print(month, day, "Christmas Day" ) else: print("The entered month and day don't correspond to any fixed-date holiday")
true
b07dbba62277f34936ea44beac14c6f6b5b723e1
Indiana3/python_exercises
/wb_chapter2/exercise37.py
459
4.53125
5
## # Display whether a letter is a vowel, semi-vowel or consonant # # Read the letter letter = input("Please, enter a letter: ") # Determine whether the letter is a vowel, semi-vowel or consonant if letter == "a" or letter == "e" or \ letter == "i" or \ letter == "o" or letter == "u": print("The entered letter is a vowel") elif letter == "y": print("The entered letter is a semi-vowel") else: print("The entered letter is a consonant")
true
d98256ff20e7c8f16eefdbfbe6194f9ea30978d5
Indiana3/python_exercises
/wb_chapter1/exercise31.py
534
4.21875
4
## # Convert kilopascals to pounds per square inch, # millimeters of mercury and atmospheres # PA_IN_KPA = 1000 PA_IN_PSI = 6895 PA_IN_MMHG = 133.322 PA_IN_ATM = 101325 # Read the pressure in KPa kpa = float(input("Please, enter a pressure" \ " in KPa: ")) # Convert to PSI psi = kpa / PA_IN_KPA * PA_IN_PSI # Convert to mmHg mmhg = kpa / PA_IN_KPA * PA_IN_MMHG # Convert to atm atm = kpa / PA_IN_KPA * PA_IN_ATM # Display the results print(kpa, "KPa are equal to: ") print(psi, "psi") print(mmhg, "mmHg") print(atm, "atm")
false
b7f8e9548744f01241a2a6620f0d423049be4cc6
Indiana3/python_exercises
/wb_chapter5/exercise119.py
1,470
4.25
4
## # Read a series of values from the user, # compute their avarage, # print all the values before the avarage # followed by the values equal to the avarage (if any) # followed by the values above the avarage # # Start with an empty list values = [] # Read values from user until blank line is entered value = input("Please, enter a value: ") while value != "": value = float(value) values.append(value) value = input("Please, enter another value: ") # Compute the avarage of the values in the list avarage = sum(values) / len(values) # Create a list for values below the avarage # followed by one for values equal to avarage # followed by on for values above the avarage below_avarage = [] equal_to_avarage = [] above_avarage = [] # For each value in values, determine if it's smaller, equal or greater than avarage # and add it to the appropriate list for i in range(len(values)): if values[i] < avarage: below_avarage.append(values[i]) elif values[i] == avarage: equal_to_avarage.append(values[i]) elif values[i] > avarage: above_avarage.append(values[i]) # Print below_avarage, equal_to_avarage and above avarage lists print("Values below {} are:".format(avarage)) for value in below_avarage: print(" ", value) print("Values equal to {} are:".format(avarage)) for value in equal_to_avarage: print(" ", value) print("Values above {} are:".format(avarage)) for value in above_avarage: print(" ", value)
true
9e20a1c8b86d3447270e08a2dffcaa246ff479b6
ITh4cker/ATR_HAX_CTF
/crypto/light_switch_crypto/challenge/solve_me.py
2,869
4.375
4
""" This script reads from "key" and "encrypted_flag" and uses "magic_func" to convert the encrypted flag into its decoded version. You are asked to implement the magic_func as described in CTF_1.png Successful decryption should print a valid flag (ATR[....]) in the console. This script is expected to run with python3. """ import string def magic_func(A, B): ################################################################################# # # # Modify the function starting here # # # ################################################################################# # Implement here the circuit logic described in "CTF_1.png" # The output of magic_func is the variable 'o' # 'o' needs to be a bit (a python integer that is either 0 or 1) # Input are A and B as seen in the diagram, and are also bits as defined above. # You can use logical operators such as & | ^ ~ on A and B o = 0 return o def tobits(s): # This function coverts a list of bytes (represented as a string) # into its binary representation result = [] for c in s: bits = bin(ord(c))[2:] #convert unicode of every character to binary ([2:] since remove 0b) bits = '00000000'[len(bits):] + bits #append 0's in front result.extend([int(b) for b in bits]) #add to list and return return result def frombits(bits): # This function converts a list of bits (reprenseted as integer in the range 0,1) # into a a list of bytes (represented as a string) chars = [] for b in range(int(len(bits)/8)): #divide by 8 byte = bits[b*8:(b+1)*8] #take chunks of 8 bits and convert to string chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(chars) def main(): # First load the key and the encrypted flag with open('key', 'r') as fa: key = ''.join(fa.readlines()) print('\n Reading my key: ', key, '\n') with open('encrypted_flag', 'r') as f: msg = ''.join(f.readlines()) print('\n Reading encrypted flag: ', msg, '\n') # Convert key and message as their binary representation b_msg = tobits(msg) b_key = tobits(key) o = [] # Array of bits that will contains the decoded message print('\n *** Complete magic_func *** \n') for i in range(len(b_msg)): # Iterates over each byte of the message and the key # And feed them to the magic function for "decoding" o.append(magic_func(b_msg[i], b_key[i])) new_o = frombits(o) # Converts the decoded message from bit to string print("\n Output: ", new_o, '\n') if __name__== "__main__": main()
true
e7860a52633ea24a1f729bc4ca837c943f6d9489
calumpetergunn/functions_lab
/src/python_functions_practice.py
1,559
4.21875
4
def return_10(): return 10 def add(number_1, number_2): return number_1 + number_2 def subtract(number_1, number_2): return number_1 - number_2 def multiply(number_1, number_2): return number_1 * number_2 def divide(number_1, number_2): return number_1 / number_2 def length_of_string(string): return len(string) def join_string(string_1, string_2): return string_1 + string_2 def add_string_as_number(string_1, string_2): return int(string_1) + int(string_2) # def number_to_full_month_name(month): # import calendar # return calendar.month_name[month] months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] def number_to_full_month_name(number): number = number - 1 return months[number] # print(number_to_full_month_name(12)) def number_to_short_month_name(month): return number_to_full_month_name(month)[0:3] # print(number_to_short_month_name(10)) def volume_of_cube(length_of_side): return length_of_side ** 3 # print(volume_of_cube (3)) def string_reverse(str): string_reversed = '' index = len(str) while index > 0: string_reversed += str [index - 1] index = index - 1 return string_reversed # print (string_reverse("Scotland")) # ALSO - much simpler # def string_reverse(str): # return str[::-1] def fahrenheit_to_celcius(fahrenheit): celcius = (fahrenheit - 32) * (5.0/9.0) print(f"The value before rounding is {celcius}") return round(celcius, 2)
false
a904d64fcfe0e3a5b08e87478c64ce09d6159d20
MaximUltimatum/Booths_Algorithm
/booths_algorith.py
938
4.125
4
#! usr/bin/python def booths_algorithm(): multiplicand_dec = input('Please enter your multiplicand: ') multiplier_dec = input('Please enter your multiplier: ') multiplicand_bin = twos_complement(multiplicand_dec) multiplier_bin = twos_complement(multiplier_dec) print(multiplicand_bin) print(multiplier_bin) return def twos_complement(dec): #Convert to dec, adding 1, then removing negative adjusted = abs(int(dec) + 1) #Turns into binary number binint = "{0:b}".format(adjusted) #Flip bits flipped = flip(binint) # Iterates through and makes the binary value 4 for i in range(4-len(flipped)): flipped = "1" + flipped return flipped def flip(string): flipped_string = "" for bit in string: if bit == "1": flipped_string += "0" else: flipped_string += "1" return flipped_string booths_algorithm()
true
4d765644d6e5a7bbe84541972a16ccd2865e5489
azalio/learn_alg
/selection_sort.py
994
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint def selection_sort(rand_list): for position in range(0, len(rand_list)): min_position = find_min(rand_list, position) swap(rand_list, position, min_position) position += 1 return rand_list def find_min(rand_list, position): min_value = rand_list[position] min_index = position for i in range(position + 1, len(rand_list)): if rand_list[i] < min_value: min_value = rand_list[i] min_index = i return min_index def swap(rand_list, position, new_position): rand_list[position], rand_list[new_position] = rand_list[new_position], rand_list[position] return True def main(): # generate random list list_len = randint(5, 20) rand_list = [] while(list_len >= 0): rand_list.append(randint(0, 100)) list_len -= 1 print('List before selection sort alg:\n{}'.format(rand_list)) print('List after selection sort alg:\n{}'.format(selection_sort(rand_list))) if __name__ == '__main__': main()
false
c62620a95f843279a23f63dd91539072da06f283
ninja-programming/python-basic-series
/for_loop_examples.py
1,484
4.34375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 30 01:40:11 2021 @author: mjach """ '''For look examples''' my_fruits_list = ['apple', 'orange', 'banana', 'watermelon'] #checking is the fruit in my list print('Is this fruit in my list?:', 'apple' in my_fruits_list) '''for loop example''' # for fruit in my_fruits_list: # print(f'Fruit name is :{fruit}') '''how to use range() function in for loop - here range 0 is inclusive I mean 0 will print it will start from 0 and 4 is exclusive I mean 4 will not print, it will stop to number 3 ''' # for number in range(11): # print(f'Number is : {number}') '''How to print specific number within range we can specify start and end. here number 1 is inclusiveand number 10 is exclusive ''' # for number in range(1, 10): # print(f'Here number will print from 1 to 9: {number}') '''range() function another use specify start, end, increment ''' # for number in range(2, 20, 2): # print(f'Number is :{number}') '''How to print out the index of the items we can use buit in function enumerate ''' # for index, fruit in enumerate(my_fruits_list): # print(f'Fruit :{fruit} is at index no : {index}') '''how to use for loop in dictionary''' my_fruit_dict= {1:'apple', 2:'orange', 3:'banana', 4:'watermelon'} # for fruit in my_fruit_dict: # print(f'That will return only keys of the dict.: {fruit}') for keys, values in my_fruit_dict.items(): print(f'Fruit :{values} is at {keys} ')
true
34933504a0772f57dc179df6824378109f82b1bd
ninja-programming/python-basic-series
/user_input_example.py
685
4.21875
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 5 03:13:49 2021 @author: mjach """ ''' How to take input from the user ''' # fruit = input('What fruit do you like?: ') # print('I like ', fruit) # #input always take as a string # #if you put neumaric number you have to converted it to int format # first_number = int(input('Enter a first number:')) # second_number = int(input('Enter a second number:')) # total = first_number + second_number # print('Total is:', total) #what if, if you do not converted it to int format first_number = input('Enter a first number:') second_number = input('Enter a second number:') total = first_number + second_number print('Total is:', total)
true
cc06e7ff87923e871d168d43d5981f5b1f0b1d44
ivandos/python-quiz
/prime_num.py
678
4.1875
4
# Задача 2: "Наибольший простой делитель" # Простые делители числа 13195 - это 5, 7, 13 и 29. # Каков самый большой делитель числа 600851475143, являющийся простым числом? import math def biggest_divider(num: int): ''' Function to find the biggest divider of a simple value ''' max_num = 0 for i in range(2, int(math.sqrt(num)) + 1): while num % i == 0: max_num = i num = num / i return max_num # Test # number = 13195 # print(biggest_divider(number)) number = 600851475143 print(biggest_divider(number))
false
b8218ce3cdfab46aaa1ebe310e5f2496904f136c
JpradoH/Ciclo2Java
/Ciclo 1 Phyton/Unidad 2/Ejercicios/Funcion Format.py
733
4.1875
4
# saca "El valor es 12 print ("El valor es {}".format(12)) # saca "El valor es 12.3456 print ("El valor es {}".format(12.3456)) # Tres conjuntos {}, el primero para el primer parámetro de format(), el segundo para el segundo # y así sucesivamente. # saca "Los valores son 1, 2 y 3" print ("Los valores son {}, {} y {}".format(1,2,3)) # Entre las llaves podemos poner la posición del parámetro. {2} es el tercer parámetro de format() # {0} es el primer parámetro de format. # saca "Los valores son 3, 2 y 1" siempre y cuando este dentro del rango de posicion. print ("Los valores son {2}, {1} y {0}".format(1,2,3)) #re fiere al tema de parametros por omicion. # saca "2 y 1" print ("{pepe} y {juan}".format(juan=1, pepe=2))
false
ed99ff3dcc7cdc2dd4dbebe6840e3812fb547a41
AlyoshaS/ProgFuncional-Python
/Exercicios-Prog-Funcional/4.py
490
4.125
4
#!/usr/bin/python # coding: latin-1 # início - recursão mútua # 04. Defina dois predicados lógicos '[even]' e '[odd]' que # indiquem se um número 'n' passado como argumento é par ou ímpar respectivamente. # Não é permitido o uso do operador '%' (resto da divisão). def even(n): if n == 0: return True else: return odd(n-1) def odd(n): if n == 0: return False else: return even(n-1) print(even(5), even(6)) print(odd(5), odd(6))
false
ecb414331eb8969f0d1bc41769c25cec5dff9c9a
nmichel123/PythonPractice
/firstprogram.py
224
4.1875
4
def say_hi(name): if name == '': print("You did not enter your name!") else: print("Hey there...") for letter in name: print(letter) name = input("Type in your name!") say_hi(name)
true
a302427405ab86e1db5137d2f12df354401066be
Rahulkumar-source/Albanero_Task_Pratice
/problem5.py
536
4.125
4
def checkOutlier(arr): oddCount = 0 evenCount = 0 for item in arr: if item % 2 == 0: evenCount += 1 else: oddCount +=1 # This is going to print the count of item if even or odd # print(oddCount, evenCount) if oddCount == 1: for item in arr: if item % 2 != 0: print(item) if evenCount == 1: for item in arr: if item % 2 == 0: print(item) print(checkOutlier([1,2,3]))
true
e0a15db4596363ba96f9372234b8971a91a4a4e9
nchapin1/codingbat
/logic-1/cigar_party_mine.py
658
4.21875
4
def cigar_party(cigars, is_weekend): """When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise.""" if is_weekend == False: return 40 <= cigars <= 60 if is_weekend == True: return 40 <= cigars # Solution """ def cigar_party(cigars, is_weekend): if is_weekend: return (cigars >= 40) else: return (cigars >= 40 and cigars <= 60) """
true
833dcac2c6987ea820f492b73f7ed48d41b47806
giri110890/python_gfg
/Control_Flow/__iter__and__next__.py
1,941
4.5
4
# Python code demonstrating basic use of iter() listA = ['a', 'e', 'i', 'o', 'u'] iter_listA = iter(listA) try: print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) print( next(iter_listA)) #StopIteration error except: pass # Python code to demonstrate basic use of iter() lst = [1, 2, 3, 4] iter_lst = iter(lst) while True: try: print(iter_lst.__next__()) except: break # Python code demonstrating # basic use of iter() listB = ['Cat', 'Bat', 'Sat', 'Mat'] iter_listB = listB.__iter__() try: print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) print(iter_listB.__next__()) #StopIteration error except: print(" \nThrowing 'StopIterationError'", "I cannot count more.") # USer defined objects # Python code showing use of iter() using OOPS class Counter: def __init__(self, start, end): self.num = start self.end = end def __iter__(self): return self def __next__(self): if self.num > self.end: raise StopIteration else: self.num += 1 return self.num - 1 # Driver code if __name__ == "__main__": a, b = 2, 5 c1 = Counter(a, b) c2 = Counter(a, b) # Way 1-to print the range without iter() print("Print the range without iter()") for i in c1: print ("Eating more Pizzas, couting ", i, end ="\n") print ("\nPrint the range using iter()\n") # Way 2-using iter() obj = iter(c2) try: while True: print("eating more Pizzas, counting ", next(obj)) except: # When StopIteration raise, Print custom message print("\nDead on overfood, GAME OVER")
false
dfdea4321eb8f4e514469bbc73d532c9542477ce
giri110890/python_gfg
/Functions/partial_functions.py
540
4.28125
4
# Partial functions allows us to fix a certain number of arguments of a function # and generate a new function from functools import * # A normal function def f(a, b, c, x): return 1000 * a + 100 * b + 10 * c + x # A partial function that calls f with a as 3, b as 1 and c as 4 g = partial(f, 3, 1, 4) # Calling g() print(g(5)) # A normal function def add(a, b, c): return 100 * a + 10 * b + c # A partial function with b = 1 and c = 2 add_part = partial(add, c = 2, b = 1) # Calling partial function print(add_part(3))
true
4b825fb64a8c2a660fc38bc53006992ff3344b91
giri110890/python_gfg
/Functions/args_and_kwargs.py
1,386
4.71875
5
# Python program to illustrate # *args for variable number of arguments def myFun(*argv): for arg in argv: print(arg) myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') # Python program to illustrate **kwargs for variable number of keyword # arguments def myFun1(**kwargs): for key, value in kwargs.items(): print("%s == %s" %(key, value)) # Driver code myFun1(first = 'Geeks', mid = 'for', last = 'Geeks') # Python program to illustrate **kargs for # variable number of keyword arguments with # one extra argument. def myFun3(arg1, **kwargs): print(arg1) for key, value in kwargs.items(): print ("%s == %s" %(key, value)) # Driver code myFun3("Hi", first ='Geeks', mid ='for', last='Geeks') # Using *args and **kwargs to call a function def myFun4(arg1, arg2, arg3): print("arg1:", arg1) print("arg2:", arg2) print("arg3:", arg3) # Now we can use *args or **kwargs to pass arguments to this function: args = ("P", "v", "r") myFun4(*args) kwargs = {"arg1" : "Geeks", "arg2" : "for", "arg3" : "Geeks"} myFun4(**kwargs) # Using *args and **kwargs in same line to call a function def myFun5(*args, **kwargs): print("args: ", args) print("kwargs: ", kwargs) # Now we can use both *args ,**kwargs to pass arguments to this function : myFun5('geeks','for','geeks',first="Geeks",mid="for",last="Geeks")
true
9e1dc0c1ceddd29cde85c60493b5e25b12c387fd
loukey/pythonDemo
/chap2/exp2.6.py
1,142
4.34375
4
# -*- coding: utf-8 -*- #例2.6完整的售价程序设计 def input_data_module(): print 'What is the item\'s name?' item_name = raw_input() print 'What is its price and the percentage discounted?' original_price = input() discount_rate = input() return item_name,original_price,discount_rate def calculations_module(): item_name, original_price, discount_rate = input_data_module() amount_saved = original_price*(discount_rate/100) sale_price = original_price-amount_saved tax = sale_price*0.065 total_price = sale_price+tax return item_name,original_price,discount_rate,sale_price,tax,total_price def results_module(): item_name, original_price, discount_rate, sale_price, tax, total_price = calculations_module() print 'The item is:',item_name print 'Pre-sale Price was:$',original_price print 'Percentage discounted was:',discount_rate,'%' print 'Sale price:$',sale_price print 'Sales tax:$',tax print 'Total:$',total_price print 'Sale Price Program' print 'This program computes the total price, including tax,of' print 'an item that has been discounted a certain percentage.' results_module()
true
172091debab9edbadaa32fe6d09e1cebe6a4bbde
LiliaMudryk/json_navigation
/navigation.py
2,018
4.625
5
''' This module allows to carry out navigation through any json file. ''' import json def read_json_file(path): """ Reads json file and returns it in dictionary format """ json_file = open(path,mode="r",encoding="UTF-8") json_data = json_file.read() obj = json.loads(json_data) return obj def navigation(obj): """ Goes through json file and shows its structure """ if isinstance(obj,dict): print() print("This object is dictionary") keys = list(obj.keys()) print() print(keys) print() user_choice = input("Here are keys of this dictionary. \ Please enter name of key you want to see: ") next_element = obj[user_choice] elif isinstance(obj,list): print() print("This object is list.") print() user_choice = input('This list consists of '+str(len(obj))+' elements. \ Please enter number from 0 to '+str(len(obj)-1)+' \ to choose number of element you want to display: ') next_element = obj[int(user_choice)] else: print() user_choice = '' if isinstance(obj,str): user_choice = input('This object is a string. Do you want to display it?\ (Enter yes or no): ') elif isinstance(obj,bool): user_choice = input('This object is a boolean. Do you want to display it?\ (Enter yes or no): ') elif isinstance(obj,int): user_choice = input('This object is a integer. Do you want to display it?\ (Enter yes or no): ') elif isinstance(obj,float): user_choice = input('This object is a float number. Do you want to display it?\ (Enter yes or no): ') else: print(obj) if user_choice == 'yes': print(obj) print() print('This is the end of the file.') return 0 return navigation(next_element) if __name__ == '__main__': path_to_file = input('Enter path to file: ') navigation(read_json_file(path_to_file))
true
e207f0bb2269b3c535ba3d33e06b729f0d4fedb4
ShikhaShrivastava/Python-core
/OOP Concept/Operator Overloading.py
1,768
4.21875
4
'''Operator Overloading''' #type-1 '''print(10+20+30) #addition print('sh'+'ik'+'ha') #concatination''' #**********MAGIC METHOD******************* #type-2 '''class Book: def __init__(self,page): self.page=page b1=Book(200) b2=Book(400) #print(b1+b2) --->TypeError :Unsupported operand type print(b1.page+b2.page)''' #*************************************************************** #type-3 class Book: def __init__(self,page): self.page=page def __add__(self,other): print(id(self)) print(id(other)) return self.page+other.page #b1.page+b2.page b1=Book(200) b2=Book(400) print(id(b1)) print(id(b2)) print(b1+b2) #************************************************************** #type-4 '''class Book: def __init__(self,page): self.page=page def __add__(self,other,another): return self.page+other.page+another.page #b1.page+b2.page b1=Book(200) b2=Book(400) b3=Book(100) print(b1+b2+b3)''' #//Error #Note: Inside Magic Method we can not have more than 2 parameter #****************************************************************** #type-5 '''class Book: def __init__(self,page): self.page=page def __add__(self,other): return (self.page+other.page) def __str__(self): #return "I will get called when print is encountered" return str(self.page) b1=Book(200) b2=Book(400) print(b1) print(b2) print(b1+b2)''' #******************************************************************** #type-6 '''class Book: def __init__(self,page): self.page=page def __add__(self,other): return Book(self.page+other.page) def __str__(self): return str(self.page) b1=Book(200) b2=Book(400) b3=Book(120) print(b1+b2+b3)'''
false
ced43f858acb12ba007d9585fe5e47a8b3432115
ShikhaShrivastava/Python-core
/List/Accessing Index & Value.py
405
4.28125
4
'''Accessing Index and Value of element from list''' print("I-Accessing Index & Value of element from list") print(" ") print("1.Enumerate") lst = [1, 2, 3, 4, 5, 6, 7] print(lst) for i, j in enumerate(lst): print("Index is:", i, "& Value is:", j) print(" ") print("2.Range Function") lst = [1, 2, 3, 4, 5, 6, 7] print(lst) for i in range(len(lst)): print("Index is:", i, "& Value is:", lst[i])
false
608058dd4948f105e45a5e1243090aadc4d99909
sreekanth-s/python
/vamsy/divisible_by_5.py
264
4.15625
4
## Iterate the given list of numbers and print only those numbers which are divisible by 5 input_list=[1,2,3,4,5,10,12,15.5,20.0,100] def divisible_by_5(input_list): for i in input_list: if i % 5 == 0: print(i) divisible_by_5(input_list)
true
4167630d5010c99a8545ba6e0d1b64ea478ac033
sreekanth-s/python
/old_files/temp.py
863
4.125
4
def sum_of_numbers_in_alphanumeric_string(string=""): """count the sum of inidividual charecters that are numbers in a given string""" total = 0 for val in string: if val.isnumeric(): total=total+int(val) return total #x=sum_of_numbers_in_alphanumeric_string("34g3v6456b456456b56b4n 64n7b46b6546.6") #print(x) def encoding_and_decoding(coded_str=""): """ """ new_str = "" for i in range(len(coded_str)): tmp=1 print(new_str) print(coded_str) print(i) new_str=new_str+coded_str[i] while coded_str[i] == coded_str[i+1] : tmp = tmp+1 i = i + 1 # print(i) coded_str=coded_str[i:] # print(coded_str) new_str=new_str+str(tmp) return new_str y=encoding_and_decoding("sssaaaaaii") print(y)
false