blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2bf12cc265f899db13119297227544c252fbe25e
lperri/CTCI-Practice-Problems
/ch1_arrays_strings/interview_questions/iq_4.py
941
4.34375
4
# palindrome permutation: write a function to check if a string is a permutation of a palindrome # the defining property of a palindrome that I will check is that it must have no more than 1 char # that appears an odd number of times -- all other chars must appear an even number of times # def is_permutation_palindrome(string: str) -> bool: char_dict = {} # populate char_dict for char in string: if char in char_dict: char_dict[char] += 1 else: char_dict[char] = 1 # count number of chars that appear odd number of times num_odd = 0 for char in char_dict: if num_odd > 1: return False if char_dict[char] % 2 != 0: num_odd += 1 return True if __name__ == "__main__": pal_string = "arceacr" non_pal_string ="dooolll" print(is_permutation_palindrome(pal_string)) print(is_permutation_palindrome(non_pal_string))
true
0d942835131e7e0c5c9a6a42a3e62c74719874b8
lperri/CTCI-Practice-Problems
/ch2_linkedlists/interview_questions/implementation.py
2,186
4.375
4
class Node: def __init__(self, val=None): ''' constructor containing the data in a given node and a pointer to the next node (if a next node exists) ''' self.val = val self.next = None class LinkedList: ''' wraps Node class; useful because if head node changes for one obj, other objs can continue to reference their head node ''' def __init__(self): ''' constructor containing only a head node -- head node contains no data (in this implementation)''' self.head = Node() def prepend(self, val) -> None: ''' prepend a node to the start of the linked list ''' current_first = self.head.next new_node = Node(val) self.head.next = new_node new_node.next = current_first def append(self, val) -> None: ''' append a node to the end of the linked list ''' # start at head node current_node = self.head while current_node.next != None: current_node = current_node.next # now at the end of the linked list new_node = Node(val) current_node.next = new_node def remove(self, target_val) -> None: ''' removes node if exists with value=target_val ''' prev_node, current_node = self.head, self.head.next while current_node.next != None: if current_node.val == target_val: prev_node.next = current_node.next prev_node, current_node = current_node, current_node.next def get_length(self, count_head=True) -> int: ''' obtain length of linked list by traversing elements and counting them ''' # set counter at 1 to account for head node current_node = self.head counter = 1 if count_head else 0 while current_node.next != None: counter += 1 current_node = current_node.next return counter def display_as_list(self) -> None: ''' prints node values in list format ''' elements = [] current_node = self.head while current_node != None: elements.append(current_node.val) current_node = current_node.next print(elements)
true
c1af1aaaa7c3e2af6251f334d13d26cfcd75509a
lperri/CTCI-Practice-Problems
/ch2_linkedlists/interview_questions/iq_3.py
1,324
4.125
4
# delete a node in the middle (any node other than first and last) given ONLY access to THAT node from implementation import * def delete_a_middle_node(node: Node) -> None: ''' strategy: shift the rest of the linked list (using values) back by one, thus deleting this node ''' rest_of_list_values = [] node_to_delete = node # collect values we want to keep curr_node = node_to_delete.next while curr_node != None: rest_of_list_values.append(curr_node.val) curr_node = curr_node.next # now push values left # and remove the last node (we have one less node now; last node has dup value to the one before) curr_node = node_to_delete prev_node = curr_node i = 0 while curr_node.next != None: curr_node.val = rest_of_list_values[i] i += 1 prev_node, curr_node = curr_node, curr_node.next # now prev_node is the node before last, so link it to None => removing the last node prev_node.next = None # time O(n) space O(1) if __name__ == "__main__": my_list = LinkedList() my_list.append(5) my_list.append(4) my_list.append(3) my_list.append(2) my_list.append(1) node_to_delete = my_list.head.next.next my_list.display_as_list() delete_a_middle_node(node_to_delete) my_list.display_as_list()
true
ad93e097e9040e6a3265ba54db03520a737294e8
sgoldenlab/simba
/simba/roi_tools/ROI_size_calculations.py
2,313
4.28125
4
import math import numpy as np def rectangle_size_calc(rectangle_dict: dict, px_mm: float) -> dict: """ Compute metric height, width and area of rectangle. :param dict rectangle_dict: The rectangle width and height in pixels. :param float px_mm: Pixels per millimeter in the video. :example: >>> rectangle_size_calc(rectangle_dict={'height': 500, 'width': 500}, px_mm=10) >>> {'height': 500, 'width': 500, 'height_cm': 5.0, 'width_cm': 5.0, 'area_cm': 25.0} """ rectangle_dict["height_cm"] = round((rectangle_dict["height"] / px_mm) / 10, 2) rectangle_dict["width_cm"] = round((rectangle_dict["width"] / px_mm) / 10, 2) rectangle_dict["area_cm"] = round( rectangle_dict["width_cm"] * rectangle_dict["height_cm"], 2 ) return rectangle_dict def circle_size_calc(circle_dict, px_mm) -> dict: """ Compute metric radius and area of circle. :param dict circle_dict: The circle radius in pixels :param float px_mm: Pixels per millimeter in the video. :example: >>> circle_size_calc(circle_dict={'radius': 100}, px_mm=5) >>> {'radius': 100, 'radius_cm': 2.0, 'area_cm': 12.57} """ radius_cm = round((circle_dict["radius"] / px_mm) / 10, 2) circle_dict["radius_cm"] = radius_cm circle_dict["area_cm"] = round(math.pi * (radius_cm**2), 2) return circle_dict def polygon_size_calc(polygon_dict, px_mm) -> dict: """ Compute metric area of polygon. :param dict polygon_dict: The polygon vertices as np.ndarray :param float px_mm: Pixels per millimeter in the video. :example: >>> polygon_size_calc(polygon_dict={'vertices': np.array([[0, 2], [200, 98], [100, 876], [10, 702]])}, px_mm=5) >>> {'vertices': [[ 0, 2], [200, 98], [100, 876], [ 10, 702]], 'area_cm': 45.29} """ y_vals = polygon_dict["vertices"][:, 0] x_vals = polygon_dict["vertices"][:, 1] poly_area_px = 0.5 * np.abs( np.dot(x_vals, np.roll(y_vals, 1)) - np.dot(y_vals, np.roll(x_vals, 1)) ) polygon_dict["area_cm"] = round((poly_area_px / px_mm) / 500, 2) return polygon_dict polygon_size_calc( polygon_dict={"vertices": np.array([[0, 2], [200, 98], [100, 876], [10, 702]])}, px_mm=5, )
true
e847db09fd18d1d7b4dd1e357a06c9be33547fb5
Gajendra28121996/PythonGarden
/Python_If_Statement.py
609
4.4375
4
is_male=True is_tall=False if is_male: print("You are Male !!") else: print("You are Probably Good !") ##When one or both of value is true use OR if is_male or is_tall: print("You are Male && Tall!!") else: print("You are Probably Good Nor Tall!") ##Mandatory to both to be true print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") if is_male and is_tall: print("You are Male and Tall !") elif is_male and not(is_tall): print("You are Male Not Tall!") elif not(is_male) and is_tall: print("you are Not Male and but Tall") elif not(is_male) and not(is_tall): print("You are Not male and Nor Tall")
false
0ccca243f2e0c95ec7b519ef346be233efe95b6a
Gajendra28121996/PythonGarden
/Python_List_Function.py
1,165
4.25
4
## List of number list_Of_Number=[3,4,6,9,11,13] friends=["Gajendra","Stan Lee","Repeating","Enstine","Iron Man","Skarlett Jhonson","Repeating","Repeating"] print(friends) print(list_Of_Number) ## append() >>> Allows me to append another item to the list friends.append("Creed") print(friends) ##Print the Index of List Element print(friends.index("Creed")) ## inser(index_num, value_to_be_Inserted) >>> Allows me to inset an item at specified index. ## Function will insert an elemnet in the pecified index and all list element will be adjusted with respect to the insertion friends.insert(2,"Stephen Hawkings") print(friends) ## remove( element to be removed ) friends.remove("Enstine") print(friends) ## pop removes the last elemnt from the list friends.pop() print(friends) ##Count How many timmes the word occur in the list print(friends.count("Repeating")) ## Sort() >>> sort in alphabetical order friends.sort() print(friends) ##Reverse the List friends.reverse() print(friends) ## hold the Copy of the list in another variable strange_friend=friends.copy() print(strange_friend) ## clear() >>> Reset the list or cleas all element from the list friends.clear() print(friends)
true
5b35d79e61d1f13c982f86418330e8fbf0fd35b3
slushhub/mining-mondays
/how-to-read-code/1.py
1,527
4.375
4
""" Variables Variables are just names for values. Names help in reading. Imagine asd vs my_telephone_number, which is more informative? """ # my name is Tero my_name = 'Tero' # my age is 24 my_age = 24 # teemus age is two times my age teemus_age = 2 * my_age """ Conditionals The point of conditionals is to check for a value and act based on it. Note the indented things are run only if the condition is truthy! """ # my name is Tero my_name = 'Tero' # if my name is Tero if my_name == 'Tero': # then print Buenos Aires! print('Buenos Aires!') """ Functions Functions can take variables as input values. They all output a value. The point of a function is to make implementation details hidden behind a name. Imagine a post office is a function. You input them a package. They do all the complex stuff to deliver it. """ # define a function called calculate circle area with radius # it takes radius as an input def calculate_circle_area_with_radius(radius): # calculated area is pi times radius to the power of 2 calculated_area = math.pi * radius**2 # return calculated area return calculated_area # area1 is the calculated circle area with radius of 5 area1 = calculate_circle_area_with_radius(5) # 78,5... # area2 is the calculated circle area with radius of 20 area2 = calculate_circle_area_with_radius(20) # 1256... # area3 is the calculated circle area with radius of 412 area3 = calculate_circle_area_with_radius(412) # 532996,16...
true
93fd684abc67c7d66f4dbbe95807eee290f32970
Ankan002/Python-College-Practical-Code-and-Info
/Practical 11/code.py
207
4.34375
4
string = str(input("Enter the string for which you want to find the ASCII value: ")) new_ascii = "" for c in string: new_ascii = new_ascii + str(ord(c)) print("ASCII value of", string, "is:", new_ascii)
true
80ae29f7a2c28667febd972edff724c5159df732
samkit-jpss/DSA
/Queue/queue.py
943
4.15625
4
class Queue: def __init__(self): self.items=[] #Insertion of Element def Enqueue(self,data): self.items.insert(0,data) #Pop the element at the last or first inserted element def Dequeue(self): return self.items.pop() #Returns the size of the list def qsize(self): return "Length of items: {}".format(len(self.items)) #Function that returns boolean if the list is empy or not def isEmpty(self): return self.items == [] weekdays=Queue() weekdays.Enqueue("Monday") #inserting element "Monday" weekdays.Enqueue("Tuesday") #inserting element "Tuesday" weekdays.Enqueue("Wednesday") #inserting element "Wednesday" print(weekdays.Dequeue()) #Removes "Monday" print(weekdays.Dequeue()) #Removes "Tuesday" print(weekdays.__dict__) #Output what remains in the items list print(weekdays.qsize()) print(weekdays.isEmpty())
true
14a4148c8197eaec9bd2449d7a619dfce139f8f6
Pavche/python_scripts
/dictionary2.py
728
4.1875
4
#!/usr/bin/python3 # This script demonstrates dictionary which is a part of Python programming language. birthdays = {'Маргарита':'28 март 1960','Румяна':'23 май 1961', 'Красимир':'27 декември' ,'Младен':'25 април 1976','Павлин':'30 юни 1979','Галя':'2 септември 1981', 'Драган':'17 юни 1985','Катерина':'28 октомври 2009','Константин':'29 ноември 2012'} print('Разпечатва имена') for i in birthdays.keys(): print(i) print('\n') print('Разпечатва дати') for j in birthdays.values(): print(j) print('\nСмесено отпечатване') for k in birthdays.items(): print(k)
false
cafe7dbe26a417237e56b62d26dee6f5a6a37adf
BobIT37/Python3Programming
/venv/07-Built-in Functions/01-Map.py
645
4.4375
4
# map() takes in two or more arguments # a function and one or more iterables # syntax # map(function, iterable...) # map returns iterator my_pets = ["alfred", "tabitha", "william", "arla"] uppered_pets = [] ''' for pet in my_pets: pet_ = pet.upper() uppered_pets.append(pet_) print(uppered_pets) ''' uppered_pets = list(map(str.upper, my_pets)) print(uppered_pets) def fahrenheit(celsius): return (9/5)*celsius + 32 temps = [0, 22.5, 40, 100] F_temps = map(fahrenheit, temps) print(list(F_temps)) # map() with multiple iterables a = [1,2,3,4] b = [5,6,7,8] c = [9,10,11,12] print(list(map(lambda x,y,z:x+y+z,a,b,c)))
true
a1c3cb52cd539c3d1b27e8d49c0f150cd3f7ed6b
akinahmet/python
/smallest_number.py
297
4.21875
4
number1=int(input("number1: ")) number2=int(input("number2: ")) number3=int(input("number3: ")) if number1<number2 and number1<number3: print("number 1 is the smallest") elif number2<number1 and number2<number3: print("number 2 is the smallest") else: print("number 3 is the smallest")
false
f58692c3858f078b4aacddaf8a01549d1658c32c
jsjimenez51/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
958
4.125
4
#!/usr/bin/python3 """ finds a peak in a list of unsorted integers """ def find_peak(list_of_integers): """ finds peak using a binary search """ if list_of_integers: start = 0 end = len(list_of_integers) - 1 if start == end: return list_of_integers[start] # checks if the start or end of the list are peaks if list_of_integers[start] > list_of_integers[1]: return list_of_integers[start] if list_of_integers[end] > list_of_integers[end - 1]: return list_of_integers[end] # finds the mid point of the list to begin binary search mid = (end - start) // 2 if list_of_integers[mid] < list_of_integers[mid - 1]: return find_peak(list_of_integers[:mid]) if list_of_integers[mid] < list_of_integers[mid + 1]: return find_peak(list_of_integers[mid + 1:]) return list_of_integers[mid] return None
true
88f8501b1125a38941f880cf381bf1e5e142c14b
jpicasso/LessonSummary3
/4Python/5HomeWork/9hw.py
647
4.65625
5
# Exercise 9. # A string is a palindrome if it is identical forward and backward. For example “anna”, “civic”, “level” and “hannah” are all examples of palindromic words. Write a program that reads a string from the user and uses a loop to determines whether or not it is a palindrome. Display the result, including a meaningful output message. input_9 = input('Enter a word: ') reverse_9 = input_9[-1:-len(input_9)-1:-1] if input_9 == reverse_9: print('{} equals {}. This is a palindromic word.' .format(input_9, reverse_9)) else: print('{} does not equal {}. This is not a palindromic word.' .format(input_9, reverse_9))
true
696c6e6c8c0f663ff5e929881f5c6ea315947053
IacovColisnicenco/100-Days-Of-Code
/DAYS_001-010/Day - 003/Exercises/day-3-2-exercise.py
601
4.34375
4
height = float(input("Enter your height in Metres (m): ")) weight = float(input("Enter your weight in Kilograms (kg): ")) bmi = weight / height ** 2 bmi_result = round(bmi, 2) if bmi_result < 18.5: print(f"Your BMI is -> {bmi_result}, You are Underweight") elif bmi_result < 25: print(f"Your BMI is -> {bmi_result}, You have a Normal weight") elif bmi_result <30: print(f"Your BMI is -> {bmi_result}, You are slightly Overweight") elif bmi_result < 35: print(f"Your BMI is -> {bmi_result}, You are Obese") else: print(f"Your BMI is -> {bmi_result}, You are Clinically Obese")
false
e6936a156c850aaed279bb7cad50e41f91b65a8e
IacovColisnicenco/100-Days-Of-Code
/DAYS_011-020/Day - 19 - Exercise/turtle_race.py
1,430
4.3125
4
from turtle import Turtle, Screen import random my_screen = Screen() my_screen.setup(width=800, height=600) user_bet = my_screen.textinput(title="Make Your Bet", prompt="Which turtle will win the race? Enter a color: ").lower() colors = ["red", "orange", "yellow", "green", "DarkBlue", "purple", "SpringGreen", "DarkTurquoise"] all_turtles = [] is_race_on = False y_axis = -220 for turtle_index in range(0, 8): new_turtle = Turtle(shape="turtle") # The default size of a Turtle object is 20 pixels. # Sets the turtle's width to 40px and height to 40px and width of the Turtle's outline to 1 new_turtle.shapesize(2, 2, 1) new_turtle.color(colors[turtle_index]) new_turtle.penup() new_turtle.goto(x=-380, y=y_axis) y_axis += 65 all_turtles.append(new_turtle) if user_bet: is_race_on = True while is_race_on: for turtle in all_turtles: # 360 is 400 - half the width of the turtle. if turtle.xcor() > 360: is_race_on = False winning_color = turtle.pencolor() if winning_color == user_bet: print(f" You've won! The {winning_color} turtle is the winner! ") else: print(f" You've lost! The {winning_color} turtle is the winner! ") # Make each turtle move a random amount. rand_distance = random.randint(0, 10) turtle.forward(rand_distance) my_screen.exitonclick()
true
15628f246ef699d41ba11f8c27162193a5c0129f
YashaswiniPython/pythoncodepractice
/7_Dictionary.py
1,413
4.25
4
# Python file Created By Bibhuti d={"a":"d",2:"Python"}; print(d); # print(type(d)); # print(d.get('a')); # print(d.get(2)); # print(d.get("b")); # if key is not available it will return None # print(d.keys()); # it will provide all the keys set # print(d.values()); # it will provide all the values # print(d.items()); # it will show all the key value pair # print(d.__len__()); # print(d.keys().__len__()); # d.__delitem__(2); # delete key value pair based on user key input # print(d); # if key is not available it will show you error # print(d.__getitem__(2)); # use to get the value of perticulat key # if element is not available it will show error # print(d[2]); # print(d[1]); # d[3]="new"; # print(d); # d[2]="NewValueOf2"; # print(d); # d.pop(2); # print(d); # d.pop(1); # if element not available it will show error # print(d); # d.__setitem__("c","setitem"); # print(d); # d.setdefault(1); # if value is not their it will add the given key and its value is None # print(d); # d.setdefault(True); # if value is present it will not affect the existing # print(d); # d.update({"c":123,"d":"bhvhjg"}); # it is use to add key,value pair into dictionary,multiple key value pair also we can add # print(d); # d.update() # empty parameter it will not show error rather than dictionary unchange # print() # d.popitem(); # print(d);
true
84462e5404558af15885e666e0783c27a3b05ce9
Martiboy/Spotlight
/Machiel/word adventure.py
2,318
4.15625
4
def menu(lists, question): for entry in lists: print (1 + lists.index(entry)) print (" ) " + entry) return int(input(question)) - 1 items = ["pot plant","painting","vase","lampshade","shoe","door"] keylocation = 2 keyfound = 0 loop = 1 print ("Last night you went to sleep in the comfort of your own home.") print ("Now, you find yourself locked in a room. You don't know how") print ("you got there, or what time it is. In the room you can see") print (len(items), 'things:') for x in items: print (x) print ("") print ("The door is locked. Could there be a key somewhere?") while loop == 1: choice = menu(items,"What do you want to inspect? ") if choice == 0: if choice == keylocation: print ("You found a small key in the pot plant.") print ("") keyfound = 1 else: print ("You found nothing in the pot plant.") print ("") elif choice == 1: if choice == keylocation: print ("You found a small key behind the painting.") print ("") keyfound = 1 else: print ("You found nothing behind the painting.") print ("") elif choice == 2: if choice == keylocation: print ("You found a small key in the vase.") print ("") keyfound = 1 else: print ("You found nothing in the vase.") print ("") elif choice == 3: if choice == keylocation: print ("You found a small key in the lampshade.") print ("") keyfound = 1 else: print ("You found nothing in the lampshade.") print ("") elif choice == 4: if choice == keylocation: print ("You found a small key in the shoe.") print ("") keyfound = 1 else: print ("You found nothing in the shoe.") print ("") elif choice == 5: if keyfound == 1: loop = 0 print ("You put in the key, turn it, and hear a click") print ("") else: print ("The door is locked, you need to find a key.") print ("") print ("Light floods into the room as \ you open the door to your freedom.")
true
c89bf29734f53ac1f3304173ad99b60544f404b6
Amy7/Python-task
/guessinggame.py
721
4.25
4
import random number = random.randint(1,10) #print(number) n = 3 while(n): try: guess = int(input(("please guess the number:"))) while(guess > 10 or guess < 0): guess = int(input(("please input your number from 1 to 10"))) n -= 1 if(guess == number): print("congratulation!") break elif(guess-number==1 or guess-number==-1): print("it's hot") elif(guess-number==2 or guess-number==-2): print("it's warm") else: print("it's cold") except: print("please input your number from 1 to 10") if(n==0 and guess != number): print("The guessing game over!")
true
c4a15cabe8aa9caefbac67b0326ee84d1e85fade
Samuel1P/Prep
/algorithms/binary_search_using_while.py
492
4.1875
4
# this code will search for a integer in a sorted list using while loop arr_ = [1, 1, 2, 3, 3, 3, 4, 5, 6, 7] def binary_search(arr, first, last): while (first <= last): mid = (first + last) // 2 if ele == arr[mid]: return f"Found {ele}" elif ele < arr[mid]: last = mid - 1 elif ele > arr[mid]: first = mid + 1 return "Not Found" ele = 7 # element to be searched print(binary_search(arr_, 0, len(arr_) - 1))
true
7e22593e514c169076f99900424e42fe3f775463
davray/lpthw-exercises
/ex15.py
2,236
4.40625
4
# import the function argv from module sys from sys import argv # give argv variables to unpack script, filename = argv # assign var txt to open var filename txt = open(filename) # print string with raw format char with var filename print "\nHere's your file %r:" % filename # print var txt contents open(file.read) print txt.read() txt.close() # print string print "Type the filename again:" # get user input, assign user input to var file_again file_again = raw_input("> ") # open var filename, assign content to var txt_again txt_again = open(filename) # print txt_again contents using open(file.read) print "\n" + txt_again.read() txt_again.close() # Study Drill # 1. Above each line, write out in English what that line does. # - Code commented. # 2. If you are not sure, ask someone for help or search online. Many # times searching for "python THING" will find answers for what that # THING does in Python, Try searching for "python open." # 3. I used the name "commands" here, but they are also called # "functions" and "methods." Search around online to see what other # people do to define these. Do not worry if they confuse you. It's # normal for programmers to confuse you with vast extensive knowledge. # 4. Get rid of the part from lines 10-15 where you use raw_input and # try the script then. # - File: ex15_sd4.py # 5. Use only raw_input and try the script that way. Think of why one way # of getting the filename would be better than another. # - Depends on how interactive you want your script to be. You also # need to be careful with how raw_input assigns its value to a var # as a string. # 6. Run pydoc file and scroll down until you see the read() command # (method/function). See all the other ones you can use? Skip the # ones that have __ (two underscores) in front because those are # junk. Try some of the other commands. # - File: ex15_sd6.py # 7. Start python again and use open from the prompt. Notice how you can # open files and run read on them right there? # 8. Have your script also do a close() on the txt and txt_again # variables. It's important to close files when you are done with them # = Added close() to Line 11 and Line 20 closing out files.
true
cf68d0df2b2cc12f6ca2b3605628e18e79623d81
rravitanneru/python
/identical operators.py
408
4.21875
4
# there are two identical operators # is, is not # is by default evalutes to true if vars on both sides of operator pointing to same memory location, object,value # is not by default evalutes to true if vars on both sides of operator pointing to same memory location, object,value a = 10 b = 10 if(a is b): print('a is present in b') p = 12 q = 11 if(p is not q): print('a is not in b')
true
9850628b90b5acf55b731ffeebe01edc6b43b1a4
developbiao/pythonbasics
/2023/guess_high_low.py
339
4.1875
4
#!/usr/bin/env python3 #! -*- coding:utf-8 -*- number = 18 guess = -1 print("Guess number game!") while guess != number: guess = int(input("Please Input guess number:")) if guess == number: print("Yes Correct!") elif guess < number: print("To low...") elif guess > number: print("To hight...") print("Hello Guess number")
false
acab9b007c20b3a87d3bacb197ed031e4d173832
developbiao/pythonbasics
/2023/oop/people.py
898
4.125
4
#!/usr/bin/env python3 #-*- coding:utf-8 -*- class people: # Public property name = '' age = 0 # Prive property __weight = 0 # Construct def __init__(self, name, age, weight): self.name = name self.age = age self.__weight = weight # Sepak def speak(self): print("Hello My name is %s, Im %d years old." % (self.name, self.age)) # inherit class student(people): grade = '' def __init__(self, name, age, weight, grade=''): # call parent construct people.__init__(self, name, age, weight) self.grade = grade def speak(self): print("Hello My name is %s, Im %d years old, Im a student my grade %s" % (self.name, self.age, self.grade)) # New Instance xiaoming = people('xiaoming', 27, 70) xiaoming.speak() # New student xiaohua = student('xiaohua', 17, 90, 'Level 3') xiaohua.speak()
false
b5f0f634f1327d084dfc75a15fdc651eabc8aab1
developbiao/pythonbasics
/2023/intervidew-questions/bubble-sort.py
280
4.25
4
#!/usr/bin/env python3 def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n - i -1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] arr = [32, 64, 71, 89] bubble_sort(arr) print("Sorted a array:", arr)
false
2bd89f67c58952885d2c88787af5692d86cff020
kyuugi/saitan-python
/やってみよう_必修編/chapter06/6_7_people.py
746
4.125
4
# 空のリストを作成する people = [] # 人の辞書を作成してリストに追加する person = { 'first_name': 'たかのり', 'last_name': '鈴木', 'age': 49, 'city': '東京', } people.append(person) person = { 'first_name': 'せぶん', 'last_name': '鈴木', 'age': 2, 'city': '東京', } people.append(person) person = { 'first_name': 'にあ', 'last_name': '鈴木', 'age': 4, 'city': '東京', } people.append(person) # 辞書の全情報を出力する for person in people: name = f"{person['last_name']}{person['first_name']}" age = person['age'] city = person['city'].title() print(f"{name}は{city}に住んでおり、{age}才です。")
false
9942ee03ecf8a05d7e9f4f21c22ec38c6e2035f5
RasselJohn/AlgorithmExercises
/src/03.py
859
4.28125
4
# Check number on primary. import math def is_prime(number): """ If number is prime - return True :param number: int :return: boolean >>> is_prime(25) False >>> is_prime(12) False >>> is_prime(11) True >>> is_prime(1) Traceback (most recent call last): ... ValueError: Number must be more than 2! >>> is_prime(-12) Traceback (most recent call last): ... ValueError: Number must be more than 2! """ if number < 2: raise ValueError("Number must be more than 2!") if number // 2 == 0: return False curr = 3 square_root = math.floor(number ** 0.5) while (curr <= square_root) and (number % curr != 0): curr += 2 return curr > square_root if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
true
fdd0b1dd24d97cc57ec3ea18ae5bf2bb61838274
RasselJohn/AlgorithmExercises
/src/05.py
288
4.125
4
# Change 2 variables without third. # one way a = 3 b = 2 print("a = {0}, b = {1}".format(a, b)) a, b = b, a print("a = {0}, b = {1}".format(a, b)) # second way a = 3 b = 2 print("a = {0}, b = {1}".format(a, b)) a = a + b b = a - b a = a - b print("a = {0}, b = {1}".format(a, b))
false
8aa28961dcbc8655bbfa0df490b841496cbdef91
haochen208/Python
/pyyyy/23 阶段综合练习三/01.py
240
4.1875
4
# 请将列表中所有的字符串变为小写 L = ["Hello", "World", "Apple", "Banana"] L1 = [] for i in L: L1.append(i.lower()) print(L1) # 列表推导式:[表达式 for 变量 in 序列] print([i.lower() for i in L])
false
15903f72755a22a5ec6d9a95c83d3b2df08bf887
haochen208/Python
/pyyyy/01 输入、输出、变量/02变量.py
575
4.28125
4
# a = 2 # b = a # print(b) # num1 = 1 # num2 = 2 # num3 = 3 # num1, num2, num3 = 1, 2, 3 # num1 = num2 = num3 = 4 # print(num1,num2,num3) # a = 10 # b = a # a = 20 # print(a,b) # 变量名命名规则: # (1)数字、字母、下划线,其中数字不能开头 # (2)不能与python关键字重名 # (3)见名知意 # 下划线_:shift + - # _123 # nu23_? # 1info # student school # hello_ABC_123 # a = 1 # print(a) # name = "吕昊宸" # 练习: # 交换两个变量的值: a = 1 b = 2 a,b = b,a print(a,b)
false
8d1a4bdcdc2561106225df1eab8dd8998b2bd062
BrantLauro/python-course
/module01/classes/class09a.py
2,657
4.375
4
from style import blue, red, purple, none a = 'Hello World!' print(f'The string {blue}is{none} {purple}{a} {none}\n' f'The {blue}index 2nd{none} is {purple}{a[2]} {none}\n' f'The string {blue}until the 3rd index{none} is {purple}{a[:3]} {none}\n' f'The string {blue}starting in the 3rd index{none} is {purple}{a[3:]} {none}\n' f'The string {blue}counted every 2{none} is {purple}{a[::2]} {none}\n' f'The string has {blue}{len(a)}{none} characters \n' f'The string has {blue}{a.count("o")}{none} letters "o" \n' f'The string has {blue}{a.count("O", 0, 3)}{none} letters "O" starting on 0 index until the 3rd index\n' f'The string has a the word {blue}"World" starting in the index{none}: {purple}{a.find("World")} {none}\n' f'The string has the word {blue}"Python"{none}? {purple}{"Python" in a} {none}\n' f'If it substitutes {blue}"World"{none} to {blue}"Python"{none} would be: {purple}{a.replace("World", "Python")} {none}\n') b = input('Type something: ') print(f'{b} in {blue}uppers{none} stay: {purple}{b.upper()} {none}\n' f'{b} in {blue}lowers{none} stay: {purple}{b.lower()} {none}\n' f'{b} {blue}capitalized{none} stay: {purple}{b.capitalize()} {none}\n' f'{b} was a {blue}title{none} stay: {purple}{b.title()} {none}\n' f'{b} {blue}with no spaces in the right{none} stay: {purple}{b.rstrip()} {none}\n' f'{b} {blue}with no spaces in the left{none} stay: {purple}{b.lstrip()} {none}\n' f'{b} {blue}with no spaces in the right and left{none} stay: {purple}{b.strip()} {none}\n' f'{b} {blue}capitalized after taken away the spaces{none} stay: {purple}{b.strip().capitalize()} {none}\n' f'{blue}Splitting off all words in {b}{none} would be: {purple}{b.split()} {none}\n') print('''The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!''')
false
e896dd1641e9cd3b823e9cd29c74c05e1c2678cb
BrantLauro/python-course
/module03/ex/ex082.py
548
4.125
4
numbers = [] pair = [] odd = [] choice = ' ' while True: while choice not in 'NY': choice = input('Do you want to add a number on the list? [Y/N] ').upper().strip()[0] if choice == 'N': break if choice == 'Y': number = int(input('Type a number: ')) numbers.append(number) if number % 2 == 0: pair.append(number) else: odd.append(number) choice = ' ' print(f'The list is {numbers}') print(f'The pair numbers are {pair}') print(f'The odd numbers are {odd}')
true
b5ce81277156b93bd26483fd54ccfdd67c18e368
BrantLauro/python-course
/module01/ex/ex017.py
312
4.15625
4
from math import hypot oside = float(input('What is the length of the opposite side? ')) aside = float(input('What is the length of the adjacent side? ')) h = hypot(oside, aside) print(f'The hypotenuse of the triangle whose opposite side and adjacent side measure respectively {oside} and {aside} is {h:.2f}')
false
ddd4b58144fcf47fa58039da5129f097d6f38619
royaldream/Python
/OOPS/Practice/Monk and circular distance.py
2,083
4.28125
4
"""Its time for yet another challenge, and this time it has been prepared by none other than Monk himself for Super-Hardworking Programmers like you. So, this is how it goes: Given N points located on the co-ordinate plane, where the point is located at co-ordinate , , you need to answer q queries. In the query, you shall be given an integer , and considering you draw a circle centered at the origin with radius , you need to report the number of points lying inside or on the circumference of this circle. For each query, you need to print the answer on a new line. Input Format : The first line contains a single integer N denoting the number of points lying on the co-ordinate plane. Each of the next N lines contains 2 space separated integers and , denoting the x and y co-ordintaes of the point. The next line contains a single integer q, denoting the number of queries. Each of the next q lines contains a single integer, where the integer on the line denotes the parameters of the query . Output Format : For each query, print the answer on a new line. Constraints : SAMPLE INPUT 5 1 1 2 2 3 3 -1 -1 4 4 2 3 32 SAMPLE OUTPUT 3 5 Explanation For the query in the sample, the circle with radius equal to 3 looks like this on the co-ordinate plane enter image description here The points : , and lie inside or on the circumference of the circle.""" import math def countPoints(data, r,i): """ :type data: object """ area = math.pi * r * r; count = 0 for x in data: r1 = math.sqrt(math.pow(int(x[0]), 2) + math.pow(int(x[1]), 2)) a = math.pi * r1 * r1 if area >= a: count += 1 print count if __name__ == '__main__': no = int(raw_input()) data = [] radius = [] for i in range(no): data1 = raw_input() data1 = data1.split(" ") data.append([data1[0], data1[1]]) testCase = input() for i in range(testCase): a = int(raw_input()) radius.append(a) for i in range(testCase): countPoints(data, int(radius[i]),i)
true
8dce269430fdc7db07ddeb21dfe79ae3940dc3e2
sjacksondev/bouncy_ball
/bouncy.py
850
4.21875
4
""" PROGRAM: bouncy.py NAME: Sabrina DATE: 9/5/19 Program calculate the total difference travelled by a bouncing ball. User will input: The starting height of the ball How bouncy the ball is How many bounces the ball will make Output will be the total distance the ball travels """ # Request the inputs height = float(input("Enter the starting height of the ball: >>> ")) index = float(input("Enter the bounciness index of the ball: >>> ")) bounces = int(input("How many bounces do you want to observe? >>> ")) # Accumulator for total distane totalDistance = 0 # For loop to determine total distance travelled for count in range(bounces): totalDistance += height height += index totalDistance += height # Output of total distance print() print("The totakl distance travelled by the ball is", totalDistance)
true
eaa387f7a1ae2943c95610ef6220e15a1eec2328
martinthk/python-exercises
/code/Ex13_Heron'sConvergence.py
569
4.125
4
# Ex13: Heron’s method of convergence # compute √𝑎 using Heron's method of Convergence # Take as input a number (a), and an initial guess for the value of √𝑎 # and repeatedly apply equation 1 until the approximate solution converges to close to the true solution. import math a = int(input('Enter the value for a: ')) guess = int(input('Enter your initial guess for x: ')) xOld = guess xNew = 1/2*(xOld+(a/xOld)) while abs(xOld-xNew) > 0.001: xOld = xNew xNew = (1/2)*(xOld + a/xOld) print(xNew) print('The square root of', a, 'is', xNew)
true
5e13c84ade3c1b2275afe75f006fd03e3409283a
samjabrahams/anchorhub
/anchorhub/util/hasattrs.py
736
4.4375
4
""" hasattrs() checks a list of string arguments and sees whether the provided object has all of them. It uses the built-in hasattr() method with each attribute name """ def hasattrs(object, *names): """ Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param names: a variable amount of attribute names to check for :return: True if the object contains each named attribute, false otherwise """ for name in names: if not hasattr(object, name): return False return True
true
5927eacb5f5e6e10ef6874975eb47ffefad6947d
samjabrahams/anchorhub
/anchorhub/util/addsuffix.py
544
4.65625
5
""" File for helper function add_suffix() """ def add_suffix(string, suffix): """ Adds a suffix to a string, if the string does not already have that suffix. :param string: the string that should have a suffix added to it :param suffix: the suffix to be added to the string :return: the string with the suffix added, if it does not already end in the suffix. Otherwise, it returns the original string. """ if string[-len(suffix):] != suffix: return string + suffix else: return string
true
3263741eeae211b01761513ce52b0f8c88a20632
pjgb/dailyprogrammer
/ch287e.py
2,897
4.1875
4
#!/usr/bin/env python3 # Write a function that, given a 4-digit number, returns the largest digit # in that number. Numbers between 0 and 999 are counted as 4-digit numbers # with leading 0's. # # largest_digit(1234) -> 4 # largest_digit(3253) -> 5 # largest_digit(9800) -> 9 # largest_digit(3333) -> 3 # largest_digit(120) -> 2 # # In the last example, given an input of 120, we treat it as the 4-digit # number 0120. # # Bonus 1 # Write a function that, given a 4-digit number, performs the "descending # digits" operation. This operation returns a number with the same 4 digits # sorted in descending order. # # desc_digits(1234) -> 4321 # desc_digits(3253) -> 5332 # desc_digits(9800) -> 9800 # desc_digits(3333) -> 3333 # desc_digits(120) -> 2100 # # Bonus 2 # Write a function that counts the number of iterations in Kaprekar's Routine, # which is as follows. # Given a 4-digit number that has at least two different digits, take that # number's descending digits, and subtract that number's ascending digits. # For example, given 6589, you should take 9865 - 5689, which is 4176. # Repeat this process with 4176 and you'll get 7641 - 1467, which is 6174. # Once you get to 6174 you'll stay there if you repeat the process. # In this case we applied the process 2 times before reaching 6174, # so our output for 6589 is 2. # # kaprekar(6589) -> 2 # kaprekar(5455) -> 5 # kaprekar(6174) -> 0 # # Numbers like 3333 would immediately go to 0 under this routine, but since we # require at least two different digits in the input, all numbers will # eventually reach 6174, which is known as Kaprekar's Constant. def largest_digit(n): digits = [int(d) for d in str(n).zfill(4)] return max(digits) print(largest_digit(1234)) print(largest_digit(3253)) print(largest_digit(9800)) print(largest_digit(3333)) print(largest_digit(120)) # Bonus 1 def desc_digits(n, reverse=False): digits = [int(d) for d in str(n).zfill(4)] sorted_digits = sorted(digits, reverse=(not reverse)) return ''.join([str(i) for i in sorted_digits]) print(desc_digits(1234)) print(desc_digits(3253)) print(desc_digits(9800)) print(desc_digits(3333)) print(desc_digits(120)) # Bonus 2 def kaprekar(n, i=0): digits = [int(d) for d in str(n).zfill(4)] if len(set(digits)) < 2: raise ValueError('number has less than 2 different digits') asc = int(desc_digits(n, reverse=True)) desc = int(desc_digits(n)) current = desc - asc if n == current: return i else: return kaprekar(current, i+1) print(kaprekar(1234)) print(kaprekar(3253)) print(kaprekar(9800)) print(kaprekar(3333)) print(kaprekar(120)) record = 0 for i in range(1,9998): try: current = kaprekar(i) record = (current if record < current else record) except ValueError: continue print(record) # 7
true
7fdfdf1e450cdc5e88cc3db5bf09a3bcabf548fe
pbarton666/learninglab
/begin_advanced/py_class_support.py
1,671
4.28125
4
#py_class_support.py """Demonstrate basic class operations""" #a simple class class Mammal(): pass #a class instance (a specific Mammal) m = Mammal() #...upgraded to initialize with instance attribute class Mammal(): def __init__(self): self.warmblooded=True #a class instance m = Mammal() #single inheritance, executing parent's __init__() method class Dog(Mammal): def __init__(self, name): Mammal.__init__(self) self.name=name def speak(self): print("The dog {} says: WOOF!".format(self.name)) dog = Dog("Fang") dog.speak() print("Warmblooded? {}".format(dog.warmblooded)) #another subclass of Mammal class Cat(Mammal): def __init__(self, name): self.name=name self.breath="bad" Mammal.__init__(self) def speak(self): print("The Cat {} says: Derp.".format(self.name)) cat=Cat("Snarky") cat.speak() print(cat.breath) #multiple inheritance class Dat(Dog, Cat): "Dog/Cat combo - MRO favors left-most argument" def __init__(self): super().__init__("Dat") print("\nDat: MRO is Dog then Cat") self.speak() dat=Dat() class Dat(Cat, Dog): "Cat/Dog combo - MRO favors left-most argument" def __init__(self): super().__init__("Dat") print("\nDat: MRO is Cat then Dog") self.speak() dat=Dat() class Dat(Cat, Dog): "Cat/Dog combo - MRO favors left-most argument" def __init__(self): super().__init__("Dat") print("\nDat: MRO is Cat then Dog \n") self.speak() d=Dat() #method override class Dat(Cat, Dog): "Cat/Dog combo - MRO favors left-most argument" def __init__(self): super().__init__("Dat") self.speak() def speak(self): print("I'm a Dat, and I say 'DAT'!!!") dat=Dat()
true
8c7460b07a9b10da69dc1bff93c7203ddb263699
MediaPreneur/Introduction-to-python
/twinx.py
481
4.1875
4
import matplotlib.pyplot as plt import numpy as np x = np.arange(0., 100, 1); y1 = x**2; # y1 is defined as square of x values y2 = np.sqrt(x); # y2 is defined as square root of x values fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(x, y1, 'bo'); ax1.set_ylabel('$x^{2}$'); ax2 = ax1.twinx() # twinx() function is used to show twinned x axes ax2.plot(x, y2, 'k+'); ax2.set_ylabel('$\sqrt{x}$'); ax2.set_title('Same x axis for both y values'); plt.show()
true
d2447fcd3ecbb9525e41efdcd06c99aee7d2382b
ivddorrka/OP_nutriotionproject
/examples/example_pandas.py
2,342
4.40625
4
''' This module demonstrates how to use some pandas functionality ''' import pandas as pd def series_examples(): ''' This function demonstrates some basic pandas functionality on how to work with Series ''' nums_list = [1, 7, 2] nums_list_serie = pd.Series(nums_list, index=["x", "y", "z"]) print(nums_list_serie, end='\n\n') nums_dict = {"day1": 420, "day2": 380, "day3": 390} nums_dict_serie = pd.Series(nums_dict, index = ["day1", "day3"]) print(nums_dict_serie) def read_and_work_with_csv(path : str = 'example.csv'): ''' This function demonstrates some examples of using pandas to filter data, get entries from top/bottom, sort dataframe, det information about dataframe, etc. ''' df = pd.read_csv(path, sep=';') # print whole DataFrame print(df) # print 1 row from top print(df.head(1)) # print 1 row from bottom print(df.tail(1)) print('Length with duplicates: ', len(df)) df.drop_duplicates(inplace = True) print('Length without duplicates: ', len(df)) # we can also get a lot of useful information about out dataframe and change that values # print DataFrame columns as list print(f'Columns: {list(df.columns)}') print(f'Shape: {df.shape}') print(f'Indices: {list(df.index)}') # filter only those entries with Location value Manchester and not Department == 'Sales' manchester_df = df[(df.Location == 'Manchester') & ~(df.Department == 'Sales')] # since some values have been dropped during filtering, we should reset indices so that indices # go from 0 to number of indices-1 and not their old indices wich may be not consequent manchester_df = manchester_df.reset_index(drop=True) print(manchester_df) # print sum of Identifier column print(manchester_df['Identifier'].sum()) # sort dataframe by Identifier column in ascending order manchester_sorted_df = manchester_df.sort_values(by='Identifier', ascending=True) print(manchester_sorted_df) # drop One-time password and Recovery code columns new_df = manchester_df.drop(['One-time password', 'Recovery code'], axis=1) print(new_df) # write to file without indices column new_df.to_csv('new-1.csv', index=False) if __name__ == '__main__': series_examples() read_and_work_with_csv()
true
9ea487ecec4a6cba47c433571cd4cf2dbf4a15bf
5-digits/interview-techdev-guide
/Data Structures/Stack/Python/Stack.py
1,397
4.1875
4
# Implementation of stack using list in Python # Stack is "LIFO(Last In First Out)" # push method is used to add an item on top of stack # pop method is used to get the topmost item from stack import copy class Stack: """ Just for the sake of teaching, this stack is implemented in such a way that it uses a minimal amount of Python list methods. """ def __init__(self, values: list = None): if values: self.data = copy.deepcopy(values) else: self.data = [] def push(self, value): """ Append method. Add an element to the top of the stack """ self.data.insert(0, value) def pop(self): """ Pop method. Take an element from the top of the stack if it's not empty. Throws an exception for an empty stack. """ if len(self.data) > 0: value = self.data[0] self.data = self.data[1:] return value else: raise Exception("The stack is empty!") def __str__(self): if len(self.data) > 0: return ",".join(self.data) else: return "[]" stack = Stack(['first','second','third','four']) stack.push("abc") stack.push("def") print(stack) print(stack.pop()) print(stack) print(stack.pop()) print(stack)
true
60e4b0ea0fccdd254b27bf3db7381ae89f6e142d
5-digits/interview-techdev-guide
/Data Structures/Trie/Trie.py
1,648
4.15625
4
class TrieNode(object): def __init__(self): self.children = [] #will be of size = 26 self.isLeaf = False def getNode(self): p = TrieNode() #new trie node p.children = [] for i in range(26): p.children.append(None) p.isLeaf = False return p def insert(self, root, key): key = str(key) pCrawl = root for i in key: index = ord(i)-97 if index > 25 or index < 0: print("Small alphabet charchters only allowed") return if(pCrawl.children[index] == None): # node has to be initialised pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isLeaf = True #marking end of word def search(self, root, key): #print("Searching %s" %key) #DEBUG pCrawl = root for i in key: index = ord(i)-97 # handling non alphabet characters if index > 25 or index < 0: return False if(pCrawl.children[index] == None): return False pCrawl = pCrawl.children[index] if(pCrawl and pCrawl.isLeaf): return True def main(): root = TrieNode().getNode() root.insert(root, "elephant") root.insert(root, "tiger") root.insert(root, "timothy") search = input("Enter the word to search for: ") if root.search(root, search): print("The word:", search, "exists") else: print("The given word doesnt exist") if __name__ == '__main__': main()
true
1c3c733e9237ca2b137a127f4e72afc5569a3fee
ThomasKisner/pythonPractice
/calculator/main.py
1,224
4.15625
4
#import regex import re print("Our Magical Calculator") print("Type 'quit' to exit\n") #initializing previous total variable previous = 0 #initializing variable which the calc will refer to to see if it should keep running run = True def performMath(): #getting run and previous into the function's scope global run global previous equation = "" #checking if a calculation has already been run, if not asking for an input if previous == 0: equation = input("Enter equation:") else: equation = input(str(previous)) #Checking if someone wants to quit or clear if equation == 'quit': print('Googbye, human') run = False elif equation == 'clear': previous = 0 print('cleared\n') #using regex to strip extraneous chars, helps to make eval statement safe. else: equation = re.sub('[a-zA-Z,.:()" "]', '', equation) if previous == 0: #if no previous value exists just evaluation input equation previous = eval(equation) else: #if previous value exists evaluate it with most recent input previous = eval(str(previous)+equation) while run: performMath()
true
18f0d82657191e25db883856110f164c2ea14eaf
jkcomm113/compciv-2018-jkeel
/week-05/sortsequences/sort_numbers.py
770
4.53125
5
from datastubs import NUMBER_LIST def reverse_numerical_order(): """ Sort the list of numbers but in reverse order """ return sorted(NUMBER_LIST, reverse=True) def numerical_order(): """ Sort the list of numbers in numerical order """ return sorted(NUMBER_LIST) # fill it out def as_absolute_value(): """ The absolute value of a number `n` is its value regardless of positive or negative sign """ return sorted(NUMBER_LIST, key=abs) # fill it out def as_inverse_number(): """ An inverse of a number `n` is defined as: `1/n` The bigger the number, the smaller its inverse, and vice versa """ def inverse(k): return 1/k sorted(NUMBER_LIST, key=inverse) # fill it out
true
7233fd761b83d8ca2e835fe5f9f2c675734d6528
damiso15/mini_python_projects
/Tutorial/stringlists.py
393
4.59375
5
# Ask the user for a string and print out whether this string is a palindrome or not. # (A palindrome is a string that reads the same forwards and backwards.) palindrome = input("Enter your word: ") new_word = palindrome[::-1] if palindrome == new_word: print(f"This word '{palindrome.upper()}' is a palindrome") else: print(f"This word '{palindrome.upper()}' is not a palindrome")
true
68bd9399dd5e6c277088cda5e482911758b6bd63
damiso15/mini_python_projects
/Tutorial/fibonacci.py
1,176
4.65625
5
# Write a program that asks the user how many Fibonacci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. # Make sure to ask the user to enter the number of numbers in the sequence to generate. # (Hint: The Fibonacci sequence is a sequence of numbers where the next number in the sequence is the sum of the # previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) def fibonacci(nth_time): # nth_time = int(input("Enter the number of sequence to be generated: ")) n0 = 1 n1 = 2 count = 0 new_list = [] if nth_time <= 0: print("\nNumber must be a positive integer: ") elif nth_time == 1: new_list.append(nth_time) print(f"\nFibonacci sequence: {new_list}") else: while count < nth_time: new_list.append(n0) nth = n0 + n1 n0 = n1 n1 = nth count += 1 new_list.append(nth) return f"\nFibonacci sequence:{new_list}" nth_time = int(input("Enter the number of sequence to be generated: ")) result = fibonacci(nth_time) print(result)
true
4b57628098ef9b0119cf0972c2767a6b01ef128a
RotemHalbreich/Ariel_OOP_2020
/Classes/week_09/TA/simon_group/3-2-numbers.py
740
4.28125
4
# Type Conversion x = 1 print(type(x)) y = 3.4 print(type(y)) # convert from int to float: a = float(x) # convert from float to int: b = int(y) # 1.0 will be 1 a = str(3.444) print(a) print(type(a)) x = 2 print("Exponentiation is nice", x, "**2 =", x ** 2) # to make random num import random print(random.randrange(1, 10)) """ Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y """
true
6d69a1d1ba294f493adc583638dbd9dd022038e8
RotemHalbreich/Ariel_OOP_2020
/Classes/week_09/TA/simon_group/6-1-functions.py
2,069
4.71875
5
#__________________________________________functions__________________________________________# #all python methods is built-in functions #assign def my_function(): print("Hello from a function") # Calling a Function my_function() # Parameters def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus") # Default Parameter Value # # If we call the function without parameter, it uses the default value: def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") # To let a function return a value, use the return statement: def my_function(x): return 5 * x print( my_function(3) ) #Argument and parameters """ From a function's perspective: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called. """ #If the number of arguments is unknown, add a * before the parameter name: def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") #You can also send arguments with the key = value syntax. def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") #If the number of keyword arguments is unknown, add a double ** before the parameter name: def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes") #List as an Argument def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] #functions can be empty: def myfunction(): pass #Recursion: function can call itself. #it can never terminates #best way to find out how it works is by testing and modifying it. def tri_recursion(k): if(k > 0): result = k + tri_recursion(k - 1) print(result) else: result = 0 return result print("\n\nRecursion Example Results") tri_recursion(6)
true
a364892efd223ac885e7760869159a1e03264fee
MingduDing/A-plan
/leetcode/数组Array/exam088.py
1,105
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/7/16 14:25 # @Author : Domi # @File : exam088.py # @Software: PyCharm """ 88.合并两个有序数组(easy) 题目:给定两个有序整数数组nums1和nums2,将nums2合并到nums1中, 使得nums1成为一个有序数组。 思路:双指针。将指针p1置为nums1的末尾,p2为nums2的末尾,在每一 步将最小值放入输出数组中。 """ def merge(nums1, m, nums2, n): """ 88.合并两个有序数组 :param nums1: 有序整数数组1 :param m: num1元素数量 :param nums2: 有序整数数组2 :param n: num2元素数量 :return: 合并后的nums1 """ p1 = m - 1 p2 = n - 1 p = m + n - 1 while p1 >= 0 and p2 >= 0: if nums1[p1] < nums2[p2]: nums1[p] = nums2[p2] p2 -= 1 else: nums1[p] = nums1[p1] p1 -= 1 p -= 1 nums1[:p2+1] = nums2[:p2+1] # 防止nums2中遗漏元素 print(nums1) nums1_1 = [5, 6, 7, 0, 0, 0] nums2_2 = [1, 2, 3] merge(nums1_1, 3, nums2_2, 3)
false
53f7b06bcc782e7a45bb253ffbf901b765d4a1b5
cyyrusli/mit6001
/finalexam/dict_interdict.py
569
4.125
4
# function f depends on the question def f(a,b): return a > b def dict_interdiff(d1, d2): ''' d1, d2: dicts whose keys and values are integers Returns a tuple of dictionaries according to the instructions above ''' intersect = {} difference = {} for key in d1: if key in d2: difference[key] = f(d1[key],d2[key]) else: intersect[key] = d1[key] for key in d2: if key not in d1: intersect[key] = d2[key] tuple_interdiff = (difference, intersect) return tuple_interdiff
true
47dc8198d00f854081d70b6ec9ad68c8ee80b27d
srknthn/InformationSecurity
/TheKey/PSet3_Encrypt.py
803
4.375
4
__author__ = 'sr1k4n7h' def substitution_cipher(text, key): H = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25} key = key.upper() if len(key) < 26: key += ''.join(sorted(set("ABCDEFGHIJLMNOPQRSTUVWXYZ").difference(key))) encrypted = '' for i in text.upper(): if i.isalpha(): encrypted += key[H[i]] else: encrypted += i return encrypted print("SIMPLE SUBSTITUTION - ENCRYPTED TEXT : " + substitution_cipher(input("ENTER THE PLAIN TEXT : "), input("ENTER THE KEY STRING : ")))
false
7e73037b4d41b3712a758343ce09c5972a0c0e06
audrec/Information-System-in-Python
/Week2/audrec_hw_2/audrec_hw_2_1_1.py
870
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Yen-Chi Chen Class: CS 521 - Spring 2 Date: 29-Mar-2021 Homework Problem #: 2.1.1 This program prompts for a number, do calculation on the input, then print if the result matches the expected calculated value. """ def calc_num(num): num = ((num + 2) * 3 - 6) / 3 return num # Take input and convert to integer. input_str = input('Enter a numeric number: ') input_int = int(input_str) # Apply calc_num function to perform the calculation, and assign to the variable result result = calc_num(input_int) # Print messages for calculated value checks. if (result == ((input_int + 2) * 3 - 6) / 3): print('The calculated value for the input ', input_str, ' is: ', result, ', which is matched to the expected result.') else: print('The calculated value for the input is not matched with the expected value.')
true
7a126889b92cc23a3af824dae35a16dcbfa08744
audrec/Information-System-in-Python
/Week3/audrec_hw_3/audrec_hw_3_14_6.py
1,541
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Yen-Chi Chen Class: CS 521 - Spring 2 Date: 05-April-2021 Homework Problem #: 3.14.6 Description: This program check if the input file exists, write in the input, read the file line by line, write each line into a list, and put and print these lists of lists as the result. """ # Test the input file for existence try: f = open('student_records.txt') print('file exists!') f.close() # If the input file is not exists, print error message except FileNotFoundError: print("File doesn't exist! Creating a new file now...") # Open the file and input 20 words, create the file if it's inexisted my_file = open('student_records.txt', "w+") my_file.writelines("Tyrion Lannister, 1, 3.7\n") my_file.writelines("Daenerys Targaryen, 52, 2.8\n") my_file.writelines("Jon Snow, 13, 3.9\n") my_file.writelines("Sansa Stark, 24, 3.4\n") # Close the file after writing words into the file my_file.close() # Initialize an empty list for the result list result_list = [] # Open the file and read it line by line with open('student_records.txt') as file: for line in file: # Initialize an empty list for each single list single_list = [] # Strip each line by \n line = line.strip() # Append this line to the single_list single_list.append(line) # Append each single_list to the result_list result_list.append(single_list) # Close the file when finished the operation on it file.close() # Print the result in the format of list of list print(result_list)
true
3bce67d9c5e52b5de880c8b5aeae417dadb61791
audrec/Information-System-in-Python
/Week2/audrec_hw_2/audrec_hw_2_2_6.py
1,396
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Yen-Chi Chen Class: CS 521 - Spring 2 Date: 29-Mar-2021 Homework Problem #: 2.2.6 This program calculates and prints all the leap years from 1899 to 2021 using for-loop and while-loop. """ # Create a list to store the leap year list_1 = [] # Calculates and prints leap years using for-loop filtered with if condition for year in range(1899, 2022): if (year % 4) == 0: if (year % 100) == 0: if (year % 400 == 0): list_1.append(str(year)) else: list_1.append(str(year)) # Print the result with comma separated each element in the list result = ','.join(list_1) print(result) # Create a list to store the leap year list_2 = [] # Initialize the year variable with value 1899 year = 1899 # Calculates and prints leap years using while-loop filtered with if condition while year >= 1899: # Break the while-loop when year reaches 2022 if (year == 2022): break if (year % 4) == 0: if (year % 100 == 0): if (year % 400 == 0): list_2.append(str(year)) else: list_2.append(str(year)) # Add 1 to the year variable for each iteration year += 1 # Print the result with comma separated each element in the list result_2 = ','.join(list_2) print(result_2)
true
d206443289bdf15b2eb046a768027b0e86552bd0
audrec/Information-System-in-Python
/Week2/audrec_hw_2/audrec_hw_2_1_3.py
882
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Yen-Chi Chen Class: CS 521 - Spring 2 Date: 29-Mar-2021 Homework Problem #: 2.1.3 This program prompts for a number, converts the input to an integer and make a calculation on it. Print the result with comma separation and with the desired format. """ # Function to apply the calculation def calc_num(n): n = n + n ** 2 + n ** 3 + n **4 return n # Take input and convert to integer value input_str = input("Please enter an integer: ") input_int = int(input_str) # Calculate by calling calc_num function and assign to the variable result result = calc_num(input_int) # Add comma separator if the result is greater than 1000 if result > 1000: result = "{:,}".format(result) # Print the output in the desired format print("{0} + {0} * {0} + {0} * {0} * {0} + {0} * {0} * {0} * {0} = {1}".format(input_str, result))
true
79c8959a444f21bc7da6201f69b2de369225281c
meghagoyal0602/Learn-Python
/class-1.py
655
4.3125
4
# name=input('input name: ') # print() # print('hello') # print(name) # first_name='Megha' # last_name='Goyal' # print(first_name last_name) # print(first_name +' ' + last_name) sentence='My name is Megha Goyal aaaa' print(sentence.upper()) print(sentence.lower()) print(sentence.count('a')) first_name=input('what is your name? ') last_name=input('what is last name? ') # print('hello ' + first_name.capitalize() +' ' + last_name.capitalize()) # output='hello, '+first_name+last_name output=f'hello, {first_name} {last_name}' # output='hello, {} {}'.format(first_name,last_name) # output='hello, {0} {1}'.format(first_name,last_name) print(output)
false
ec92cfcdd172a096c44a4e6fa2fa00fcfcce1cc5
Rider66code/PythonForEverybody
/bin/ex_04_06.py
1,989
4.4375
4
# 2.3 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking or bad user data. # 3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly. # 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your variable sum or use the sum() function. # This first line is provided for you def computepay(): if fhrs>40: pay = 40*frate+(fhrs-40)*(frate*1.5) else: pay = fhrs*frate return pay hrs = input("Enter Hours:\n") try: fhrs=float(hrs) except: print("Can't parse hours value, closing.") quit() rate = input("Enter Rate:\n") try: frate=float(rate) except: print ("Can't parse rate value, closing.") quit() p = computepay() print(p)
true
c8deb8da0a3081d6cfa416f07489452b51ec5265
Rider66code/PythonForEverybody
/bin/p3p_c2w3_ex_003.py
227
4.375
4
#Write a function called subtract_three that takes an integer or any number as input, and returns that number minus three. def subtract_three(num): subint=num-3 return subint number=6 x=subtract_three(number) print(x)
true
19a52856f363659f8fd757c8c1ad2fc5c4b13913
Rider66code/PythonForEverybody
/bin/ex_08_04.py
853
4.53125
5
# 8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. # You can download the sample data at http://www.py4e.com/code3/romeo.txt # fname = input("Enter file name: ") # fh = open(fname) # lst = list() # for line in fh: # print(line.rstrip()) fname = input("Enter file name:\n") try: fh = open(fname) except: print("Can't find file " + fname + ", closing.") quit() rlist=list() for line in fh: words=line.split() for word in words: if word not in rlist: rlist.append(word) rlist.sort() print(rlist)
true
1fcdd81958539b61521e74a6c8391f6591ef034e
Rider66code/PythonForEverybody
/bin/p3p_c2w2_practice011.py
538
4.15625
4
#5. Create a dictionary called lett_d that keeps track of all of the characters in the string product and notes how many times each character was seen. Then, find the key with the highest value in this dictionary and assign that key to max_value. product = "iphone and android phones" lett_d={} for char in product: if char not in lett_d: lett_d[char]=0 lett_d[char]+=1 temp_value=lett_d[char] for char in lett_d: if temp_value<lett_d[char]: temp_value=lett_d[char] max_value=char print(max_value)
true
b441d98f935367351ba393e5d2b69e6eb62fc2e4
Rider66code/PythonForEverybody
/bin/p3p_c3w2_ex_005.py
348
4.1875
4
#2. The for loop below produces a list of numbers greater than 10. Below the given code, use list comprehension to accomplish the same thing. Assign it the the variable lst2. Only one line of code is needed. L = [12, 34, 21, 4, 6, 9, 42] lst = [] for x in L: if x > 10: lst.append(x) print(lst) lst2=[x for x in L if x>10] print(lst2)
true
f1f929084315b9ca80a5ad02efb0d3ba11d556bd
Rider66code/PythonForEverybody
/bin/ex_03_03.py
730
4.4375
4
# 3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table: # Score Grade # >= 0.9 A # >= 0.8 B # >= 0.7 C # >= 0.6 D # < 0.6 F # If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85. score = input("Enter Score:\n") try: fscore=float(score) except: print("Cannot parse score, stopping.") quit() if fscore<0 or fscore>1: print("Score is out of range, stopping.") elif fscore>=0.9: print("A") elif fscore>=0.8: print("B") elif fscore>=0.7: print("C") elif fscore>=0.6: print("D") else: print("F")
true
a61a9dd8e303173efe651c956ba240c0c80604ad
Rider66code/PythonForEverybody
/bin/p3p_c3w1_ex_001.py
619
4.1875
4
nested2 = [{'a': 1, 'b': 3}, {'a': 5, 'c': 90, 5: 50}, {'b': 3, 'c': "yes"}] #write code to print the value associated with key 'c' in the second dictionary (90) print(nested2[1]['c']) #write code to print the value associated with key 'b' in the third dictionary print(nested2[2]['b']) #add a fourth dictionary add the end of the list; print something to check your work. nested2.append({'bob':1,'kilgore':2}) print(nested2[3]['kilgore']) #change the value associated with 'c' in the third dictionary from "yes" to "no"; print something to check your work nested2[2]['c']='no' print(nested2[2]) print(nested2[2]['c'])
true
44b53d49d776e220eddc6b61ecb2b5e817233d74
Rider66code/PythonForEverybody
/bin/p3p_c3w1_ex_006.py
562
4.59375
5
#2. Below, we have provided a list of lists that contain information about people. Write code to create a new list that contains every person’s last name, and save that list as last_names. info = [['Tina', 'Turner', 1939, 'singer'], ['Matt', 'Damon', 1970, 'actor'], ['Kristen', 'Wiig', 1973, 'comedian'], ['Michael', 'Phelps', 1985, 'swimmer'], ['Barack', 'Obama', 1961, 'president']] def list_get(somelist): templist=list() for sublist in somelist: templist.append(sublist[1]) return templist last_names=list_get(info) print(last_names)
true
37081bfd7e273b6261e209e6710ebafab8766439
Rider66code/PythonForEverybody
/bin/p3p_c4w1_ex_005.py
1,063
4.65625
5
#Create a class called Cereal that accepts three inputs: 2 strings and 1 integer, and assigns them to 3 instance variables in the constructor: name, brand, and fiber. When an instance of Cereal is printed, the user should see the following: “[name] cereal is produced by [brand] and has [fiber integer] grams of fiber in every serving!” To the variable name c1, assign an instance of Cereal whose name is "Corn Flakes", brand is "Kellogg's", and fiber is 2. To the variable name c2, assign an instance of Cereal whose name is "Honey Nut Cheerios", brand is "General Mills", and fiber is 3. Practice printing both! class Cereal: """Testing class, 2 strings, 1 integer, to 3 variables in constructor""" def __init__(self,n,b,f): self.name=n self.brand=b self.fiber=f def __str__(self): return "{} cereal is produced by {} and has {} grams of fiber in every serving!".format(self.name,self.brand,self.fiber) c1=Cereal("Corn Flakes","Kellogg's",2) c2=Cereal("Honey Nut Cheerios","General Mills",3) print(c1) print(c2)
true
aa008441857c91d8dc8c08f4d23a330ff62a5e00
Rider66code/PythonForEverybody
/bin/p3p_c2w3_ex_005.py
312
4.4375
4
#12. Write a function named intro that takes a string as input. Given the string “Becky” as input, the function should return: “Hello, my name is Becky and I love SI 106.” def intro(s): newstr='Hello, my name is {} and I love SI 106.'.format(s) return newstr name='Becky' x=intro(name) print(x)
true
b20cf3e97aab795c3369a0059da6867465207741
Rider66code/PythonForEverybody
/bin/p3p_c2w5_ex_007.py
370
4.28125
4
#4. Sort the following dictionary’s keys based on the value from highest to lowest. Assign the resulting value to the variable sorted_values. dictionary = {"Flowers": 10, 'Trees': 20, 'Chairs': 6, "Firepit": 1, 'Grill': 2, 'Lights': 14} sorted_values=[] for key,value in sorted(dictionary.items(),key=lambda stock:stock[1],reverse=True): sorted_values.append(key)
true
5cb05183bc3130546e2d3066d9284c041644d29e
Rider66code/PythonForEverybody
/bin/p3p_c2w4_example_011.py
273
4.25
4
# this works names = ["Jack","Jill","Mary"] for n in names: print("'{}!' she yelled. '{}! {}, {}!'".format(n,n,n,"say hello")) # but this also works! names = ["Jack","Jill","Mary"] for n in names: print("'{0}!' she yelled. '{0}! {0}, {1}!'".format(n,"say hello"))
false
4d464b49cfc49a35a3dd7e6a6e8218db0b3f87ea
Rider66code/PythonForEverybody
/bin/p3p_c2w3_ex_009.py
241
4.125
4
#2. Write a function called count that takes a list of numbers as input and returns a count of the number of elements in the list. def count(x): cnum=0 for num in x: cnum+=1 return cnum nlist=(1,2,3) print(count(nlist))
true
7eff73ede7c96cb6bfad9696369029c261af97c3
rahuladream/LeetCode
/April_LeetCode/Week_1/Queue/adding_element_enque.py
638
4.1875
4
class Queue: def __init__(self): self.queue = list() def add_element(self, val): # Insert element if val not in self.queue: self.queue.insert(0, val) return True return False def size(self): # Size of queue return len(self.queue) def remove_element(self): if len(self.queue) > 0: return self.queue.pop() return ("Queue is empty") the_queue = Queue() the_queue.add_element('Apple') the_queue.add_element('Mango') print("The length of queue: {}".format(the_queue.size())) print(the_queue.remove_element())
true
ee2624e6d8dfac12498e1ef101bcb90633d0c4e4
rohanmahajan1993/pythonlibrary
/generators_iterators.py
688
4.4375
4
''' Iterators can be passed in to many built in functions and also are used in for loops. All that is required is that we have a iter method that returns an object that can has next init. Usually, one class does both. ''' class IterableObject: def __init__(self, n): self.i = 0 self.n = n def __iter__(self): return self def next(self): if self.i < self.n: self.i +=1 return self.i else: raise StopIteration() iterable = IterableObject(10) for i in iterable: print i """ The generator synthax provides a more convenient way to implement generators. """ def first(n): num = 0 while num < n: yield num num +=1 a = first(10) for i in a: print i
true
d60a399e157fad6646fd6b94dcbcbf6b59cfeb45
MANOJPATRA1991/Data-Structures-and-Algorithms-in-Python
/Recursion/factorial_of_a_number.py
230
4.125
4
def factorial(num): # This is the most efficient base case as it keeps our program from crashing # if you try to compute the factorial of a negative number. if num <= 1: return 1 else: return num * factorial(num-1)
true
5d4a1145efcfe5df20efb15dd010c7116d35304e
MANOJPATRA1991/Data-Structures-and-Algorithms-in-Python
/Trees/Tree_Structure_Using_Classes/__init__.py
2,034
4.3125
4
class BinaryTree: """ Creates a Binary Tree with a root, left child and right child. Attributes: rootObj(any): The value of the root of the tree leftChild(BinaryTree): The left child of the tree rightChild(BinaryTree): The right child of the tree """ def __init__(self, rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def insert_left(self, new_node): """ Inserts a new node as the left child of the root Args: new_node(any): The value to insert """ if self.leftChild is None: self.leftChild = BinaryTree(new_node) else: t = BinaryTree(new_node) t.leftChild = self.leftChild self.leftChild = t def insert_right(self, new_node): """ Inserts a new node as the right child of the root Args: new_node(any): The value to insert """ if self.rightChild is None: self.rightChild = BinaryTree(new_node) else: t = BinaryTree(new_node) t.rightChild = self.rightChild self.rightChild = t def get_right_child(self): """ Get the right child of the root """ return self.rightChild def get_left_child(self): """ Get the left child of the root """ return self.leftChild def set_root_val(self, obj): """ Set new value for the root """ self.key = obj def get_root_val(self): """ Get the value of the root """ return self.key # r = BinaryTree('a') # print(r.get_root_val()) # print(r.get_left_child()) # r.insert_left('b') # print(r.get_left_child()) # print(r.get_left_child().get_root_val()) # r.insert_right('c') # print(r.get_right_child()) # print(r.get_right_child().get_root_val()) # r.get_right_child().set_root_val('hello') # print(r.get_right_child().get_root_val())
true
85cf8486dba0b0a8ea95b8eabe0de226ffb07dc2
javi12135/FreeCodeCamp-Challenges
/Scientific Computing with Python/Exercises/06 Strings/06-05_EX.py
404
4.5
4
#Exercise 5: Take the following Python code that stores a string: #str = 'X-DSPAM-Confidence:0.8475' #Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number str = 'X-DSPAM-Confidence:0.8475' colon = str.find(":")+1 end = len(str) number = float(str[colon:end]) print(number)
true
5b3fa8ced6372df9c2070f4376468fcaedee4552
javi12135/FreeCodeCamp-Challenges
/Scientific Computing with Python/Exercises/06 Strings/06-03_EX.py
383
4.125
4
#Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments #_def count(tocount): # count = 0 # for letter in word: # if letter == tocount: # count += 1 # print(count) word=input("What is your word?: ") tocount=input("What do you want to count?: ") print(word.count(tocount))
true
a552714cbd6f094cd8bab4e95d9d927a7a7a27c2
zamanwebdeveloper/OOP_in_Python
/92.Inheritance3.py
458
4.125
4
# Inheritance # is a relationship # Car is vehicle # Truck is vehicle class Vehicle: def __init__(self,name): self.vehicle_name = name def name(self): print(self.vehicle_name) class Car(Vehicle): def drive(self): print(self.vehicle_name,'is dirve') class Truck(Vehicle): def wheel(self): print(self.vehicle_name,'--> has 8 wheel') a = Car('Toyota') a.name() a.drive() b = Truck('tata') b.name() b.wheel()
false
459fdabf8b73d59e5f3e55884526fd6061e727cf
santi7779/PythonCrashCourse
/Chapter3/names.py
583
4.125
4
# friends = [ "Billy", "Bob", "Trevor", "Frank", "Oscar"] # print(friends[0]) # print(friends[1]) # print(friends[2]) # print(friends[3]) # print(friends[4]) # print(f"Hello {friends[0]} how are you?") # print(f"Hello {friends[1]} how are you?") # print(f"Hello {friends[2]} how are you?") # print(f"Hello {friends[3]} how are you?") # print(f"Hello {friends[4]} how are you?") cars = ["Tesla", "BMW", "Mercedes", "Mini", "Aston Martin"] # print(f"I would like to own a {cars[3]}") for c in range(len(cars)): print(cars[c]) for c in range(5): print(c)
false
d12289fa550924c56dd8058922640c952a3ddc3a
kaushiktalukdar/utility_Python
/inheritance/inheritance_demo4.py
805
4.3125
4
# https://www.w3schools.com/python/python_inheritance.asp class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) # now, have a Student class inherit Person class and with __init__ method amd super() class Student(Person): def __init__(self, fname, lname, year): # Python also has a super() function that will make the child class inherit all the methods and properties from its parent: # super means "use the original method that this class inherit from" super().__init__(fname, lname) self.my_year = year # test the Student method x = Student("mile", "oreal", 32) x.printname() print (x.firstname, x.lastname) print (x.firstname, x.lastname, x.my_year)
true
b8415210ee2e6cdce020e57a6ce54e0f5da9a86f
ramasawmy/assignment
/Assignment_6.py
779
4.125
4
list_1 = [] list_2 = [] list1 = int(input("Enter the length of list_1:")) print("enter odd value in list_1:") for i in range(list1): list1_value = int(input()) list_1.append(list1_value) list2 = int(input("Enter the length of list_2:")) print("enter even value in list_2:") for j in range(list2): list2_value = int(input()) list_2.append(list2_value) print("list_1 is :", list_1) print("list_2 is :", list_2) list_3 = [] for odd in list_1: if(odd % 2 != 0): list_3.append(odd) else: print("invalid") for even in list_2: if(even % 2 == 0): list_3.append(even) else: print("invalid") print("list_3 with odd value from list_1 and with even value from list_2 :", list_3)
false
fb4554919ffb11208d378e59babd90f0d478ca73
ksm0207/Study_P
/Part#1/example02-2.py
1,943
4.1875
4
# 슬라이싱 으로 문자열 나누기 data = "20010331Rainy" day = data[:8] # data[:8]은 data[8] 이 포함되지 않습니다 weather = data[8:] # data[8:] 은 data[8] 을 포함합니다 print("20010331 = ", day) print("Rainy = ", weather) print("Year : ", data[0:4]) print("Day : ", data[4:8]) print("Weather : ", data[8:]) # 슬라이싱 연습문제 나눠서 출력하기 name = "Kimsungmin" print("First Name = ", name[:3]) print("last Name = ", name[3:]) # Pithon 이라는 문자열을 Python 으로 바꾸기 a = "Pithon" print(a[:1] + "y" + a[2:]) b = "Namsungmin" print(b[:0] + "Kim" + b[3:]) # format 함수를 사용한 포매팅 print("I eat {0} apples".format(3)) print("I eat {0} apples".format("One")) print("I ate {0} apples so I was sick for {1} days !!".format("One", "two")) print("I ate {0} apples so I was sick for {day} days !!".format("One", day=3)) # f 문자열 포매팅 # 파이썬 3.6 버전부터는 f 문자열 포매팅 기능을 사용 할 수 있습니다 name = "홍길동" age = 26 print(f"내 이름은 {name} 입니다 나이는 {age} 이예요") print(f"나는 내년이면 {age+1} 살이 됩니다.") # f 문자열 포매팅은 name & age 와 같은 변수 값을 참조 할수 있다 # 딕셔너리 활용하기 . key 와 value 라는 것을 한 쌍으로 갖는 자료형 입니다 my = {"name": "홍길동", "age": 30} print(f"내 이름은 {my['name']} 이고 나이는 {my['age']} 입니다") # 문자열 관련 함수들 a = "".join("abcd") # 문자열 삽입 print("Join() = ", a) b = "lalalalalalalala".upper() # 소문자 --> 대문자 로 변환 print(b) c = "LALALALALALALALA".lower() # 대문자 --> 소문자 로 변환 print(c) a_strip = " Hi ".strip() # 양쪽 공백 제거 print("strip()=", a_strip) a_split = "Python Django Flask Wow!!".split() # 문자열 나누기 print("split()=", a_split)
false
40188ed9783ccf80a57df4c9f7e1674b2003218f
sandeepgholve/Python_Programming
/Python 3 Essential Training/05 Variables/variables-dictionaries.py
539
4.125
4
#!/usr/bin/python3 def main(): d = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 } print("Dictionaries: ", d) for k in d: print(k, d[k]) print("Sorted by Keys: ") for k in sorted(d.keys()): print(k, d[k]) print("Dictionaries are mutable objects") dd = dict( one = 1, two = 2, three = 3, four = 4, five = "five" ) dd["seven"] = 7 for kk in sorted(dd.keys()): print(type(kk), kk, type(dd), dd[kk]) if __name__ == "__main__" : main()
false
f23d3a877daba5711631d8ebce25517164f6d0b7
CKowalczuk/Python---Ejercicios-de-Practica-info2021
/fun_ej10.py
1,424
4.28125
4
""" Ejercicio 10: Precedencia del operador Escriba una función llamada precedencia que devuelve un número entero que representa la precedencia de un operador matemático. Una cadena que contiene el operador se pasará a la función como su único parámetro. Su función debe devolver 1 para + y -, 2 para * y /, y 3 para ˆ. Si la cadena que se pasa a la función no es uno de estos operadores, la función debería devolver -1. Incluya un programa principal que lea un operador del usuario y muestre la precedencia del operador o un mensaje de error que indique que la entrada no era un operador. En este ejercicio, se usa ˆ para representar la exponenciación, en lugar de la elección de Python de **, para facilitar el desarrollo de la solución. """ from utiles import encabezado OP_1 = "+-" OP_2 = "*/" OP_3 = "ˆ" def precedencia(operador): if operador in OP_1: return 1 elif operador in OP_2: return 2 elif operador in OP_3: return 3 else: return -1 titulo = "Ejercicio 10: Precedencia del operador" indicaciones = "Obtener la precedencia de un operador matemático" encabezado(titulo,indicaciones) operador = input("Ingrese el operador a verificar :") if precedencia(operador) > 0: print("La precedencia del operador %s es %i " % (operador, precedencia(operador))) else: print("El valor ingresado no es iun operador válido para verificar")
false
a1ab9d4bf1738928d4e72e221703ae7eedcf4a43
CKowalczuk/Python---Ejercicios-de-Practica-info2021
/fun_ej16.py
1,645
4.125
4
""" Ejercicio 16: Dígitos hexadecimales y decimales Escriba dos funciones, hex2int e int2hex, que conviertan entre dígitos hexadecimales (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E y F) y enteros de base 10. La función hex2int es responsable de convertir una cadena que contiene un solo dígito hexadecimal en un entero de base 10, mientras que la función int2hex es responsable de convertir un entero entre 0 y 15 en un solo dígito hexadecimal. Cada función tomará el valor para convertir como su único parámetro y devolverá el valor convertido como el único resultado de la función. Asegúrese de que la función hex2int funcione correctamente para letras mayúsculas y minúsculas. Sus funciones deberían finalizar el programa con un mensaje de error significativo si se proporciona un parámetro no válido. """ from utiles import encabezado def hex2int(hexa): equival = {"a":10, "b":11, "c":12, "d":13, "e":14, "f":15} hexa = hexa.lower() if hexa > "9": return equival[hexa] else: return hexa def int2hex(ente): equival = {10:"a", 11:"b", 12:"c", 13:"d", 14:"e", 15:"f"} ente = int(ente) if ente > 9: return equival[ente] else: return ente titulo = "Ejercicio 16: Dígitos hexadecimales y decimales" indicaciones = "Convertir cadenas Hexadecimales y enteras" encabezado(titulo,indicaciones) hexa=input("Ingrese una valor Hexadecimal entre 1 y f : ") ente=input("Ingrese un entero entre 0 y 15 : ") print("El valor entero del Hexadecimal ingresado es :",hex2int(hexa)) print("El valor Hexadecimal del entero ingresado es :",int2hex(ente))
false
74f998c6890376ec70bcfde78fcc5443bb6950a3
richrosenthal/Day3_Choose_Your_Own_Adventure
/main.py
1,353
4.34375
4
#Day 3 Making a choose your own Adventur game #Author Richard Rosenthal #Date 5-11-21 import time print("Welcome to escape Ikea!") user_name = input("What is your name?") print(f"Hello {user_name}") print("\nYou awake on a couch in a darken building") print("\nAs you come to your senses you realize you fell asleep in an IKEA show room") time.sleep(2) print("\nYou start to panic, however, you see what looks like an exit sign to your right and a long dark hallway to your left") time.sleep(2) print("\nTo make matters worse you hear footsteps behind you.") answer_one = input("Do you go 'left' or 'right'?") if answer_one == 'left': answer_two = input("\nGood choice, your bravery shall be rewarded. You reach another corner a closet to the right or another long hallway to the left? 'left' or 'right'?") if answer_two == 'right': answer_three = input("\nPhew the closet was just an allusion. It lead to a hidden staircase. But the footsteps are getting closer. You can either run to the bottom of the stairs to the left or you can jump out the window to the right. Do you go 'left' or 'right?'") if answer_three == 'right': print(f"\nThat was the correct choice {user_name}! You thankfully landed on top of a dumpster and made it out the building. Just drive away and never look back.") else: print(f"\nYou died {user_name}")
true
8475bf43520d376399d0685774af9639e64b3c37
karthikeyansa/python-placements-old
/python-day-2/prob4.py
247
4.21875
4
#4)Write a Python program to find the repeated items of a tuple.\ n=tuple(map(int,input("Enter the set of numbers separated by space: ").split())) m=[] for i in n: if i not in m: m.append(i) else: print(i,"repeated items")
true
eb0474408306e293bffdc85c3bcaea8c44500906
hungryglobe8/Games
/TrafficJam/coordinate.py
1,797
4.15625
4
class Coordinate(): def __init__(self, x, y): self.x = x self.y = y def __str__(self): ''' Print coordinate in (x, y) notation. ''' return f"({self.x}, {self.y})" def __eq__(self, other): return self.x == other.x and self.y == other.y def shift_left(self): ''' Coordinate (0, 0) becomes (-1, 0) ''' self.x -= 1 def shift_right(self): ''' Coordinate (0, 0) becomes (1, 0) ''' self.x += 1 def shift_up(self): ''' Coordinate (0, 0) becomes (0, -1) ''' self.y -= 1 def shift_down(self): ''' Coordinate (0, 0) becomes (0, 1) ''' self.y += 1 def extend_right(self, size): ''' Given a size, return an immutable list of coordinates stemming right from self.x and self.y. For example, extend_right(3) from (0, 0) returns: ((0, 0), (1, 0), (2, 0)) ''' coors = [Coordinate(self.x, self.y)] for num in range(1, size): coors.append(Coordinate(self.x + num, self.y)) return coors def extend_down(self, size): ''' Given a size, return an immutable list of coordinates stemming down from self.x and self.y. For example, extend_down(2) from (0, 0) returns: ((0, 0), (0, 1)) ''' coors = [Coordinate(self.x, self.y)] for num in range(1, size): coors.append(Coordinate(self.x, self.y + num)) return coors def within_range(self, x_min, x_max, y_min, y_max): ''' Determine if a coordinate falls in the range of (0, x_max) and (0, y_max), with x_max and y_max being exclusive. ''' return self.x in range(x_min, x_max) and self.y in range(y_min, y_max)
false
06d1261bc25aa98aa951aa9a5a2075b152fbc330
MohammedGhafri/data-structures-and-algorithms-python
/data_structures_and_algorithms/challenges/queue_with_stacks/queue_with_stacks.py
2,331
4.25
4
from data_structures_and_algorithms.challenges.stacks_and_queues.stacks_and_queues import Node,Stack s1=Stack() s2=Stack() class PseudoQueue: """ This class create a queue with 2 stacks Has two method -till now- enqueue and dequeue """ def __init__(self): self.s1=Stack() self.s2=Stack() def enqueue(self,value): """ do enqueue with push and pop methods from Stack """ if self.s1.top==None: self.s1.push(value) else: current=self.s1.top while current: # a=self.s1.pop() # print("from else",a) a=self.s1.pop() if a=="All Nodes have been poped": break self.s2.push(a) print("How many Times",a) # current=current.next self.s1.push(value) current_2=self.s2.top while current_2: # print("push") # print(self.s2.peek()) b=self.s2.pop() if b=="All Nodes have been poped": break print("This is B: ",b) # print("this is b",b) self.s1.push(b) # current_2=current_2.next def dequeue(self): """ do dequeue with push and pop methods from Stack using FIFO """ if self.s1.top: temp=self.s1.top self.s1.top=self.s1.top.next temp.next=None return temp.value def __str__(self): """ return string of Queue output-{string} """ output='' current=self.s1.top while current: output+=f"{current.value} -> " current=current.next output+= "None" return output if __name__=='__main__': q=PseudoQueue() q.enqueue("A") q.enqueue("B") q.enqueue("C") q.enqueue("D") # # print(q.dequeue()) print(q,"queue") # # print(q.s2.top.value) print("dequeue",q.dequeue()) print("dequeue",q.dequeue()) print("dequeue",q.dequeue()) print("dequeue",q.dequeue()) print("dequeue",q.dequeue())
false
4905790ec2556d50a4cf35d0ec8a1b7cf8dc4a30
PixElliot/andela-bc-5
/Fizz Buzz Lab.py
382
4.125
4
#!/usr/bin/env python def fizz_buzz(num): if (num % 3 == 0) and (num % 5 == 0): # If num divisible by 3 & 5 return 'FizzBuzz' elif num % 3 == 0: # If num divisible by 3 return 'Fizz' elif num % 5 == 0: # If num divisible by 5 return 'Buzz' else: # If num not divisible by 3 & 5 return num
false
65a0f82d98dd8ac8b102310ba030decb8d5c0768
xingshuiyueying/NewLearner
/palindome1.py
966
4.1875
4
# 网上copy下来的,未完成要求 # 设置需要过虑的标点符号 forbidden = (".", "?", "!", ":", ";", "-", "—", "()", "[]", "...", "'", '""', "/", ",", " ") # 获取一个字符串,书中要求确认"Rise to vote, sir."是回文 text = input("请输入:") #将字符串倒过来 def reverse(text): str_tmp = [] str = "" for i in range(0,len(text)): if text in forbidden: continue else: str_tmp.append(text.lower())#方便比较,将字母转成小写字母 return str.join(str_tmp)[::-1] #做是否是回文检测 def is_palindrome(text): str_tmp = [] str = "" for i in range(0,len(text)): if text in forbidden: continue else: str_tmp.append(text.lower()) return str.join(str_tmp) == reverse(text) #输出检测结果 if is_palindrome(text): print(text, "是回文") else: print(text, "不是回文")
false
1a7af0f7c7a05a307648e13984082765187e8fef
dani-fn/Projetinhos_Python
/projetinhos/ex#60 - cálculo de fatorial.py
424
4.1875
4
from math import factorial n = int(input('Digite um número para saber seu fatorial: ')) sequence = 0 while sequence != 2: if n == 1 or n == 0: sequence = 2 print('!{} '.format(n), end='') else: print('!{} = '.format(n), end='') for sequence in range(n, 1, -1): print(sequence, 'x ', end='') print('1 ', end='') print('= {}'.format(factorial(n)))
false
faf6eec81bb3cb2e2628495b9123f0f86ac7c229
dani-fn/Projetinhos_Python
/aulas/Aula#17-listas1.py
1,222
4.25
4
lanche = ['hamburguer', 'suco', 'pizza', 'pudim'] print(lanche) lanche[2] = 'sorvete' # São MUTÁVEIS print(lanche) lanche.append('cookie') # Adiciona no final print(lanche) lanche.insert(0, 'hot dog') # Adiciona onde eu quiser, sem tirar nada print(lanche) del(lanche[0]) # ou lanche.pop(0) # pop() tira o ÚLTIMO print(lanche) lanche.remove('cookie') # removo determinado valor (sem colocar o índice) print(lanche) if 'pizza' in lanche: lanche.remove('pizza') #todo o que faz o comando "pass" valores1 = list(range(4, 11, 2)) # outra forma de criar uma lista print(valores1) valores2 = [5, 2, 7, 6, 8, 1, 9] # Sem ordem print(valores2) print(valores2[3]) # → 6 valores2.sort() # Organizar em ordem print(valores2) valores2.sort(reverse=True) # Organizar ao inverso print(valores2) print('-' * 32) print(f'Essa lista tem {len(valores2)} elementos') # podemos usar o "len" valores2.insert(5, 8) # pos 5 valor 8 print(valores2) valores2.remove(8) # Tirou só o primeiro "8" print(valores2)
false
ae2cb20b5f88cc8af74842fb577ed4601a6b904e
dani-fn/Projetinhos_Python
/aulas/Aula#7 - operadores aritméticos - anotações.py
660
4.3125
4
print('"+" Adição') print('"-" Subtração') print('"*" Multiplicação') print('"/" Divisão real') print('"**" Potenciação') print('"//" Divisão inteira') print('"%" Módulo ou resto da divisão') print('------------------------------------') #Todo operador(no caso, os operadores aritméticos), precisa de um operando #No caso a cima, temos operadores binários, isto é, que precisam de dois operandos print(5+2) print(5-2) print(5*2) print(5/2) print(5**2) print(5//2) print(5%2) print(18%2) #Ordem de Precedência é a mesma que a da escola, "()" - "**" - "*, /, //, %" - "+, -" print(3*5+4**2) print(3*(5+4)**2)
false
8139dee0d7a7febfb105846a4b8bb298fadf410f
mithrandil444/Make1.2.1
/leeftijd.py
809
4.3125
4
#!/usr/bin/env python """ This script will ask you in which year you were born en calculate how old you are and in which year you will be 50 years old.. Bron : https://www.youtube.com/watch?v=7lg5BHLrw4E """ # IMPORTS import datetime __author__ = "Sven De Visscher" __email__ = "sven.devisscher@student.kdg.be" __status__ = "Development" # CONFIGURING I/O Age = int(input('Please enter the year you were born: ')) # Input that asks you for your birthyear Year = datetime.datetime.now().year # Finds the current year that is displayed on your laptop def main(): print('You are ', Year - Age, ' Years old') # Print your current age print('You will be 50 in this year: ',Age + 50) # Print the year were you will be 50 years old if __name__ == '__main__': # code to execute if called from command-line main()
true
817b67418e4de2ac72ab26c8686f989d29042a0f
Kotarosz727/python-algorism
/bubble_sort.py
468
4.125
4
def bubble_sort(numbers): len_numbers = len(numbers) while len_numbers > 1: len_numbers -= 1 for i in range(0, len_numbers): if numbers[i] > numbers[i+1]: numbers[i] , numbers[i+1] = numbers[i+1], numbers[i] return numbers # numbers = [2,5,1,8,7,4,3] # res = bubble_sort(numbers) # print(res) import random numbers = [random.randint(0, 1000) for i in range(10)] res = bubble_sort(numbers) print(res)
true
1d148131a8f0533658493bf9ad4de3e6f40e8ace
abdalimran/46_Simple_Python_Exercises
/28.py
324
4.1875
4
from functools import reduce def find_max(x,y): if x>y: return x else: return y def find_longest_word(words): lengths = list(map(len,words)) return (reduce(find_max,lengths)) def main(): words = input("Enter the list of words: ").split() print(find_longest_word(words)) if __name__=="__main__": main()
true
9d7036a5b7a93956ece880558141aeb556cfebf6
maherme/python-deep-dive
/Variables_Memory/EverythingObject.py
1,007
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 24 20:33:42 2021 @author: maherme """ #%% a = 10 print(type(a)) # Notice a is a class b = int(10) # We can create a new class using the constructor as an integer print(b) print(type(b)) #%% # You can get some help using help(int) for example # We can use the constructor according the help document: c = int() print(c) c = int('101', base=2) print(c) #%% # A function is also a class def square(a): return a ** 2 print(type(square)) f = square print(id(square)) print(id(f)) print(f is square) #%% # Notice we can return functions from other functions: def cube(a): return a ** 3 def select_function(fn_id): if fn_id == 1: return square else: return cube f = select_function(1) print(f is square) f = select_function(2) print(f is cube) print(select_function(2)(3)) #%% def exec_function(fn, n): return fn(n) print(exec_function(cube, 3)) print(exec_function(square, 3)) #%%
true
2588dc0d7a0f92cec88cb9d49ad448bc571d9ff8
maherme/python-deep-dive
/Extras/RandomSeeds.py
1,783
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 10 00:35:44 2021 @author: maherme """ #%% import random for _ in range(10): print(random.randint(10, 20), random.random()) #%% # Every time you reset the seed the sequence will start with the same values: random.seed(0) for _ in range(10): print(random.randint(10, 20), random.random()) print("----------------------") random.seed(0) for _ in range(10): print(random.randint(10, 20), random.random()) #%% # random has other interested methods like shuffle or gauss: def generate_random_stuff(seed=None): random.seed(seed) results = [] for _ in range(5): results.append(random.randint(0, 5)) characters = list('abc') random.shuffle(characters) results.append(characters) for _ in range(5): results.append(random.gauss(0, 1)) return results #%% generate_random_stuff() generate_random_stuff(0) # We get the same result than above if we use the same seed generate_random_stuff(0) generate_random_stuff(25) # We get the same result than above if we use the same seed generate_random_stuff(25) #%% # How to test the above?. We can do a frequency analysis: def freq_analysis(lst): return {k: lst.count(k) for k in set(lst)} lst = [random.randint(0, 10) for _ in range(100)] print(lst) set(lst) freq_analysis(lst) # You can see frequency is not uniform #%% # We can increase the number: d = freq_analysis([random.randint(0, 10) for _ in range(1_000_000)]) total = sum(d.values()) # total has to match with 1 million. {k: v/total * 100 for k, v in d.items()} #%% # The functionality above is implemented in Counter class: from collections import Counter Counter([random.randint(10, 20) for _ in range(100_000)]) #%%
true
26a1d204dcfbd8f918d2e4cca6f822ed84cac3cf
maherme/python-deep-dive
/Basics/for.py
1,928
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 9 23:43:32 2021 @author: maherme """ #%% # In Python, an iterable is an object capable of returning values one at a # time. # In other lenguages a for loop is similar to: for(int i=0; i<5; i++){...} # This is similar to a while loop: i = 0 while i < 5: print(i) i += 1 i = None #%% # In Python a for loop is used with iterable items. # In this code range() is an iterable which return a number which is stored in # i. for i in range(5): print(i) #%% # As iterable, you can do a for with a list: for i in [1, 2, 3, 4]: print(i) #%% # You can also use a string: for c in 'hello': print(c) #%% # You can also use a tuple: for x in ('a', 'b', 'c', 4): print(x) #%% # You can create more complex loops: for i, j in [(1, 2), (3, 4), (5, 6)]: print(i, j) #%% # You can use other statements inside a for loop: for i in range(5): if i == 3: break print(i) #%% # You can also use an "else" statement: for i in range(1, 5): print(i) if i % 7 == 0: print('multiple of 7 found') break else: print('no multiples of 7 in the range') #%% # You can also use "try catch" statement. This working in the same way than # in while loop. for i in range(5): print('--------------------') try: 10/(i-3) except ZeroDivisionError: print('divided by 0') continue finally: print('always run') print(i) #%% # You don't need the index for an iterable with index like a string: s = 'hello' for c in s: print(c) #%% s = 'hello' i = 0 for c in s: print(i, c) i += 1 #%% s = 'hello' for i in range(len(s)): print(i, s[i]) #%% # This is a more readable way to implement the code above: s = 'hello' for i, c in enumerate(s): print(i, c) #%%
true