blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
8c468a4dbb5cc22029f6f940a187328260ea67bb
ColeHiggins2/data-structure-practice
/sorting/binarysearch.py
1,272
4.21875
4
# recursive binary search def binarySearch (arr, l, r, x): if r >= l: mid = l + (r-l)/2 if arr[mid] == x: return mid # if element is smaller, its only in left elif arr[mid] > x: return binarySearch(arr, l, mid-1, x) # else the elemtnt is only in right else: return binarySearch(arr, mid+1, r, x) # not present else: return -1 #helper code arr = [1,2,3,4,5] x = 3 results = binarySearch(arr, 0, len(arr)-1, x) if results != -1: print("element is at index:", results) else: print("element is not present in array") #iterative binary search def Iterativesearch(arr2, l, r, x): while l <= r: mid = l + (r-1)/2; #if element is at middle if arr2[mid] == x: return mid # if element is greater, ignore left half elif arr2[mid] < x: l = mid + 1 # if element is smaller, ignore right half else: r = mid - 1 # element not present return -1 # helper code arr2 = [2,3,5,6,7] x = 3 results = Iterativesearch(arr2, 0, len(arr2)-1, x) if results != -1: print("element is at index:", results) else: print("element is not present in array")
true
2ebcc1c9887aa4242ef2da5e5c6fc16240c729e0
NajlaaNawaii/DataStructures
/LinkedLists.py
996
4.25
4
#A single node that holds Data and Point to the next node class node: #Constructor def __init__(self,data,next=None): self.data=data self.next=next #Creating a single node first=node(3) #Creating A linkedList with a single head node class LinkedList: def __init__(self): self.head=None ##linkedList with a single head node #LL=LinkedList() #LL.head=node(3) #print(LL.head.data) #insertion methods def insert(self,data): newNode=node(data) if(self.head): current=self.head while(current.next): current=current.next current.next=newNode else: self.head=newNode #print method def print(self): current=self.head while(current): print(current.data) current=current.next LL=LinkedList() LL.insert(3) LL.insert(5) LL.insert(6) LL.insert(9) LL.print()
true
f7ac142ff415daaba05d557166ce5d9ab9c24daf
Taveeh/Fundamentals-of-Programming
/Assignment 1/Third Set.py
1,882
4.21875
4
# [12] Determine the age of a person, in number of days. Take into account leap years, as well as the date of birth and current date (year, month, day). from datetime import date ''' Verifies if a year is a leap year Input: y - year Output: True - if y is leap year ''' def leapYear(y): if y != 4: return False if y != 100: return True if y != 400: return False return True ''' Verifies if it is a valid date of birth Input: y, m ,d - integers Output: True - if it is a valid date False - otherwise ''' def verify(y, m, d): if y > date.today().year or y <= 0: return False if y < date.today().year: if m > 12 or m < 0: return False if d > 31 or d < 0: return False if m == 2: if leapYear(y) and d > 29: return False if not leapYear(y) and d > 28: return False if (m == 4 or m == 6 or m == 9 or m == 11) and d > 30: return False return True if y == date.today().year: if m > date.today().month: return False elif m < date.today().month: return True else: if d > date.today().day: return False else: return True year = int(input("Year of birth: ")) month = int(input("Month of birth: ")) day = int(input("Day of birth: ")) if not verify(year, month, day): print("Please enter a valid date of birth") else: current_date = date.today() birth_date = date(year, month, day) time = current_date - birth_date if time.days == 0: print("Welcome to the new world, because today you were born") elif time.days == 1: print('You have been born yesterday. Literally!') else: print ('You have lived for',time.days,'days so far')
false
a5211cd84f5fa6c4e225870f871b2f6e308c6a7b
Taveeh/Fundamentals-of-Programming
/Assignment 1/Second Set.py
411
4.25
4
# [9] Consider a given natural number n. Determine the product p of all the proper factors of n. ''' Function to calculate the product of the proper factors of a number Input: n - integer Output: p, product of the factors - integer ''' def product(n): p = 1 for i in range(2, int(n / 2) + 1): if n % i == 0: p *= i return p n = int(input('Give n = ')) print(product(n))
true
136a9a7ff961a0b68d7f29823fea260346294ca6
bullethammer07/Python_Tkinter_tutorial_repository
/tkinter_events.py
1,672
4.5625
5
#--------------------------------------------------- # Events in Tkinter #--------------------------------------------------- # NOTE : Visit site : https://effbot.org/tkinterbook/tkinter-events-and-bindings.htm for details of different events in tkinter # also refer documentation. from tkinter import * root = Tk() root.title("Events in Tkinter") root.geometry("700x500") # Making function 'get_val' for button def button_beh(): pass # NOTE : The function (below) has been specified with bind. # these functions take the event as the input argument. # below we have specifed the event as 'evt', this can be specified with any name def click_beh(evt): # NOTE : We can use the attributes 'x' and 'y' of the event argument specified 'evt' # the 'x' and 'y' return the coordinates where the click was made print(f"Button Clicked !!... {evt.x , evt.y}") # Making function for hovering or entering into the button area def btn_hover(evt): print(f"Coordinates : {evt.x , evt.y}") # Making a button # NOTE : here we have specified a color using 'activebackground' for what happens when the button is clicked. # highlight options can be specified using : highlightbackground, highlightcolor and highlightthickness. refer documentation for more details. bt1 = Button(root, text="Click Me", padx=10, pady=10, command=button_beh, bg="yellow", activebackground='#696969') bt1.pack() # Binding clicking of left mouse button event to the widget bt1.bind("<Button-1>", func=click_beh) # binding hovering of pointer event to the widget bt1.bind("<Enter>", func=btn_hover) root.mainloop()
true
d35b38617a53caaeef8742191873837dec15807d
bullethammer07/Python_Tkinter_tutorial_repository
/dropdown_options.py
682
4.21875
4
import tkinter as tk # Create the main window root = tk.Tk() root.title("Dropdown Menu") # Define the options options = ["Option 1", "Option 2"] # Create a Tkinter variable selected_option = tk.StringVar() selected_option.set(options[0]) # set the default option # Create the OptionMenu widget dropdown = tk.OptionMenu(root, selected_option, *options) dropdown.pack(padx=10, pady=10) # Function to print selected option def print_option(): print(f"Selected option: {selected_option.get()}") # Button to print selected option button = tk.Button(root, text="Print Selected Option", command=print_option) button.pack(padx=10, pady=10) # Start the main loop root.mainloop()
true
333befd4abd43bd223edd16299837c29edbefd90
tanwm348/git_thub
/ad/work_spacepy/day04/a04_输出.py
537
4.125
4
# 深入解析一下 输出函数 # sep 是输出之间的空格 end 不换行 aa = "1" bb ="2" cc= 33 print(aa,bb,cc,sep="*" ,end="--------" ) # print(11111) print("这是aa的值:"+aa+"这是bb的值:"+bb+"这是cc的值"+str(cc)) # 注意 字符串和数字不能直接相加,需要强制转换类型 # %s:字符串 %d:整数 %f.1(1表示保留1位小数):小数 # %后面可以加数字 表示长度 # 使用占位符 print("这是aa的值:%-10s这是bb的值:%10s 这是cc的值:%d"%(aa,bb,cc))
false
592416ed0f0f380d9f9529f6d7a2c8b8016abfc4
juliodparedes/python_para_dioses
/condicionales.py
265
4.125
4
numero=int(input("Humano por favor ingresa un numero POSITIVO: ")) if numero<0: print("Humano que parte de numero POSITIVO NO ENTIENDES") elif numero==0: print("Humano el 0 no es positivo, es neutro") else: print("Buen chico ahora dame la patita")
false
d85a79ead2d136a9ab159bdba73144accacb2540
juliodparedes/python_para_dioses
/operadorAritmetico.py
503
4.21875
4
num1=5 num2=3 resultado=num1+num2 print("La suma es: ",resultado) resultado=num1-num2 print("La resta es: ",resultado) resultado=num1*num2 print("La multiplicacion es: ",resultado) resultado=num1/num2 print("La división es: ",resultado) resultado=num1//num2 print("La división entera es: ",resultado) resultado=num1%num2 print("El módulo es: ",resultado) resultado=num1**num2 print("El exponente es: ",resultado) resultado=3**3 * ( 13/5 * (2*4) ) print("El resultado es: ",resultado)
false
eaf44d9d56f9046a416266bac1de070d6cf0d106
Billoncho/SayOurName
/SayOurName.py
594
4.21875
4
# SayOurName.py # Billy Ridgeway # Lets everybody print their names on the screen. # Asks the user to input their name. name = input("What is your name? ") # Keep printing names until we want to quit. while name != "": # Print their name 100 times. for x in range(100): # Print their name followed by a space, not a new line. print(name, end = " ") print() # After the for loop, skip down to the next line. # Ask for another name, or quit. name = input("Type another name, or just hit [ENTER] to quit: ") print("Thanks for playing!")
true
671c1e90a8ac376d34d7f82137801b34d7b71ccf
ZachW93/Python-Projects
/DailyProgrammer/IntermediateChallenge/CardFlippingGame.py
1,767
4.15625
4
''' This challenge is about a simple card flipping solitaire game. You're presented with a sequence of cards, some face up, some face down. You can remove any face up card, but you must then flip the adjacent cards (if any). The goal is to successfully remove every card. Making the wrong move can get you stuck. In this challenge, a 1 signifies a face up card and a 0 signifies a face down card. We will also use zero-based indexing, starting from the left, to indicate specific cards. So, to illustrate a game, consider this starting card set. 0100110 I can choose to remove cards 1, 4, or 5 since these are face up. If I remove card 1, the game looks like this (using . to signify an empty spot): 1.10110 I had to flip cards 0 and 2 since they were adjacent. Next I could choose to remove cards 0, 2, 4, or 5. I choose card 0: ..10110 Since it has no adjacent cards, there were no cards to flip. I can win this game by continuing with: 2, 3, 5, 4, 6. Supposed instead I started with card 4: 0101.00 This is unsolvable since there's an "island" of zeros, and cards in such islands can never be flipped face up. ''' def flip(card_list): subresult = [] result = [] for i in range(len(card_list)): if (card_list[i] == 0): subresult = [i] + subresult else: if (i+1 < len(card_list)): card_list[i+1] = (card_list[i+1] + 1) % 2 result = result + [i] + subresult subresult = [] if (subresult == []): print(result) else: print("No solution") def flips(card_input): flip([int(num) for num in card_input])
true
bd491d77ef8a4e7fd01071d1f161412a963b55ea
ZachW93/Python-Projects
/DailyProgrammer/EasyChallenge/YahtzeeUpper.py
1,686
4.34375
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 19:20:27 2020 @author: Zach Challenge: [Easy] Yahtzee Upper Section Scoring The game of Yahtzee is played by rolling five 6-sided dice, and scoring the results in a number of ways. You are given a Yahtzee dice roll, represented as a sorted list of 5 integers, each of which is between 1 and 6 inclusive. Your task is to find the maximum possible score for this roll in the upper section of the Yahtzee score card. Here's what that means. For the purpose of this challenge, the upper section of Yahtzee gives you six possible ways to score a roll. 1 times the number of 1's in the roll, 2 times the number of 2's, 3 times the number of 3's, and so on up to 6 times the number of 6's. For instance, consider the roll [2, 3, 5, 5, 6]. If you scored this as 1's, the score would be 0, since there are no 1's in the roll. If you scored it as 2's, the score would be Expected Output: yahtzee_upper([2, 3, 5, 5, 6]) => 10 yahtzee_upper([1, 1, 1, 1, 3]) => 4 yahtzee_upper([1, 1, 1, 3, 3]) => 6 yahtzee_upper([1, 2, 3, 4, 5]) => 5 yahtzee_upper([6, 6, 6, 6, 6]) => 30 """ def yahtzee_upper(yahtzeeRoll): yahtzeeDict = {} score = 0; for roll in range(1,7): yahtzeeDict[roll] = roll*yahtzeeRoll.count(roll) if yahtzeeDict[roll] > score: score = yahtzeeDict[roll] else: continue print(score) yahtzee_upper([2, 3, 5, 5, 6]) yahtzee_upper([1, 1, 1, 1, 3]) yahtzee_upper([1, 1, 1, 3, 3]) yahtzee_upper([1, 2, 3, 4, 5]) yahtzee_upper([6, 6, 6, 6, 6])
true
38a15645f2c98580e407c7834050994238296a69
alexander07081984/python_practise
/level_2.3.py
505
4.34375
4
''' Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: Example: without,hello,bag,world Output: bag,hello,without,world ''' print("Enter the words: ") user_input = input() words = user_input.split(",") print("Unsorted: ", words) #print(type(words)) sorted_words = sorted(words) print("Sorted: ", sorted_words)
true
4a0c5c706e881955ff6114f324191eec5261de31
alexander07081984/python_practise
/level_2.4.py
517
4.25
4
''' Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT ''' lines = [] while True: user_input = input() if(user_input): lines.append(user_input) else: break print(lines) upper = [words.upper() for words in lines] print(upper)
true
fbada227d8e18ed91b81b548bf3597b51a1a5bef
ravisaikiran/normal-python-programs
/nestedlists.py
913
4.15625
4
Given the names and grades for each student in a class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line. Output Format Print the name(s) of any student(s) having the second lowest grade in. If there are multiple students, order their names alphabetically and print each one on a new line. Sample Input: 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Sample Output : Berry Harry solution: dic={} s=[] for _ in range(int(raw_input())): name = raw_input() score = float(raw_input()) if score in dic: dic[score].append(name) else: dic[score]=[name] if score not in s: s.append(score) x=min(s) s.remove(x) y=min(s) dic[y].sort() for i in dic[y]: print(i)
true
e05b9025b9a0801d861efec40e07701dfed078c2
TranBinhLuatUIT/Data-Structures-And-Algorithms
/07-SquareRootOfAnInteger.py
977
4.375
4
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number == None: return None if(number < 0): return None left = 0 middle = 0 right = number while left <= right: middle = (left + right)//2 target = middle*middle if target == number: return middle elif target > number: right = middle - 1 else: left = middle + 1 return right print ("Pass" if (None == sqrt(number=None)) else "Fail") print ("Pass" if (None == sqrt(-2)) else "Fail") print ("Pass" if (0 == sqrt(0)) else "Fail") print ("Pass" if (1 == sqrt(1)) else "Fail") print ("Pass" if (5 == sqrt(27)) else "Fail") print ("Pass" if (10 == sqrt(100)) else "Fail") print ("Pass" if (11 == sqrt(128)) else "Fail")
true
ddba1e7ea110ad30ab77dcdc446a60013b4b505e
dpradhan25/Robotics-Tasks-2021
/Chirag Pradhan/project_04/project-04.py
1,065
4.3125
4
import random moviename = ['lagaan','highway','thor','dangal','newton'] #function will choose one random word from the given list moviename = random.choice(moviename) print("Guess the movie") guesses = '' #initial score of the user score = 10 while score > 0: #counts the number of times the letter does not match c=0 for char in moviename: if char in guesses: print(char,end="") else: print('*',end="") c+=1 if c >=1: print("") print("Your Score:",score) if c ==0: print("") print("Your Score:",score) print("YOU WIN!!") break #user has to input new alphabet if the previous alphabet did not match guess=input("Guess a letter:") #new input will be stored in guesses guesses += guess if guess not in moviename: score-=2 print("Wrong guess!Try again.") if(score <= 0): print("YOU LOOSE!") else: print("Correct Guess") score+=3
true
7ac9383ee3aa43a5fb6a51358eacd991a7c26988
Bimsara615/binary-calculator
/Output_Module.py
354
4.3125
4
# Defining a function which displays the binary values of input numbers and print their sum def output_function (digit1, digit2, binary_sum): print("\nBinary equivalent of the 1st number is: " ,digit1) print("Binary equivalent of the 2nd number is: " ,digit2) print("\nThe binary addition of these digits is = ",binary_sum) print("\n")
true
849f1116c2a41adb2554ce17d63e3892114557b7
mmcheng93/common_interview_questions
/linear_search.py
737
4.28125
4
def linear_search(data, x): """Perform a linear search through a list (data) for a value called (x) and return the indices of the value.""" indices = [] for i in range (0, len(data)): if (data[i] == x): indices.append(i); return indices if __name__ == "__main__": data = [] # A list of values to be searched x = 0 # A value you are looking for result = linear_search(data, x) if len(result) == 0: # If the value you are looking for is not in the list print(str(x) + " is not in the list.") else: indices = str(result).replace("[", "") indices = indices.replace("]", "") print(str(x) + " is present at the following indices " + indices)
true
2ec6573333a9e87e25e9d51187913bc5c6bada62
AndersonHJB/PyCharm_Coder
/Coder_Old/data-analysis/06-Python/6.7课堂练习.py
1,156
4.3125
4
#!/usr/bin/env python # encoding: utf-8 ''' @author: DeltaF @software: pycharm @file: 6.7课堂练习.py @desc: ''' str1 = "abc" int1 = 123 float1 = 123.123 bool1 = True # 1. 创建数据容器 list1 = [str1, int1, float1, bool1, str1, int1, float1, bool1] set1 = {str1, int1, float1, bool1, str1, int1, float1, bool1} dict1 = {'string': str1, 'int': int1, 'float': float1} # 2. 打印、查看数据类型 print(list1) print(set1) print(dict1) print(type(list1)) print(type(set1)) print(type(dict1)) # 3. 转换数据类型 print("-----------------") print(int(float1)) # 基础数据类型的转换 print(type(int(float1))) print(set(list1)) print(type(set(list1))) # set 和 list 的转换 print(list(set(list1))) # 4. 查找数据、更新、删除 print("-----------------") # print(list1) # print(list1[2]) # print(set1) # print(list(set1)[2]) # for set1: # print(dict1) # print(dict1['string']) # print(list1.append("append")) # print(list1) # print(list1.remove(True)) # print(list1) # print(set1.add('append')) # print(set1) # print(set1.remove('append')) # print(set1) dict1['key'] = 'append' print(dict1) del dict1['key'] print(dict1)
false
5e57022f2c0c22b438d73658bdae7034620659a8
4mayet21/COM404
/4-repetition/1-while-loop/6-sum-user-numbers/bot.py
337
4.125
4
numNum = int(input("how many numbers should I add up: ")) numAns = 0 numQNum = 1 numNumMod = numNum while numNum > 0: numAdd = input("please enter number " + str(numQNum) + " of " + str(numNumMod) + ": ") numAns = numAns + int(numAdd) numNum = numNum - 1 numQNum = numQNum + 1 print("the Answer is " + str(numAns))
false
ca882af3c1adcd489262c8d21eb03af6e4d97a81
4mayet21/COM404
/4-repetition/3-nested-loop/1-nested/bot.py
253
4.1875
4
rows = int(input("how many rows should I have? ")) cols = int(input("how many columns should I have? ")) face = ":-)" print("here I go") for row in range(0, rows): for col in range(0, cols): print(face, end="") print() print("done!")
true
d54d583130f1aeea72fa456237e146c7efdbac6e
4mayet21/COM404
/3-decision/6-counter/bot.py
696
4.15625
4
#ask for 3 numbers print("please enter a whole number") num_first = int(input()) print("please enter a second whole number") num_second = int(input()) print("please enter a third whole number") num_third = int(input()) #modulo to make o or 1 (maybe?) num_first_rem = num_first % 2 num_second_rem = num_second % 2 num_third_rem = num_third % 2 #count how many odds and evens if num_first_rem + num_second_rem + num_third_rem == 0: print("there are 3 evens") elif num_first_rem + num_second_rem + num_third_rem == 1: print("there are 2 evens and 1 odd") elif num_first_rem + num_second_rem + num_third_rem == 2: print("there are 2 odds and 1 even") else: print("there are 3 odds")
false
f722a64a5ec2a64420dfe87045801eab38896f79
riturajbasant/GitTest
/Class/Encapsulation.py
2,091
4.3125
4
''' Encapsulation is an important aspect of Object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident. Data Abstraction and encapsulation both are often used as synonyms. both are nearly synonym because data abstraction is achieved through encapsulation. Abstraction is used to hide internal details and show only functionalities. There are three types of modifiers. 1. public : Data can be used from inside and outside 2. Protected : _ is used to make it protected : It is like a data will be like public member but they should not be directly accessed from outside 3. Private : __ used to make it private : can't be seen and accessed from outside #Private class sample: __a=12 def __show(self): #(we can also make function private by applying __ and it won't be accessible outside of class) __ab=39 print("In show") print(self.__a) #we will always call class veriables from objects within a function print(__ab) # if we are defining private method into method then we can't access private member outside of the method obj= sample() #print(obj.__a) #can't call private member outside of method #obj.show() #this won't work incase of private method obj._sample__show()# to call private method Jugad #if we want to call private out of the class (Jugad method) print(obj._sample__a) class A: def __sample(self): self.__ab=32 print("Hello world", self.__ab) class B(A): def example(self): self._A__sample() print("In example ", self._A__ab) b=B() b.example() class __A: def sample(self): print("In sample") class B(__A): def example (self): print("In example") c=B() c.sample() c.example() ''' #Protected class A: _ab=34 def sample(self): self._a=25 print("Hello World", self._a) class B(A): def example(self): print("hello in example", self._a) c=B() print(c._ab) c.sample() c.example()
true
d571c79d813b653d5fdca0094392d44f0212fce2
jboles31/Python-Sandbox
/tuples_sets/tuples.py
842
4.28125
4
# TUPLES # ordered collection of items # immutable # cannot update/remove from it single_element_tuple = (1,) tuple_example = (1,2,3) values = (1,2,3) static_values = tuple(values) # why use tuple # faster and lighter weight than a list # tuples are valid keys in a dictionary, unlike a list, a key of a coordinate location is a good example # EXAMPLE of a good tuple # would be the months of the year # you don't need to ever change the months # Tuple Unpacking # Star Args will create a tuple of all the args given. We must unpack the tuple, made from the list provided as an arg # When you have a function that accepts star args, but is passed a list not multiple args def sum_all_values(*args): total = 0 for num in args: total += num print(total) nums = [1,2,3,4] # pass list with a star in front sum_all_values(*nums)
true
b79d4dcdd71a899361db082cd8b30e7a416e964e
Melting-Pot-Solutions-LLC/studies
/coding_supporting_routines/python/from_hackerrankcom.py
1,378
4.3125
4
# textwrap.wrap() # The wrap() function wraps a single paragraph in text (a string) so that every line is width characters long at most. # It returns a list of output lines. >>> import textwrap >>> string = "This is a very very very very very long string." >>> print textwrap.wrap(string,8) ['This is', 'a very', 'very', 'very', 'very', 'very', 'long', 'string.'] # textwrap.fill() # The fill() function wraps a single paragraph in text and returns a single string containing the wrapped paragraph. # >>> import textwrap >>> string = "This is a very very very very very long string." >>> print textwrap.fill(string,8) # This is # a very # very # very # very # very # long # string. ------------------------------------------------------------------------------------------------------------------ #.ljust(width) #This method returns a left aligned string of length width. >>> width = 20 >>> print 'HackerRank'.ljust(width,'-') #HackerRank---------- #.center(width) #This method returns a centered string of length width. >>> width = 20 >>> print 'HackerRank'.center(width,'-') #-----HackerRank----- #.rjust(width) #This method returns a right aligned string of length width. >>> width = 20 >>> print 'HackerRank'.rjust(width,'-') #----------HackerRank ------------------------------------------------------------------------------------------------------------------
true
f29e0615a7790a56857053198e4f822d9ff2b01a
aymannc/LeetCode
/print_immutable_linked_list_in_reverse.py
663
4.25
4
""" Print out an immutable singly linked list in reverse in linear time (O(n)) and less than linear space (space<(O(n)) for example : Given the linked list : 4-5-12-1-3 Your program should print : 3-1-12-5-4 """ from LinkedList import ListNode class Solution: @staticmethod def print_linked_list(head: ListNode) -> None: if head is None: return Solution.print_linked_list(head.next) print(head.val, end=' -> ') linked_list = ListNode(4) linked_list.add(ListNode(5)) linked_list.add(ListNode(12)) linked_list.add(ListNode(1)) linked_list.add(ListNode(3)) print(linked_list) Solution.print_linked_list(linked_list)
true
9a1ad0e4584a94747fdac910cd54fe9d1d2887c3
BardisRenos/Project-Euler
/Problem1.py
1,085
4.28125
4
# Multiples of 3 and 5 # Problem 1 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. class Problem1: def multipleOf(self, num): if(type(num) is str): return False if(num < 1): return False else: listOfSum = [] for i in range(1, num): if(i%3 == 0 or i%5 == 0): listOfSum.append(i) return sum(listOfSum) #Unit testing import unittest class test_Problem1(unittest.TestCase): def test_values(self): #Test of the given value A = Problem1() self.assertFalse(A.multipleOf("10")) def test_zero_or_negative_value(self): #Test if the given value is zero or negative A = Problem1() self.assertFalse(A.multipleOf(0)) def test_result(self): A = Problem1() self.assertEqual(A.multipleOf(10), 23) if __name__ == "__main__": unittest.main()
true
1139e4155ad1993250b155aafc256ca9bda1734f
Rupakray2001/Python-
/30th Assignment_copyVSdirect assignment delVSclear and Reverse list.py
1,296
4.46875
4
''' copy - It copies and creates a seperate object altogether. The example shows that the out of this would be "[4, 3, 2, 1, 1, 2, 3, 4]". Where due to the "reverse" function the only the original list is getting reversed whereas the copied object is not getting reversed ''' a=[1,2,3,4] b=a.copy() e=a.reverse() print(a+b) ''' Direct assignment = just simply creates a referance to the origianl list. That is when the reverse function is used it reverse both the orginal list and the referenced list ''' c=[1,2,3,4] d=c f=c.reverse() print(c+d) #_______________________________________________________________________________ #difference between del and clear # Del = can be used with list, it deletes the specified index g = ["apple", "banana", "cherry","mango"] del g[1] print(g) print(type(g)) # Clear = it would clear the whole data e={1,2,3,4,5,6,7,8} f=e g=e.clear() print(g) print(e) # Clear = can be used with list h={1,2,3,4,5,6,7,8} i=h.copy() print(type(i)) j=h.clear() print(i) print(j) k = ["apple", "banana", "cherry","mango"] l=k.clear() print(l) #_____________________________________________________________________________ #how to reverse the list m = ["apple", "banana", "cherry","mango"] n=m[::-1] print(n)
true
e0dd6d63457eae0591768bc0bf3b670e780cfd25
VasilyRum/Hometask_from_Lessons
/Lesson VI - Exc, Iter and Gen/task_6_3.py
1,059
4.34375
4
""" Есть два списка разной длины, в одном ключи, в другом значения. Составить словарь. Для ключей, для которых нет значений использовать None в качестве значения. Значения, для которых нет ключей игнорировать. """ def get_dictionary(lst1, lst2): """ :param lst1: list number one :param lst2: list number two :return: dictionary: keys from list one, values from list two For keys that have no values, use None as the value. Values for which there are no keys to ignore. """ dictionary = {} value_list = iter(lst2) for i in lst1: try: value = next(value_list) dictionary.update({i: value}) except StopIteration: dictionary.update({i: None}) return dictionary print(get_dictionary([1, 2, 3, 4], [5, 8])) print(get_dictionary([1, 2, 3, 4], [5, 6, 7, 8, 9]))
false
84ce9f3172211f1c72f78fcd750f1ff4a72a6a3a
ahsan1201/hackerrank-30-days-of-code
/Day9.py
819
4.375
4
# Recursion # Factorial question def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return x * factorial(x-1) num = 3 print("The factorial of", num, "is", factorial(num)) # ------------------------------------------ # Hacker Rank accepted # import math # import os # import random # import re # import sys # Complete the factorial function below. # def factorial(n): # if n == 1: # return 1 # else: # return (n * factorial(n - 1)) # # # if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') # # n = int(input()) # # result = factorial(n) # # fptr.write(str(result) + '\n') # # fptr.close()
true
4325e36bdc2315e9af30fdfe68ba5c96bbccf70e
Reikenzan/Some-Python
/SomeWork/guessRandNum.py
970
4.21875
4
""" pick a random num from (1-100) & ask the user to guess. tell if guess is too high or low.""" # generates random number and stores it in num import random ans = "y" #loop until user doesn't want to play while ans =="y" or ans =="yes": num = random.randrange(1,101) guess = 0 #initialize guess to be 0(a wrong answer) #loop until user guesses num: while guess != num: #-ask user to guess and store in var guess guess = int(input("Enter your guess:")) #-check if guess is too high or too low & if correct, congratulates if guess > num: print("Your guess is too high") elif guess < num: print("Your guess is too low") else: print("Congratulations! You guessed my number.") # game has ended. Ask if want to play again ans = str(input("Do you want to play again(Y/N)")) #end of loop. print("Thanks for playing")
true
024d8ab8cdfbe2694749bf36d2dbb667137639b3
Reikenzan/Some-Python
/Labs/TicTacToeLab2.py
2,900
4.25
4
from turtle import * def setUp(): #Set up the screen and turtle win = Screen() tic = Turtle() tic.speed(10) #Change the coordinates to make it easier to tranlate moves to screen coordinates: win.setworldcoordinates(-0.5,-0.5,3.5, 3.5) #Draw the vertical bars of the game board: for i in range(1,3): tic.up() tic.goto(0,i) tic.down() tic.forward(3) #Draw the horizontal bars of the game board: tic.left(90) #Point the turtle in the right direction before drawing for i in range(1,3): tic.up() tic.goto(i,0) tic.down() tic.forward(3) tic.up() #Don't need to draw any more lines, so, keep pen up #Set up board: board = [["","",""],["","",""],["","",""]] return(win,tic,board) def playGame(tic,board): #Ask the user for the first 8 moves, alternating between the players X and O: for i in range(4): x = int(input("Enter x coordinates for X's move: ")) y = int(input("Enter y coordinates for X's move: ")) tic.goto(x+.25,y+.25) tic.write("X",font=('Arial', 90, 'normal')) board[x][y] = "X" x = int(input("Enter x coordinates for O's move: ")) y = int(input("Enter y coordinates for O's move: ")) tic.goto(x+.25,y+.25) tic.write("O",font=('Arial', 90, 'normal')) board[x][y] = "O" # The ninth move: x = int(input("Enter x coordinates for X's move: ")) y = int(input("Enter y coordinates for X's move: ")) tic.goto(x+.25,y+.25) tic.write("X",font=('Arial', 90, 'normal')) board[x][y] = "X" def checkWinner(board): for x in range(3): if board[x][0] != "" and (board[x][0] == board[x][1] == board[x][2]): return(board[x][0]) #we have a non-empty row that's identical for y in range(3): if board[0][y] != "" and (board[0][y] == board[1][y] == board[2][y]): return(board[0][y]) #we have a non-empty column that's identical if board[0][0] != "" and (board[0][0] == board[1][1] == board[2][2]): return(board[0][0]) if board[2][0] != "" and (board[2][0] == board[1][1] == board[2][0]): return(board[2][0]) return("No winner") def cleanUp(tic,win): #Display an ending message: tic.goto(-0.25,-0.25) tic.write("Thank you for playing!",font=('Arial', 20, 'normal')) win.exitonclick()#Closes the graphics window when mouse is clicked def main(): win,tic,board = setUp() #Set up the window and game board playGame(tic,board) #Ask the user for the moves and display print("\nThe winner is", checkWinner(board)) #Check for winner cleanUp(tic,win) #Display end message and close window main()
true
2458c49ae67119be9c6b235c1d12de2032521efb
Reikenzan/Some-Python
/SomeWork/test2.py
400
4.1875
4
import random import * #imports random library numSides = int(input("How many sides for the dice? ")) numTimes = int(input("How many times roll the dice? ")) for i in range(numTimes): #print(random.random()*50+50)#instuction to generate a random decimal num. # between 0 included print(randrange(1,numSides+1)) #range generates an int between 1 and 6
true
3a447e71c88764c2ebb39881baad4eecf1f32429
Reikenzan/Some-Python
/Labs/DrawingFromFileLab.py
2,397
4.3125
4
"""Drawing From File Lab Katherine St. John, Spring 2015 Introductory Programming, Lehman College, CUNY Read colors from a file and display using turtle graphics """ from turtle import * """ Welcome messages for the program""" def welcome(): print("This program prints pixelated pictures") print("stored as lists of colors in text files.") print() """ Sets up the screen with the origin in upper left corner """ def setUpScreen(xMax,yMax): win = Screen() win.setworldcoordinates(-0.5, yMax+0.5,xMax+0.5,-0.5) return win """ Draws a grid to the graphics window""" def drawGrid(xMax,yMax): tic = Turtle() tic.speed(100) #Draw the vertical bars of the game board: for i in range(0,xMax+1): tic.up() tic.goto(0,i) tic.down() tic.forward(yMax) #Draw the horizontal bars of the game board: tic.left(90) #Point the turtle in the right direction before drawing for i in range(0,yMax+1): tic.up() tic.goto(i,0) tic.down() tic.forward(xMax) """ Fills in the square (x,y) with color""" def fillSquare(x,y,color): t = Turtle() t.hideturtle() #Hides cursor and speeds up drawing t.speed(10) t.up() t.goto(x,y) t.fillcolor(color) t.begin_fill() for i in range(4): t.forward(1) t.left(90) t.end_fill() """ Ask user for input file and return the file handler, lines, height and width""" def getData(): fname = input('Enter file name: ') infile = open(fname, "r") lines = infile.readlines() infile.close() height = len(lines) width = lines[0].count(" ")+1 print(height, width) return lines, height, width """Draws the colors to the graphics window:""" def drawColors(lines): #For each row in the file: for row in range(len(lines)): #Break the row into pieces (stripping off any trailing newlines or spaces) cells = lines[row].rstrip().split(" ") #For each entry, fill in with the specified color: for column in range(len(cells)): fillSquare(column,row,cells[column]) def main(): welcome() lines, m, n = getData() win = setUpScreen(m,n) drawGrid(m,n) drawColors(lines) win.exitonclick() #Close window when mouse is clicked main()
true
0078302a7a81f12f899aa69a4bb79406b7f5ecde
Reikenzan/Some-Python
/HomeWork/hw27.py
550
4.40625
4
"""Write a program that implements the following pseudocode. This code asks the user for 10 numbers and prints out the largest number entered. 1. Ask the user for a number and store it as maxSoFar 2. Repeat 9 times: 3. Ask the user for a number and store it as num 4. if num > maxSoFar: 5. replace the old value in maxSoFar by num 6. print out that the largest number entered is maxSoFar""" for i in range(10): num = input("Enter a number:") if num > maxSoFar: print("The largest number entered is", +".")
true
a047437685653bdc6e7c46b82f289e4d464c5fa6
Reikenzan/Some-Python
/SomeWork/reviewWhileLoop.py
524
4.34375
4
"""1.) ask user for a number until they hit enter without entering a number(empty) 2.) at the end tell user the sum of all entered numbers""" # ask for num num = input("Enter a number (hit enter to stop): ") #initialize accumulator var total = 0 while num != "":#whil is not empty #add user's number to accumulaotr total = total + int(num) #ask for another number num = input("Enter a number (hit enter to stop): ") print("All done! The sum of all entered numbers:",str(total))
true
c7ecd79f0c7880e9632e6249252c7bdf240624e6
Reikenzan/Some-Python
/HomeWork/hw42.py
545
4.5625
5
"""Write a program that asks the user for the name of a text file, and then prints to the screen the first character of each line in that file. If the line is blank, print an empty line. Hint: First get your program to pass Tests 1 and 2, which do not have blank lines in the file. Then add in the code to handle blank lines for Test 3.""" file = input("Enter a file name:") fileref = open(file,'r') print("The first letters fo the lines in your file are:") for line in fileref: print(line[0].upper()) fileref.close()
true
e452cc02370b98e8834fe1e4af3d3c7a75c26c0d
Reikenzan/Some-Python
/SomeWork/S15/v4-Q_10.py
1,592
4.375
4
"""(a) Write a complete class that keeps tracks of information about chocolate. Your class, Chocolate should contain instance variables for the name, pricePerPound, weight and countryOfOrigin, and should have a constructor method as well as a method, cost(), that returns the price (pricePerPound * weight) for the chocolate and a method, getWeight(), that returns theweight for the chocolate. (b)Write a function that takes as input a list of chocolate, called shoppingList, and returns the most expensive chocolate in the list (i.e. the maximum of all the costs of the chocolate in the inputted list): def maxWeight(shoppingList): """ # (a) class Chocolate: # constructor def __init__(self, initName,initPrice,initWeight,initCountry): self.name = initName self.weight = initWeight self.price = initPrice self.countryOfOrigin = initCountry # getter def getWeight(self): return self.weight def cost(self): return self.price * self.weight def __str__(self): return self.name + ", $" + str(self.cost()) # (b) def maxCost(shoppingList): mostExpensiveSoFar = shoppingList[0] for choc in shoppingList: if choc.cost() > mostExpensiveSoFar.cost(): mostExpensiveSoFar = choc #print(choc.cost()) return mostExpensiveSoFar choc1 = Chocolate("Choc1",0.5,2,"Peru") choc2 = Chocolate("Choc2",0.1,5,"Columbia") choc3 = Chocolate("Choc3",1,1,"Ecuador") chocList = [choc1,choc2,choc3] print(maxCost(chocList))
true
7192d480633186bddfffc9c4a513b3c088ca0fe0
gunjan-madan/Python-Solution
/Module5/2.2.py
2,556
4.96875
5
# In one of your previous lessons, you have written a program called "Guess the number" game by pre assigning the number to be guessed. # Now imagine if you could get the computer to generate a random number, and then you could use that for the guessing game. # Python provides a built-in module that you can use to generate random numbers. # Let's take a look. '''Task 1: It's all Random''' print("***** Task 1: *****") print() # Uncomment the statements below and click Run import random num=int(input("Guess a number between 0 and 10: ")) if num==random.randrange(0, 11): print("You guessed the right number") else: print("Sorry! Better luck next time") # We have imported the module random and have used the function random.randrange(0, 11) to generate a number between 0 and 11. # Here the function randrange() returns a number between 0 (included) and 11 (not included) '''Task 2: Password Generator''' print("***** Task 2: *****") print() # The random module can also return a random element from a given string. # Uncomment the statements below, click Run and observe the output #y="python" #val=random.choice(y) #print(val) # Run the program 3 to 4 times and see the output changing. # choice() shuffles the character in the string and returns random character each time. # The choice() function can be used in applications that require a random password to be generated. # Ready to write a program that generates a random password. Part of the program is written for you.. # Uncomment the statements, complete the program and click Run, to execute the program import random password="" x="welcome" y="CODING" z="123456" for i in range(3): p=random.choice(x) l=random.choice(y) t=random.choice(z) passw=passw+p+l+t print("The password generated is :",passw) '''Task 3: Football pitch''' print("***** Task 3: *****") print() # Your friend wants to create a football pitch. # Write a program that generates a random number between 10m and 15m. This number will be used as the radius to find the area and circumference. # The area and circumference value will be used to create a football pitch. # Hint: Area of circle = 3.14*radius*radius # Perimeter of a circle= 2*3.14*radius import random num=random.randrange(10, 16) print("The radius of the football pitch is: ",num) area=3.14*num*num peri=2*3.14*num print("The area of the football pitch is ",area) print("The perim eter of the football pitch is ",peri) '''Fantastic!! You are getting better with working with the “random” package/module . Way to go!!'''
true
1261a031937c307935f9bc1bca4f5b319435f1d2
gunjan-madan/Python-Solution
/Module3/2.1.py
2,170
4.40625
4
#while loop along with if conditions # Have you been to a game arcade? # Which of the games are your favourite? # Are you ready to design one? ''' Task 1: Number Buzzer Game''' print("**** Task 1: ****") print() # Write a “Guess the Number” game, where a player has to guess a number between 10 and 20. Let's assume that the number to guess is 15. # Let's add some checks to the game, you have written: # If the number is lesser than 10, you must give a warning message and ask them to guess again # If the number is greater than 20, you must give a warning message for the same and ask them to guess again # If the number is right, then you display a congratulatory message num=int(input("Guess a number between 10 and 20: ")) while(num!=15): if num<10: print("Number is lesser than 10") num=int(input("Guess a number between 10 and 20: ")) elif num>20: print("Number is greater than 20") num=int(input("Guess a number between 10 and 20: ")) else: print("Try again!!") num=int(input("Guess a number between 10 and 20: ")) print("Bingo!! You guessed right") ''' Task 2: Break the loop''' print("**** Task 2: ****") print() # Now let's bring in a twist in the program you wrote in Task 1. # You need to modify the program, in a way that it allows only 3 chances to guess the number. ctr=1 while(ctr<=3): num=int(input("Guess a number between 10 and 20: ")) if num<10: print("Number is lesser than 10") elif num>20: print("Number is greater than 20") elif num==15: print("Bingo!! You guessed right!") break else: print("Try again!!") ctr=ctr+1 ''' Task 3: To quit or not to quit''' print("**** Task 3: ****") print() # Write a program that takes numbers between 1 and 100 from the user. # To quit entering numbers the user needs to press 0. # The program should then display the sum and the product of the numbers. print("**** Task 3: ****") num=1 tot=0 prod=1 while(num!=0): num=int(input("Enter a number (To quit press 0: )")) if num < 0 or num > 100: print("Enter a number between 1 and 100") elif num==0: break else: tot=tot+num prod=prod*num print("Sum: ",tot) print("Prod:",prod)
true
c75d7f94f3b93fd83a02c7defdf2d23138905bf4
gunjan-madan/Python-Solution
/Module6/1.4.py
1,673
4.59375
5
'''Task1: Global vs Local Variables''' print("***** Task 1: *****") print() #Global variables are the ones that are defined and declared outside any function and are not specified to any function. They can be used by any part of the program. #Local variables are specific to a particular function # This function has a variable with # name same as s. # def f(): # s = "Me too." # print(s) # # Global scope # s = "I love python" # f() # print(s) '''Task1: Global keyword''' print("***** Task 1: *****") print() # global keyword allows you to modify the variable outside of the current scope. # The basic rules for global keyword in Python are: # When we create a variable inside a function, it is local by default. # When we define a variable outside of a function, it is global by default. You don't have to use global keyword. # We use global keyword to read and write a global variable inside a function. # Use of global keyword outside a function has no effect. # def f(): # global s # #s="me too" # print(s) # # Global scope # s = "I love python" # f() # print(s) '''Task 2: Lets get global''' print("****** Task 2: ******") print() # Create a program that: # - Declares a global variable called balance, and assign a value to it # - Write a function that : # --> Takes an input value from the user and adds it to the balance. # --> Displays the updated balance value # - Use a for loop, to call the function thrice. balance=3000 def tot(val): global balance balance=balance+val return(balance) for i in range(3): num=int(input("Enter value to add to balance: ")) print("The updated balance is:",tot(num))
true
35a58a8e797843b6d2c1ce8381bd775859f53d8a
gunjan-madan/Python-Solution
/Module2/1.2.py
1,266
4.34375
4
#Lets Learn using multiple conditions """-----Task 1: What is your score? ---------""" print(" ") print("*** Task 1: ***") # Write a program to get the marks for Mathematics from the user. # If the marks is less than 50 or equal to 50, print a message saying “you need to improve”. # If the mark is between 50 and 80, print “ Let's work little more!” # If the mark is more than 80, print “ You are doing good. Keep it up!” mark1=float(input("Enter your Math score: ")) if(mark1 <= 50): print("you need to improve") elif mark1<=80: print("Lets work little more!") else: print("You are doing good. Keep it up!") """-----Task 2: Which sides are equal? ---------""" print(" ") print("*** Task 2: ***") #In this program we will take three sides of a triangle as input from user #Compare the sides to check if they are equal a=input("Enter the first side of the triangle: ") b=input("Enter the second side of the triangle: ") c=input("Enter the third side of the triangle: ") if a == b == c: print( "All sides are equal.") elif a == c: print("The first and third side are equal.") elif a == b: print("The first and second side are equal") elif b ==c: print("The second and third side are equal") else: print("None of the sides are equal")
true
85ab6795ad5dbf48f90a766aa91f2e4b94154e54
gunjan-madan/Python-Solution
/Module1/1.2.py
749
4.3125
4
"""-----------Task 1:Create a Simple Smiley---------------""" print(" ") print("*** Task 1: ***") print("^ ^") print(" - ") """------------Task 2: Create Another Smiley-------------""" print(" ") print("*** Task 2: ***") # Can you create another smiley """-------------Task 3: Make a Blank Face---------------""" print(" ") print("*** Task 3: ***") # Put on our creative hat!! # Create a blank face using just these three characters: @ - | # Hint: Use multiple print statements """-------------Task 4: Create a Goat Face---------------""" print(" ") print("*** Task 4: ***") # Now can you make an animal face using the special characters, say goat? # First two lines are done for you, uncomment them #print ("(\___/)" ) #print (" \* */ ")
true
defdfb0fa984c54b5de39c1176129377a9a3540c
gunjan-madan/Python-Solution
/Module1/5.2.py
690
4.1875
4
"""-----------Task 1: Lets Escape!! ---------------""" print(" ") print("*** Task 1: ***") print("Hello All!\nLets Learn Python") print("Hello All!\tLets Learn Python") #Write the following sentences into different lines using \n. #I love Computer Science. I am learning Python using Replit. Trying to print all the sentences in new lines. # Lets try. Uncomment the line below and click Run: #print("I am studying about \\n in the class") """-----------Task 2: What's in store? ---------------""" print(" ") print("*** Task 2: ***") #Let's take a look. Uncomment the statements below and click Run. #print(1+2) #print("1"+"2") #print("robin" +"hood") #print(2*2) #print(2*"hello")
true
5048c28e40e6ea53a137900268d63c3803630351
loweffort-alt/Cursos-programacion
/Curso de Python/numbers.py
1,594
4.25
4
#Hacemos las operaciones básicas # print(5+7) # print(8*2.4) # print(10/3) # print(5/9) # print(10//3, "= cociente") #Si queremos el cociente de una división # print(10%3, "= residuo") #Si queremos el residuo de una división # print("") # #Se respeta las reglas aritméticas # print(5+8*3/6) #Si hay una división, da un float # print(4*2+5) #No división = int # print("") # print("--------------------------------------------------------------------") #Para hacer formularios hacemos lo siguiente: #Sirve para tomar datos de entrada de la consola # name = input("Nombre:") # lastname = input("Apellidos:") # fullname = str(f"{name}"+f" {lastname}") # age = input("Edad:") # password = age+name+lastname # new_age = int(age) + 10 # posibility = [password] # print("La muerte de {} será dentro de 10 años, osea, cuando tenga {}".format(fullname,new_age)) # print("y sólo podrá salvarse si la contraseña es verdadera") # clave = input("Contraseña:") # if (f"{clave}" in posibility) == True: # print("You are alive, Congrats!") # else: # print("Haha you die >:)") #Otra manera de hacerlo name = input("Nombre:") lastname = input("Apellidos:") fullname = str(f"{name}"+f" {lastname}") age = input("Edad:") key = age+name+lastname new_age = int(age) + 10 print("La muerte de {} será dentro de 10 años, osea, cuando tenga {}".format(fullname,new_age)) print("y sólo podrá salvarse si la contraseña es verdadera") password = input("Contraseña:") if password == key: print("Congratulations brooOoOther!! you are alived") else: print("You don't deserved you life, DIE! >:)")
false
aea95033c7f84fbf4b62258940f56eb2f98f9a70
ponogo/Mad-libs
/main.py
960
4.375
4
name = input("hello what is your name? \n") print(f"hello {name}! lets start.") print() holiday = input("enter a name of a holiday: ") place = input("enter a place: ") #hero = input("enter a name of a hero:") outfit = input("what would you like to wear: ") #power = input("what superpowers would you like to have: ") animal = input("name an animal: ") celebrity = input("name a celebrity: ") object1 = input("name an object: ") celebrity2 = input("name a different celebrity: ") proffesion = input("name a proffession: ") print(f"Last {holiday} i was taking a trip to {place} and while walking I spotted {celebrity}. I then saw that he was holding a {animal}. I was shocked to see him with a {animal} I almost didn't even notice that {celebrity2} was trying to juggle an {object1} while wearing a {outfit}. I later found out that {celebrity} was holding that animal to prepare for his job as a {proffesion} and {celebrity2} was trying to join the circus.")
true
8655ec1746f6ac9aae85e9332454be2212f842f7
bitbybitsth/automation_login
/bitbybit/interview_assignments/string_assignments.py
2,801
4.28125
4
##################### reverse ########################333 # # x = "consolidate" # # # using slicing # reversed_x = x[::-1] # print(reversed_x) # # # using for loop # # y = "incorporate" # # reversed_y = "" # for item in y: # reversed_y = item + reversed_y # # # print(reversed_y) # # z = "india" # # # using recursive function or recursion def reverse_string(s): if len(s) == 0: return s else: return reverse_string(s[1:]) + s[0] # # reversed_z = reverse_string(z) # # print(reversed_z) # # # using stack # a = "inadequate" # # def using_stack(s): # stack = [] # for i in s: # stack.append(i) # # s = "" # for _ in range(0, len(stack)): # s += stack.pop() # # return s # # # reversed_a = using_stack(a) # print(reversed_a) # # # using reversed function # b = "Propoganda" # reversed_b = "".join(reversed(b)) # print(reversed_b) ################################ Palindrome ######################################3333 # x = input("enter you string") # if x==reverse_string(x): # print("String is pallindrome") # else: # print("string is not pallindorome") # # if x == x[::-1]: # print("String is pallindrome") # else: # print("string is not pallindorome") ################################################ anagarm ############################################## s1 = "wasp" s2 = "swip" # if sorted(s1) == sorted(s2): # print("they are anagram to each other") # else: # print("they are not anagram to each other") def check_anagram(s1, s2): if len(s1) != len(s2): return False else: for i in s1: if i not in s2: break else: return True return False if check_anagram(s1,s2): print("they are anagram to each other") else: print("they are not anagram to each other") # count no of vowels & consonants # x = input() # # vow_count = 0 # con_count = 0 # # for i in x: # if i.lower() in "aeiou": # vow_count +=1 # else: # con_count +=1 # # print(f"No of vowels in string are{vow_count}") # print(f"No of consonants in string are{con_count}") # # given string is digit or not # # x = input() # # y = x.replace(" ", "") # print(y) # # if y.isdigit(): # print("string is a digit string") # else: # print("string is not a digit string") # # # # display duplicate character # # # x = input() # duplicate = [] # x = x.lower() # # for i in x: # if x.count(i) > 1: # if i not in duplicate: # duplicate.append(i) # # print(duplicate) ## rotation string # pan npa # panpan # rotation ationrot # rotationrotation x = input("enter x") y = input("enter y") if y in x+x: print(f'{y} is a rotation string of {x}') else: print(f'{y} is not a rotation string of {x}')
false
978525aadba995f76c10aae78a118498870ae18a
cjwoodruff/Python_Tutorials
/classes/my_math.py
2,488
4.3125
4
class MyMath: def myAdd(num1, num2): """Add two numbers together (num1, num2)""" if isinstance(num1, str): try: num1 = float(num1) except ValueError: print('The first value needs to be a number.') return else: num1 = float(num1) if isinstance(num2, str): try: num2 = float(num2) return num1 + num2 except ValueError: print('The second value needs to be a number.') else: num2 = float(num2) return num1 + num2 def mySubtract(num1, num2): """Subtract num2 from num1""" if isinstance(num1, str): try: num1 = flaot(num1) except ValueError: print('The first value needs to be a number.') return else: num1 = float(num1) if isinstance(num2, str): try: num2 = float(num2) return num1 - num2 except ValueError: print('The second value needs to be a number.') else: num2 = float(num2) return num1 - num2 def myMultiply(num1, num2): """Multiply num1 by num2""" if isinstance(num1, str): try: num1 = float(num1) except ValueError: print('The first value needs to be a number.') return else: num1 = float(num1) if isinstance(num2, str): try: num2 = float(num2) return num1 * num2 except ValueError: print('The second value needs to be a number,') else: num2 = float(num2) return num1 * num2 def myDivide(num1, num2): """Divide num1 by num2""" if isinstance(num1, str): try: num1 = float(num1) except ValueError: print('This first value needs to be a number.') return else: num1 = float(num1) if isinstance(num2, str): try: num2 = float(num2) return num1 / num2 except ValueError: print('The second value needs to be number.') else: num2 = float(num2) return num1 / num2
true
2306f0fc4d9abfd6b0dfbef1e08dec8d9a7dd1cd
cjwoodruff/Python_Tutorials
/functions/first_function.py
685
4.34375
4
def myAdd(num1, num2): """The myAdd function takes two arguments (num1 and num2) and adds them together to create a new variable (arg_sum) which is returned to the user. The value needs to be printed outside of the function either by passing it to a new variable or wrapping it in the print() method.""" arg_sum = num1 + num2 return arg_sum # This could also be done with: return num1 + num2 # TESTING: # Call myFunc() and pass two numbers through it and then print # the total value. total = myAdd(3, 6) print(total) # This shows that we don't necessarily need to assign the value # to a variable. We can just print it out. print(myAdd(3, 6))
true
0c96bd8044417fe57d4a142355b0029677a00b08
bwelch21/technical-interview
/Graphs/MyQueue.py
1,066
4.28125
4
# FIFO implementation of a queue class Queue(object): struct = None size = None first_item = None def __init__(self): self.struct = [] self.size = 0 self.first_item = None return def put(self, item): if self.size == 0: self.first_item = item self.struct.append(item) self.size += 1 return def put_list(self, li): if self.size == 0: self.first_item = li[0] for item in li: self.put(item) return def get(self): if self.isEmpty(): raise IndexError("No items in Queue") else: returned_item = self.struct[0] self.struct = self.struct[1:] self.size -= 1 return returned_item def peek(self): if self.isEmpty(): return None else: return self.struct[0] def isEmpty(self): return self.size == 0 def empty(): self.struct = [] self.size = 0 self.first_item = None if __name__ == "__main__": q = Queue() print "Is queue empty: ", q.isEmpty() for i in range(5): q.put(i) print "First item is: ", q.peek() print "Removed first item: ", q.get() print "Size of queue: ", q.size
true
b9a2d3240506c49c98a82c0e9c24aa565f0f340f
judeaugustinej/python-work-book
/argparse/positional_args.py
1,617
4.625
5
"""Simple example using argparser """ import argparse def squareFunc(num): return num ** 2 def add(a,b): return a + b if __name__ == "__main__": parser = argparse.ArgumentParser() #created a parser called parser. parser.add_argument("num1",help="Enter a valid interger",type = int) #we add an argument called number of type interger parser.add_argument("num2",help="Enter the second number",type = int) args = parser.parse_args() #The argument are stored in args print("The square of the first number {}".format(squareFunc(args.num1))) print("The sum of {0} and {1} is {2}".format(args.num1,args.num2,add(args.num1,args.num2))) #--Output--- """ -sh-3.2$ python3 basic_args.py -h usage: basic_args.py [-h] num1 num2 positional arguments: num1 Enter a valid interger num2 Enter the second number optional arguments: -h, --help show this help message and exit -sh-3.2$ -sh-3.2$ -sh-3.2$ python3 basic_args.py --help usage: basic_args.py [-h] num1 num2 positional arguments: num1 Enter a valid interger num2 Enter the second number optional arguments: -h, --help show this help message and exit -sh-3.2$ -sh-3.2$ -sh-3.2$ python3 basic_args.py 4 5 The square of the first number 16 The sum of 4 and 5 is 9 -sh-3.2$ -sh-3.2$ -sh-3.2$ python3 basic_args.py 4 usage: basic_args.py [-h] num1 num2 basic_args.py: error: the following arguments are required: num2 -sh-3.2$ -sh-3.2$ -sh-3.2$ python3 basic_args.py usage: basic_args.py [-h] num1 num2 basic_args.py: error: the following arguments are required: num1, num2 -sh-3.2$ -sh-3.2$ """
true
2f4b4637f106001f2c94a6a61c73a92ec1901fc4
judeaugustinej/python-work-book
/Magic-Methods/how_to_getattr.py
1,522
4.25
4
""" __getattr__(self,name) This method only gets called when a nonexistent attribute is accessed. This can be useful for catching and redirecting common misspellings, giving warnings about using deprecated attributes. """ #Without Subclassing __getattr__() class A(object): def __init__(self): self.a = 42 if __name__ == "__main__": obj = A() print(obj.x) #---Output--- """ -sh-3.2$ python3 without_getattr.py Traceback (most recent call last): File "without_getattr.py", line 9, in <module> print(obj.x) AttributeError: 'A' object has no attribute 'x' """ #With __getattr__() class A(object): def __init__(self): self.a = 42 def __getattr__(self, attr): if attr in ["b", "c"]: return 42 raise AttributeError("%r object has no attribute %r" % (self.__class__, attr)) if __name__ == "__main__": a =A() print(a.a) print(a.x) #---Output--- """ -sh-3.2$ python3 myget1.py 42 Traceback (most recent call last): File "myget1.py", line 16, in <module> print(a.x) File "myget1.py", line 9, in __getattr__ (self.__class__, attr)) AttributeError: <class '__main__.A'> object has no attribute 'x' """ #use the dict's key with MyClass instance to access the dict class MyClass(object): def __init__(self): self.data = {'a': 'v1', 'b': 'v2'} def __getattr__(self, attr): return self.data[attr] if __name__ == "__main__": obj = MyClass() print(obj.a) #'v1' print(obj.b) #'v2'
true
3b214c0af9003e1f9918438af38b940274b29c8c
judeaugustinej/python-work-book
/Dictionary/how_to_defaultdict.py
1,536
4.375
4
"""Simple usuage of defaultdict,setdefault #----defaultdict----- """ defaultdict is used to create a multi-valued dictionary Eg. d = { 'a' : [1, 2, 3], 'b' : [4, 5] } e = { 'a' : {1, 2, 3}, 'b' : {4, 5} } Now the value can be stored at each value as a list or set. Use a list if you want to preserve the insertion order of the items. Use a set if you want to eliminate duplicates (and don’t care about the order). """ >>> from collections import defaultdict >>> >>> pairs = [('a',5),('a',67),('b',45),('b',7),('c',3),('d',0)] >>> >>> >>> for key,value in pairs: ... d[key].append(value) ... >>> d defaultdict(<class 'list'>, {'d': [0], 'a': [5, 67], 'c': [3], 'b': [45, 7]}) >>>#let print the key value of dictionary d{} >>> >>> for k,v in d.items(): ... print(k,v) ... d [0] a [5, 67] c [3] b [45, 7] >>> >>>#using sets for defaultdict >>> >>> dset = defaultdict(set) >>> dset['a'].add(1) >>> dset['a'].add(11) >>> dset['a'].add(111) >>> >>> dset['b'].add(2222) >>> >>> dset['c'].add(123) >>> dset['c'].add(321) >>> >>> #key value of dset{} ... >>> for k,v in dset.items(): ... print(k,v) ... a {1, 11, 111} c {321, 123} b {2222} >>> #----setdefault---- >>> help(dict.setdefault) Help on method_descriptor: setdefault(...) D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D >>> >>> pairs = [('a',1),('a',11),('a',111),('b',22),('b',213),('c',232)] >>> >>> for key,value in pairs: ... dum.setdefault(key,[]).append(value) >>> >>> >>> dum {'a': [1, 2, 1, 11, 111], 'b': [111, 22, 213], 'c': [232]} >>>
true
b2df6b77738b169adc8e199b47955a6a11289abf
000x100000000000/Python
/Basic string operations/sentence_capitalizer.py
471
4.1875
4
# Date: 26-09-2019 # Developer: WenLong Wu # Python programming practice # Sentence Capitalizer # This program accepts a string as an argument and returns a copy of the # string with the first character of each sentence capitalized. def sentence_cap(the_sentence): new_sentence = the_sentence.split('.') for n in new_sentence: print(n.capitalize(), end = '.') def main(): sentence = input("Enter the string: ") sentence_cap(sentence) main()
true
5ef4b24fbda479a752ec2bb0de5668c7c0240e5c
KimNguyenMai/Udacity-DS-Algo
/P0-Project1/Task4.py
1,662
4.125
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ i = 0 def FindTele(record): temp = set() #create empty set for elem in record: if elem[i][:3] == "140" and elem[i] not in temp: #look for num starts with 140 in first colum, temp.add(elem[i]) # if that num not in temp, add the num to temp if elem[i+1][:3] == "140": #look for num starts with 140 in second column, if elem[i+1] in temp: #if that num already in temp, remove the num from temp temp.remove(elem[i+1]) else: #else, if that num not in temp, add the num to temp temp.add(elem[i]) return temp Call = FindTele(calls) #look for all nums with 140 area code in calls Text = FindTele(texts) #look for all nums with 140 area code in texts Telemarketers = '\n'.join(Call.difference(Text)) #get the numbers only show up in Call set, added a line break between each num. print("These numbers could be telemarketers: ", "\n", Telemarketers)
true
7aa07d3a86334565e802a2dd812ee6b29388e69e
ceb10n/project-euler
/python/01.py
883
4.15625
4
# -*- coding: utf-8 -*- """Project Euler #1: Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Project Euler: https://projecteuler.net/problem=1 Hackerrank: https://www.hackerrank.com/contests/projecteuler/challenges/euler001/problem """ def sum_multiples_of_3_or_5(number: int): return \ 3 * (((number // 3) * ((number // 3) + 1)) // 2) + \ 5 * (((number // 5) * ((number // 5) + 1)) // 2) - \ 15 * (((number // 15) * ((number // 15) + 1)) // 2) if __name__ == "__main__": t = int(input().strip()) numbers = [] for _ in range(t): n = int(input().strip()) numbers.append(sum_multiples_of_3_or_5(n - 1)) for number in numbers: print(number, end="\n")
true
8969f76f4f8c429d5d4c3b7f6b212bd354d91896
dynamoh/Interview-solved
/LeetCode/832.py
1,566
4.53125
5
""" Flipping an Image Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. Example: Input: [[1,1,0],[1,0,1],[0,0,0]] Output: [[1,0,0],[0,1,0],[1,1,1]] Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] """ class Solution(object): def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ result = [] for i in range(len(A)): temp = [] for j in A[i][::-1]: if j == 0: temp.append(1) else: temp.append(0) result.append(temp) return result def flip1(self, A): return [[row[j]^1 for j in range(len(row)-1, -1, -1)] for row in A] s = Solution() _input = [[1,1,0],[1,0,1],[0,0,0]] final = [[1,0,0],[0,1,0],[1,1,1]] output1 = s.flipAndInvertImage(_input) output2 = s.flip1(_input) import unittest class TestArray(unittest.TestCase): def test_array1(self): self.assertEqual(final, output1) def test_array2(self): self.assertEqual(final, output2) if __name__ == '__main__': unittest.main()
true
c3cefa8f5316b3b0f058e1d8ef9087ec9f04d625
OnyisoChris/Python
/Loops/range.py
412
4.46875
4
#enter the following codes in python console #range(5) #range(0, 5) #list(range(5)) #[0, 1, 2, 3, 4] #for var in list(range(5)): #print (var) #......END........ for letter in 'Python': #traversal of a string sequence print ('Current Letter :', letter) print() fruits = ['banana', 'apple', 'mango'] for fruit in fruits: #traversal of list sequence print ('Current fruit :', fruit) print("Good bye!")
true
c394a761953a87742de7137bca5c64207fd82d35
farazn019/School-Work
/Programming-For-Beginners/lab4sol.py
931
4.21875
4
#Created By Faraz Naseem..... 110009274..... October 09, 2019. #The list and all it's contents is created. list1 = [['Rose', 'Daisy'], 7, 0, 5.5, [1, 22, 2.45, 3, 6, 5.8]] #The list is printed. print("list1 = " + str(list1)) #The length of the list is calculated and printed. length_list = len(list1) print("list1 has, " + str(length_list) + " items.") #The first letter of the first string in the list is output to the console. print("The first letter of the list is, " + str(list1[0][0][0])) #The sum of the last 4 integers is calculated and output. sum_integers = list1[4][-4]+ list1[4][-3] + list1[4][-2] + list1[4][-1] print("The sum of the last 4 integers in the list is, " + str(sum_integers)) #The list is expanded by appending: apple , pear , and grape. list1.append(['apple', 'pear', 'grape']) #The updated list is printed out. print("The updated list (list1) is, " + str(list1)) #f2200d07-c5f3-4020-984a-3feb13b6d9eb
true
197fc32835ab094247271a1fe3e8bbefe3298778
yqsy/algo_test
/quick_sort/quick_sort.py
2,538
4.15625
4
# 思路: # 1. 将范围内数组分割成两个部分,左边部分比中间数字小,右边部分比中间数字大 # 中间数字的位置不能固定了 # 2. 分治 # reference: # https://pythonschool.net/data-structures-algorithms/quicksort/ import unittest class TestPartition(unittest.TestCase): def test_1(self): array = [9, 8, 7, 6, 0, 4, 3, 2, 1, 5] mid_idx = partition(array, 0, len(array) - 1) for i in array[0:mid_idx]: self.assertTrue(array[i] <= array[mid_idx]) def test_2(self): array = [9, 8, 7, 6, 0, 4, 3, 2, 1, 5] mid_idx = partition(array, 0, len(array) - 1) for i in array[mid_idx + 1:len(array)]: self.assertTrue(array[i] > mid_idx) class TestQuicksort(unittest.TestCase): def test_1(self): array = [9, 8, 7, 6, 0, 4, 3, 2, 1, 5] quciksort(array, 0, len(array) - 1) self.assertEqual(array, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) def test_2(self): array = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] quciksort(array, 0, len(array) - 1) self.assertEqual(array, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) def test_3(self): array = [3, 2, 1] quciksort(array, 0, len(array) - 1) self.assertEqual(array, [1, 2, 3]) def test_4(self): array = [3] quciksort(array, 0, len(array) - 1) self.assertEqual(array, [3]) def test_5(self): array = [] quciksort(array, 0, len(array) - 1) self.assertEqual(array, []) def quciksort(A, L, R): if L < R: m = partition(A, L, R) quciksort(A, L, m - 1) quciksort(A, m + 1, R) return A def partition(A, L, R): pivot = A[L] left = L + 1 right = R done = False while left <= right: while left <= right and A[left] <= pivot: left = left + 1 while left <= right and A[right] >= pivot: right = right - 1 if left <= right: A[left], A[right] = A[right], A[left] A[L], A[right] = A[right], A[L] return right # def partition(A, L, R): # pivot = A[R] # left = L # right = R - 1 # while left <= right: # while left <= right and A[left] <= pivot: # left = left + 1 # # while left <= right and A[right] >= pivot: # right = right - 1 # # if left <= right: # A[left], A[right] = A[right], A[left] # # A[R], A[left] = A[left], A[R] # return left if __name__ == '__main__': unittest.main()
false
f7c06c1877bdba5307e798f50a68847eef3fb164
adityaruplaha/adityaruplaha-school-projects
/CS Practical/C4.py
216
4.375
4
# Check if angles for a triangle print("Enter 3 angles:") a = float(input()) b = float(input()) c = float(input()) if a+b+c == 180: print("They form a triangle.") else: print("They don't form a triangle.")
true
dc41d99534ee989546b94902d8a93116080532f7
Youngsu-Heo/python-test
/1-chapters/06-slice-vs-stride.py
655
4.15625
4
a = ['a', 'b','c','d','e','f','g','h'] # Test deep copy print('\nd is shallow copy of a. so, both d and a reference the same address') d = a print(d == a, d is a) d = a[:] print(d == a, d is a) # Test slice print('\nb and c are new instances respectively, but each elements in them are shallow copys of a') b = a[:3] c = a[:3] print(b) print(c) print(b == c, b is c) print(b[0] is a[0], b[1] is a[1], b[2] is a[2]) print(b[0] is c[0], b[1] is c[1], b[2] is c[2]) # Test stride print('\ntest stride') x = a[::2] y = a[::2] print(x) print(x==y, x is y) print(x[0] is a[0], x[1] is a[2], x[2] is a[4]) print(x[0] is y[0], x[1] is y[1], x[2] is y[2])
false
93de87bdf110f67ad684d091732a9a44f3e3894f
jpieczar/FlaskPractice
/Class/1pyclass.py
971
4.15625
4
class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = (first.lower() + '.' + last.lower() + "@company.com") def fullname(self): # 'self' is used to work with all instances. return "{} {}".format(self.first, self.last) emp_1 = Employee("Jonathan", "Pieczara", 60000) emp_2 = Employee("Test", "McTest", 60000) print(emp_1.fullname()) # The brackets are so that the methods runs. print(Employee.fullname(emp_2)) # Another way of doing this. # print("{} {}".format(emp_1.first, emp_1.last)) # This is used if there are no methods. # emp_1 = Employee() # Instance of a class. # emp_2 = Employee() ### This method is prone to mistakes and ### is time consuming... # emp_1.first = "Jonathan" # emp_1.last = "Pieczara" # emp_1.email = "jonathan.pieczar@company.com" # emp_1.pay = "60000" # emp_2.first = "Test" # emp_2.last = "McTest" # emp_2.email = "test.mctest@company.com" # emp_2.pay = "60000"
true
fe2df71330ea68a6d90b2ba985787a71399be937
NickMad88/PythonAssignments
/Multi_Sum_Avg.py
495
4.21875
4
# Multiples - Part I - Print all odds from 1-1000 for i in range(1, 1000, 2): print i #Multiples - Part II - Prints all multiples of 5 from 5 to 1,000,000 for i in range(5, 1000000): if i % 5 == 0: print i # Sum List - Prints the sum of all values in the list a = [1, 2, 5, 10, 255, 3] sum = 0 for i in a: sum += i print sum #Average List - Prints the aerage of the values in the list a = [1, 2, 5, 10, 255, 3] sum = 0 for i in a: sum += i avg = sum / len(a) print avg
true
3cac2c66adfd056ac451dd156f54bf7e7f9a8e47
nikhilkuria/workbooks
/fundamentals/closures.py
846
4.21875
4
""" Python closures takes in a variable in the outer scope and retains the binding to it. todo : better documentation """ def sequence_generator(seed_num=1, num_of_terms=10): def sequence(): """ Note that seed_num and num_of_terms comes in from the Enclosing scope """ print('-'*100) print(f"Building {num_of_terms} sequence for {seed_num}") for index in range(1, num_of_terms+1): print(seed_num*index) print('-'*100) return sequence three_sequence = sequence_generator(3, 10) three_sequence() three_sequence = sequence_generator(5, 5) three_sequence() # magic property __closure__ print("__closure__ property is None for global functions : ", sequence_generator.__closure__) print("__closure__ property shows closure variables : ", three_sequence.__closure__)
true
f60359a638a787bbfaf42ea47e90e2a1772c67af
Pruebas2DAMK/PruebasSGE
/py/P711JSD.py
775
4.125
4
''' Joel Sempere Durá - Ejercicio 11 -------------------------------- Escribir un programa que almacene el diccionario con los créditos de las asignaturas de un curso {'Matemáticas': 6, 'Física': 4, 'Química': 5} y después muestre por pantalla los créditos de cada asignatura en el formato <asignatura> tiene <créditos> créditos, donde <asignatura> es cada una de las asignaturas del curso, y <créditos> son sus créditos. Al final debe mostrar también el número total de créditos del curso. ''' dictCurso = { 'Matemáticas': 6, 'Física': 4, 'Química': 5, } totalCreditos=0 for clave,valor in dictCurso.items(): totalCreditos+=valor print(clave+" tiene "+str(valor)+" creditos") print("-----------------------\nCreditos totales -> "+str(totalCreditos))
false
05a16981fffb501b5b09502f8b55f7438ab5eaa9
i50918547/270201034
/lab3/example2.py
325
4.15625
4
num1 = int(input("Write a number: ")) num2 = int(input("Write a number: ")) num3 = int(input("Write a number: ")) if num1<num2: if num1<num3: print("Minimum:" , num1) else: print("Minimum:" , num3) else: if num1 < num3: print("Minimum:" , num2) else: print("Minimum:" , num3)
false
4909aa3bf49a78481d4ae5a59275d6dd5e74aecf
wanghan79/2020_Python
/韩正鹏2018012694/第三次作业-生成器实现随机数生成筛选/RanNumbyGenerator.py
1,537
4.1875
4
##!/usr/bin/python3 """ Author: ZhengPeng.Han Purpose: Generate random data set. Created: 28/5/2020 """ import random import string def dataSampling(datatype, datarange, num, strlen=8): ''' :Description:Using the generator generates a random data given set of conditions :param datatype: The type of data which include int float and string :param datarange: iterable data set :param num: Input parameters that means The final result of the number of elements :param strlen:The length of input strings :return: a dataset ''' try: if (datatype is int): for i in range(num): it = iter(datarange) item = random.randint(next(it), next(it)) yield item #使用yield关键字以实现生成器 elif (datatype is str): for i in range(num): item = ''.join(random.SystemRandom().choice(datarange) for _ in range(strlen)) yield item #使用yield关键字以实现生成器 elif (datatype is float): for i in range(num): it = iter(datarange) item = random.uniform(next(it), next(it)) yield item #使用yield关键字以实现生成器 except ValueError: print("传入参数无效") except TypeError: print("类型错误,参数可能无法迭代") except Exception as e: print(e) a=dataSampling(int, (0,100), 5) b=set() for i in range(5): b.add(next(a)) print("生成:"+b)
true
35073dd6c611b925bb912468f368400d412c46d9
wanghan79/2020_Python
/周铭辉2018013134/第一次作业随机数生成和筛选.py
2,764
4.34375
4
""" 姓名: 周铭辉 学号:2018013134 项目实践第一次作业 函数封装随机数生成和筛选 """ import random import string ######################################################################################################################## def dataSampling(datatype,datarange,num,strlen=8): try: result=set() if datatype is int: while len(result)<num: it=iter(datarange) item=random.randint(next(it),next(it)) result.add(item) elif datatype is float: while len(result)<num: it=iter(datarange) item=random.uniform(next(it),next(it)) result.add(item) elif datatype is str: while len(result)<num: item=''.join(random.SystemRandom().choice(datarange) for _ in range(strlen)) result.add(item) except ValueError: print("Error: 参数无效") except TypeError: print("Error: 类型错误,无法迭代") except NameError: print("Error: 初始化参数名称") else: return result finally: print("随机生成结果:") ######################################################################################################################## def dataScreening(data, *args): try: result = set() for i in data: if type(i) is int: it = iter(args) if next(it)<=i and next(it)>=i: result.add(i) elif type(i) is float: it = iter(args) if next(it)<=i and next(it)>=i: result.add(i) elif type(i) is str: for Screening_str in args: if Screening_str in i: result.add(i) except ValueError: print("Error: 参数无效") except TypeError: print("Error: 类型错误,无法迭代") except NameError: print("Error: 初始化参数名称") else: return result finally: print("筛选生成结果:") ######################################################################################################################## def apply(): result_int = dataSampling(int, [0,122], 20) print(result_int) int_Screening = dataScreening(result_int,7,22) print(int_Screening) result_float = dataSampling(float, [0, 122], 20) print(result_float) float_Screening = dataScreening(result_float,7,22) print(float_Screening) result_str = dataSampling(str,string.ascii_letters,20) print(result_str) str_Screening = dataScreening(result_str,'a') print(str_Screening) apply()
false
52ad3a45618068e05a2a581cd4db181a5bae49b1
wanghan79/2020_Python
/周铭辉2018013134/第二次作业 修饰器修改作业一.py
1,978
4.34375
4
""" 姓名: 周铭辉 学号:2018013134 项目实践第二次作业 将作业一中的随机数生成封装为修饰函数,用于修饰随机数筛选函数进行数据筛选 """ import random import string ######################################################################################################################## def dataSampling(func): def wrapper(datatype,datarange,num,*args,strlen=8): result=set() if datatype is int: while len(result)<num: it=iter(datarange) item=random.randint(next(it),next(it)) result.add(item) elif datatype is float: while len(result)<num: it=iter(datarange) item=random.uniform(next(it),next(it)) result.add(item) elif datatype is str: while len(result)<num: item=''.join(random.SystemRandom().choice(datarange) for _ in range(strlen)) result.add(item) print('随机生成的数据:', result) return func(result,*args) return wrapper @dataSampling def dataScreening(data,*args): result = set() for i in data: if type(i) is int: it = iter(args) if next(it)<=i and next(it)>=i: result.add(i) elif type(i) is float: it = iter(args) if next(it)<=i and next(it)>=i: result.add(i) elif type(i) is str: for Screening_str in args: if Screening_str in i: result.add(i) print('筛选后的数据: ', result) return result ######################################################################################################################## dataScreening(int,[1,122],20,7,22) dataScreening(float,[1,122],20,7,22) dataScreening(str,string.ascii_letters,20,'a')
false
c4c1e685cd3df4510d4cb7aaf84dfca2df11bd9a
matheusschuetz/TrabalhoPython
/ExerciciosAula18/exercicio1.py
1,884
4.40625
4
# Aula 18 - 03-11-2019 # Exercicios para lista simples # Dada a seguinte lista, resolva os seguintes questões: lista = [10, 20, 'amor', 'abacaxi', 80, 'Abioluz', 'Cachorro grande é de arrasar'] print('1: Usando a indexação, escreva na tela a palavra abacaxi') print(lista[3]) # exemplo print(lista[3]) print('2: Usando a indexação, escreva na tela os seguintes dados: 20, amor, abacaxi') print(lista[1:4]) print('3: Usando a indexação, escreva na tela uma lista com dados de 20 até Abioluz') print(lista[1:6]) print('4: Usando a indexação, escreva na tela uma lista com os seguintes dados:' '\nCachorro grande é de arrasar, Abioluz, 80, abacaxi, amor, 20, 10') print(lista[::-1]) print('5: Usando o f-string e a indexação escreva na tela os seguintes dados:' '\n { abacaxi } é muito bom, sinto muito { amor } quando eu chupo { 80 }" deles.') print(f'{lista[3]} é muito bom, sinto muito {lista[2]} quando eu chupo {lista[4]} deles') print('6: Usando a indexação, escreva na tela os seguintes dados:' '\n10, amor, 80, Cachorro grande é de arrasar') print(lista[0::2]) print('7: Usando o f-string e a indexação escreva na tela os seguintes dados:' 'Abioluz - abacaxi - 10 - Cachorro grande é de arrasar - 20 - 80' ) print(f'{lista[5]} - {lista[3]} - {lista[0]} - {lista[-1]} - {lista[1]} - {lista[4]}') print('8: Usando o f-string e a indexação escreva na tela os seguintes dados:' '\namor - 10 - 10 - abacaxi - Cachorro grande é de arrasar - Abioluz - 10 - 20') print(f'{lista[2]} - {lista[0]} - {lista[0]} - {lista[3]} - {lista[-1]} - {lista[5]} - {lista[0]} - {lista[1]} ') print('9: Usando a indexação, escreva na tela uma lista com dados de 10 até 80') print(lista[:5]) print('10: Usando a indexação, escreva na tela os seguintes dados:' '\n10, abacaxi, Cachorro grande é de arrasar') print(lista[::3])
false
8b4b7d5c1ace8e8d9ad2053e92c35c1bfd93f0a2
jailandrade/jailandrade
/learning/challenges/ex1/ex1.py
288
4.21875
4
# -*- coding: utf-8 -*- def multiplesOf(number): multiplys = [] i = 1 while i < number: if i % 3 == 0 or i % 5 == 0: multiplys.append(i) i += 1 return sum(multiplys) def sum(multiplys): suma = 0 for d in multiplys: suma = suma + d return suma print multiplesOf(10)
false
e7258aa9b3b6d41a7f04d79071a02145a700ad27
winter-qiu/data-analysis
/1. Import Data/read_local_file.py
1,949
4.28125
4
# Python has in-built functions to create and manipulate files. No need to import. ############################################################################## # Read a txt file # Import an file object my_file = open("myLocalFile.txt", mode="a+", encoding="utf-8") #Character: Function # Useful ones #r: Open file for reading only. Starts reading from beginning of file. #w: Open file for writing only. #a: Open a file for appending. Starts writing at the end of file. # Less useful ones #r+: Open file for reading and writing. #w+: Same as 'w' but also alows to read from file. #wb+: Same as 'wb' but also alows to read from file. #a+: Same a 'a' but also open for reading. #ab+: Same a 'ab' but also open for reading. # Read the whole file file_content = my_file.read() # Read the each line of the object for line in my_file: print(line) # or line1 = my_file.readline() line2 = my_file.readline() # Close the file object my_file.close() ############################################################################## # Read a csv file import csv input_file = "myLocalFile.csv" # read csv into a list of list with open(input_file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for line in csv_reader: # line is a list print(line) # read csv into a list of dictionary with open(input_file, mode='r', encoding='utf-8-sig') as csv_file: csv_reader = csv.DictReader(csv_file) for line in csv_reader: # line is a OrderedDict, and we just conver it to regular dict print(dict(line)) # read csv into a pandas DataFrame import pandas as pd df = pd.read_csv(input_file) ############################################################################## # Read a JSON file import json input_file = "json_file.json" # regular JSON format with open(input_file,"r") as f: jsondata=json.load(f) # NJSON format for line in open(input_file): line = eval(line)
true
04beef38130477892c487b9eb2ee12186a38b50a
jclemite/MyFirstScripts
/unsolved_TerminalLibrary.py
1,109
4.4375
4
# Create an application that will ask the user for the name of a text file. import os askUser = input("Which file are you looking for? ") # Then checks to see if the file exists in the Books folder. real_path = os.path.join("Books", "Dracula.txt", "Frankenstein.txt", "PrideAndPrejudice.txt") # If the text file exists, then print the text inside of the file to the terminal. #DracFrankPAP = open(real_path) filePath = os.path.join("Books", askUser + ".txt") if os.path.isfile(filePath): #create a connection to the file bookFile = open(filePath) #read in the text that the file contains bookText = bookFile.read() #Print contents to terminal print(bookText) # If the text file does not exist, then print "Sorry! That book is not in our records! Please try again!" else : print("Sorry! That book is not in our records! Please try again!") # Hint: When the user enters the file name, keep in mind that they will not use a file extension (.txt). # Therefore, when you’re creating your file path, remember that you’ll need to have the file extension added to that user input.
true
223eae96ff6159bcdee2210fc3efcac1d08e2078
drewmullen/personal
/training/python-training/hangman.py
2,332
4.125
4
import random def setup(): # setups the foundation of the game, selects a random word from a list # and instantiates variables word_list = ['one','two','three', 'teest'] #select random word from word_list, set to lowercase, and add it as a list secret_word = [] secret_word = list(word_list[random.randint(0,(len(word_list)-1))].lower()) #build progress tracking list with _s correct_guesses = [] correct_guesses.extend('_' * len(secret_word)) game(secret_word, correct_guesses) def prompt(): # prompts user for input and makes sure its only 1 character guess = input("Enter a guess: ").lower() if len(guess) != 1: print("One character only, please!") return None else: return guess def compare_prompt(secret_word, guess, correct_guesses): # compares guessed letter to all letters in secret_word. when it finds a match it # updates the correct_guesses list and increments the found counter. # prints the found counter, letting the user know if (and how many) occurences they found counter = 0 found = 0 for letter in secret_word: if guess == letter: # counter trackers the index of the letter being compared, used to # record the occurnce in correct_guesses correct_guesses[counter] = guess found +=1 counter +=1 if found > 0: print("You got {}!".format(found)) else: print("None of those, try again!") #print(guess) def output_status(correct_guesses): #output progress tracking list print(*correct_guesses) def game(secret_word, correct_guesses): # main function that controls flow of game and monitors for a win # counter tracks the amount of guesses and reports to user at the end counter=0 while correct_guesses!= secret_word: output_status(correct_guesses) guess = prompt() if guess == None: guess = prompt() compare_prompt(secret_word, guess, correct_guesses) counter+=1 print("You won! It took you {} guesses.".format(counter)) output_status(correct_guesses) play_again() def play_again(): play_again = input("\nDo you want to play again? Y/n ") if play_again != 'n': setup() else: exit() setup()
true
478483a2aa58a20df335db70cd33e38e4d1623f6
parasgarg-smms/Intermediate-Practice-Problems
/chocolates.py
2,247
4.125
4
''' There are 2 types of chocolates in Chocoland denoted by A and B. The cholates are lined up in a queue.You want to satisfy your friends by distributing some number of non-empty contiguous chocolates such that the ratio of number of type A chocolates to number of type B chocolates is same for all the friends.You have to distribute all the chocolates and satisfy maximum number of friends. Therefore you have to find the maximum number of friends that can be satisfied. Input Format The first line of input contains the number of test cases T . Each test case starts with one line containing an integer N which is the length of the description of a queue. Each of the following N lines consists of an integer K and one of the characters A or B, meaning that K characters of the given type (A or B) follow next in the queue. Output Format For each test case, output a single line containing the maximum number of friends that can be satisfied. For 1st Test Case: Queue is ABBBAA Distributions are AB, BBAA (Ratio 1:1) For 2nd Test Case: Queue is BBBBB Distributions are B, B, B, B, B (Ratio 0:1) ''' def abc(a, ratio): global RESULT for i in range(0, len(a)): if i == len(a) - 1: return 1 str1 = a[0:i] str2 = a[i:] temp1 = str1.count('A') temp2 = str1.count('B') if temp1 == 0 or temp2 == 0: continue if temp1 / temp2 == ratio: RESULT = RESULT + 1 return abc(str2, ratio) a = "AABBBABA" RESULT = 0 c = 0 if a.count('A') == 0: print(a.count('B')) elif a.count('B') == 0: print(a.count('A')) else: for i in range(0, len(a)): if i == len(a) - 1: print(1) exit() str1 = a[0:i] str2 = a[i:] temp1 = str1.count('A') temp2 = str1.count('B') temp3 = str2.count('A') temp4 = str2.count('B') if temp1 == 0 or temp2 == 0 or temp3 == 0 or temp4 == 0: continue if temp1 / temp2 == temp3 / temp4: ratio = temp1 / temp2 RESULT = RESULT + 1 c = abc(str2, ratio) print(RESULT + c) exit()
true
635b37a79c82bce2958b24984245a1f3dbf14b47
subash2617/Task-10
/Task 10.py
1,270
4.40625
4
#1.check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9) import re def char(string): charRe=re.compile(r'[^a-zA-Z0-9.]') string=charRe.search(string) return not bool(string) print("ABCabc123") print(char("ABCabc123")) print("*&%@#!") print(char("*&%@#!")) #2.matches a word containing 'ab' import re def text_match(text): if re.search('\w*ab.\w*',text): return 'matched' else: return('Not matched') str=input() print(text_match(str)) #3.check for a number at the end of a word/sentence def number_check(string): if re.search(r'\d+s',string): return 'yes' else: return 'no' str1=input() print(number_check(str1)) #4.search the number (0-9) of length between 1 to 3 in a given string import re result=re.finditer(r"([0-9]{1,3})", "Exercises number 1, 12, 13, and 345 are important") print("Number of length 1 to 3:") for n in result: print(n.group(0)) #5.match a string that contains only uppercase letters import re def text_match(text): pattern='^[A-Z]' if re.search(pattern,text): return 'matched' else: return 'Not matched' print(text_match("hello world")) print(text_match("Python"))
true
0ec922e967ec02540518cd711e128cbf848aedc9
conflabermits/Scripts
/python/edx/week1/pset1.py
843
4.34375
4
#!/usr/bin/env python3 import argparse parser = argparse.ArgumentParser(description="Find the longest alphabetical substring for a given string") parser.add_argument("-s", "--string", type=str, help="given string", required=True) args = parser.parse_args() s = args.string alpha_sorted = "abcdefghijklmnopqrstuvwxyz" sub_start = 0 sub_end = 1 longest_substring = "" result = s[0] while sub_end < len(s): if alpha_sorted.find(s[sub_end-1]) <= alpha_sorted.find(s[sub_end]): sub_end += 1 longest_substring = s[sub_start:sub_end] if len(longest_substring) > len(result): result = longest_substring else: sub_start = sub_end sub_end += 1 print("Longest substring in alphabetical order is:", result)
true
e5dcb0b1e11d1cf7a810264cffbabfa35986a087
conflabermits/Scripts
/python/de-noob-ify/13_looping-over-dict-keys.py
695
4.34375
4
#!/usr/bin/env python3 def for_key_in_dict_keys(): dict1 = {"a": 1, "b": 2, "c": 3} for key in dict1.keys(): print(f"dict1[{key}] has value {dict1[key]}.") def for_key_in_dict(): dict2 = {"d": 4, "e": 5, "f": 6} for key in dict2: print(f"dict2[{key}] has value {dict2[key]}.") def modify_dict_during_loop(): dict3 = {"g": 7, "h": 8, "i": 9} for key in list(dict3): print(f"Zeroing out key {key} in dict3, which was {dict3[key]}.") dict3[key] = 0 print(f"dict3[{key}] now has value {dict3[key]}.") def main(): for_key_in_dict_keys() for_key_in_dict() modify_dict_during_loop() if __name__ == '__main__': main()
false
ab0d40dd877ce491f8a7385e1f8a9a09f29a4492
mitchroy41/cti-110
/M4T1_BugCollector_RoyMitchell.py
600
4.4375
4
# A program that calculates input of bugs for seven days and displays total. # 6/16/2017 # CTI-110 M4T1 - Bug Collector # Roy Mitchell # Initialize the accumulator. total_bugs = 0 # Input the number of bugs for each day. for day in range(1, 8): # Prompt user to input bugs collected for the day. print('Enter the number of bugs collected on day', day) # Input the number of bugs. bugs = int(input()) # Add daily number to total. total_bugs = total_bugs + bugs # Display the total number of bugs collected. print('You have collected a total of', total_bugs, 'bugs.')
true
6a592b920c5f34d9675824e0fef91086ad7394bc
mitchroy41/cti-110
/M3T1_AreasOfRectangles_RoyMitchell.py
916
4.40625
4
# Compare rectangle areas # 6/16/2017 # CTI-110 M3T1 - Areas of Rectangles # Roy Mitchell # This program will determine which rectangle has the greatest area. # Get length and width of rectangle 1. length1 = int(input('What is the length of rectangle 1?: ')) width1 = int(input('What is the width of rectangle 1?: ')) # Get length and width of rectangle 2. length2 = int(input('What is the length of rectangle 2?: ')) width2 = int(input('What is the width of rectangle 2?: ')) # Calculate the area of rectangle 1. area1 = length1 * width1 # Calculate the area of rectangle 2. area2 = length2 * width2 # Determine which rectangle has the greatest area and display result. if area1 > area2: print('Rectangle 1 has the greatest area.') elif area1 < area2: print('Rectangle 2 has the greatest area.') else: print('Both rectangles have the same area.')
true
426d9fe3b71327e37b27d4e548645adf1c3e7dad
andypandy31/nccdm6-h22376-2019
/example1-discount/discount.py
952
4.375
4
# Program to work out a discount # Aurelien Ammeloot # 22 Feb 2019 # Create three main variables as floating-point price = 0.0 discount = 0.0 deduction = 0.0 # Input of the main price # We convert string to float # Example 1: in 2 steps price = input("Please enter a price: ") price = float(price) # Input validation: ensure price is positive while price < 0: print("Your value is invalid.") print("Ensure your price is over 0.") price = float(input("Enter new price: ")) # Example 2: nested function, all on one line discount = float(input("Please enter a discount 0-100: ")) # Input validation: ensure discount in 0 - 100 bracket while discount < 0 or discount > 100: print("Your value is invalid.") print("Ensure your discount is in the range 0 - 100") discount = float(input("Enter new discount: ")) # Do the maths deduction = price / 100 * discount price = price - deduction # Show the answer print("The new price is:", price)
true
96aafe8babfc08679b208e82051f53434f6bb851
pratikv06/Python-Crash-Course
/8_functions/1_function.py
1,098
4.4375
4
# def - use to define function in python # after def is the name of the function # finally defination end with colon(:) # any indented line that follow def fun_name(): make up the body of function # Definiting a function def greet_user(): """Display a simple freeting.""" print("Hello.") # calling a function greet_user() #Function accept parameter def greet_user2(name): # parameter """Display a Simple message""" print("Hello, "+ name.title() +"!") greet_user2("pratik") # argument """ NOTE: - descriptive names - only lowercase letters and underscores - module name should follow this convention - every function should have comment section, immediately after function defination - no space in default value while assigning value (EX. name='pratik') - if multiple parameter, start on new line and give two tab space def function_name( parameter_0, parameter_1, parameter_2, parameter_3, parameter_4, parameter_5): - give two new line gap between two function defination - if import in program, it should be the first line except comment """
true
f95acfd168835ecc128c70068cf2de90204b68e3
pratikv06/Python-Crash-Course
/4_working_with_lists/8_overridding_tuples.py
318
4.15625
4
# Although you can’t modify a tuple, you can assign a new value to a variable # that holds a tuple. dimensions = (200, 50) print("Original dimensions:") for dimension in dimensions: print(dimension) dimensions = (400, 100, 50) print("\nModified dimensions:") for dimension in dimensions: print(dimension)
true
64d059b2940b8b0ecd8a9bcb8affca64fe6132de
pratikv06/Python-Crash-Course
/10_files_and_exceptions/12_multiple_file.py
589
4.125
4
def word_counts(filename): try: with open(filename) as f: content = f.read() except FileNotFoundError: # print(f'Sorry, the file `{filename}` does not exist...') # don't want to display exception error pass else: # Count the approximate words used in file words = content.split() num_words = len(words) print(f'The file `{filename}` has about {num_words} words.') filenames = ['file1_pi_digit.txt', 'new_sample.txt', 'file2_pi_million_digits.txt', 'file.txt'] for f in filenames: word_counts(f)
true
dc600aa83a120471a358aaa4a74391612b12f731
pratikv06/Python-Crash-Course
/6_dictionaries/4_loop_through_dictionary.py
1,248
4.3125
4
fav_lang = { 'pratik': 'python', 'amit': 'java', 'anand': 'php', 'nilesh': 'oracle', 'vishal': 'go', 'jayesh': 'php', 'ajay': 'python' } print(">> Looping through key and value both:") for key, value in fav_lang.items(): print(key.title() +"'s favorite language is "+ value.title()) print("\n>> Looping through key:") friends = ['pratik', 'vishal'] for name in fav_lang.keys(): # default behaviour, so we can omit '.keys()' print(name.title()) if name in friends: print("Hi "+ name.title() +", I see your favorite language is "+ fav_lang[name].title()) print("\n> check if person is not in dictionary") if 'ratnesh' not in fav_lang.keys(): print("Ratnesh, please provide your favorite language!") print("\n> Let sort the dictonary by key") for name in sorted(fav_lang): # key is sorted temporary print(name.title() + ", Thank you for taking Poll!") print("\n>> Looping through value:") print(">List of all language in the list") for lang in fav_lang.values(): # values() function wull return only value from dictionary print("$ "+ lang.title()) print("> The list of language is not unique. let's make it unique") for lang in set(fav_lang.values()): print("$ "+ lang.title())
true
69d70f486a9a1b90244d67301dc49ccec9bf69de
pratikv06/Python-Crash-Course
/5_if_statements/2_if_else.py
869
4.3125
4
print(">> Example of If-else statement") age = 17 if age >= 18: print("You are old enough to vote!") print("have you registered to vote yet?") else: print("Sorry, you are too young to vote...") print("Please register to vote as soon as you turn 18!") print("\n>> Example of If-elif-else statement") age = 12 if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") else: print("Your admission cost is $10.") print("\n>> We can also make use of variable to store price and \n>> print at the end of the if-elif-else block") age = 69 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5 # $5 discount to senior citizen (above 65) print("Your admission cost is $"+ str(price) +".") # we can replace the else block with elif block for more surety of the output
true
8b2afc6ad6b1efa0e605e233935218758a9e37ef
pratikv06/Python-Crash-Course
/9_classes/2_working_with_classes_objects.py
1,709
4.375
4
class Car(): '''A simple attempt to represent a car''' def __init__(self, make, model, year): '''Initialize attribute''' self.make = make self.model = model self.year = year self.odometer_reading = 0 # Setting default value def get_descriptive_name(self): '''return formatted description''' long_name = str(self.year) +" "+ self.make +" "+ self.model return long_name.title() def read_odometer(self): '''Print car mileage''' print("This car has "+ str(self.odometer_reading) +" miles on it.") def update_odometer(self, mileage): '''Set the odometer value''' # Verify that the new is grater than the previous one # It cannot be roll back if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, mileage): '''adding mileage to odometer''' self.odometer_reading += mileage # Class End my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer() print("\n>> Updating odometer value to 50") my_new_car.update_odometer(50) my_new_car.read_odometer() print("\n>> Updating odometer value lower than previous value") my_new_car.update_odometer(25) # Assigning a lower value my_new_car.read_odometer() # This is also possible while updating a value, # but using a method is best practice # # SYNTAX: # my_new_car.odometer_reading = 100 # my_new_car.read_odometer() print("\n>> Incrementing odometer value by 150") my_new_car.increment_odometer(150) my_new_car.read_odometer()
true
3a3a26144ae59fbf7d530277fce248d0695b6f50
bibekbistey/LabProject
/Functions/four.py
375
4.15625
4
'''No.4 Write a function that returns the sum of multiples of 3 and 5 between 0 andlimit(parameter) . For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20''' def sums_of_multiples_of_3_and_5(limit): sum=0 for i in range(1,limit+1): if i%3==0 and i%5==0: sum+=1 print(sum) sums_of_multiples_of_3_and_5(20)
true
8899a59440641a8287731f5d83670b775a94b48a
bibekbistey/LabProject
/LabFour/Six.py
215
4.21875
4
'''6. Write a Python program to count the number of even and odd numbers from a series of numbers.''' for i in range(1,21): if i%2==0: print(f"{i} is even") elif i%2!=0: print(f"{i} is odd")
true
51c27f5fede2ffaab41dcd4937a556d12a207d24
bibekbistey/LabProject
/LabOne/One.py
317
4.3125
4
#write a program that takes three numbers and print their sum #Every number is given on a seperate line. num1=int(input("Enter Number 1:")) num2=int(input("Enter Number 2:")) num3=int(input("Enter Number 3:")) sum=num1+num2+num3 print("three numbers are:",num1,num2,num3) print(f"the sum of three number is:{sum}")
true
4735c88fdf6c3a2d46913b62bd221896e5c8b724
MynorCifuentes/ProgrammingForEverybody
/GettingStartedWithPython/HW2.py
705
4.3125
4
#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. hours = input("Enter Hours: ") rate = input("Enter rate: ") h = float(hours) r = float(rate) if h>40: rextra = float(rate)*1.5 extra = h-40 pextra = extra*rextra pay = pextra+40*r print(pay)
true
b1db8d3b72d09679393c168eced57bd12adc1e88
Mayankjh/Python_ML_Training
/Python Training/Day 4/TaskQ.py
669
4.125
4
usa = ["atlanta","new york","chicago","baltimore"] uk = ["london","bristol","cambridge"] india = ["mumbai","delhi","banglore"] a= input("Enter the city:") if a in uk : print("The city belongs to UK ") elif a in usa: print("The city belongs to USA ") elif a in india: print("The city belongs to India ") else: print("City is not in the list/Wrong Input") b= input("Enter the city 1:") c= input("Enter the city: 2") if b and c in uk : print("The city belongs to UK ") elif b and c in usa: print("The city belongs to USA ") elif b and c in india: print("The city belongs to India ") else: print("The Cities are not from the same country")
false
887fdc969f80b5d80b1b8776553cf611b2fd25c0
Mayankjh/Python_ML_Training
/Python Training/Day 2/membershipOp.py
505
4.15625
4
# Program to show use of in and not in operators a=10 b=20 list = [10,20,30,40,50] if(a in list): print('a is in list') else: print('a is not in given list') if(b not in list): print('b is not in list') else: print('b is in given list') # Program For Indentity Operator c=90 d=20 if (c is d): print('a, b have same identity') else: print('a,b are not identical') if ( b is not a): print('a and b have different identity') else: print('a, b have same identity')
true
22e081f5d2a9598f9ab573d6ff17a703233c2281
Mayankjh/Python_ML_Training
/Python Training/Day 9/sqllitedata.py
1,690
4.125
4
#database with python import sqlite3 as sq conn = sq.connect("courses.db") cursor = conn.cursor() cursor.execute("""CREATE TABLE if not exists courses( number INTEGER PRIMARY KEY, name text, ects real);""") # normal insertion #cursor.execute("""INSERT INTO courses VALUES("02820","Python programming",5);""") # inserstion through variable #courses = ("02345","NonLinear Signal IDk",12) #cursor.execute("INSERT INTO courses values(?,?,?);",courses) # many entries at once #courses = [("2323","introduction to cognitive Science",6),("2327","introduction to Python",3)] #cursor.executemany("INSERT INTO courses values(?,?,?);",courses) #conn.commit() #Fetch data from db #cursor.execute("SELECT * FROM courses;") #print(cursor.fetchone()) # Return one row at a time with fetch one #for row in cursor: # print(row) # Limiting no. of rows #cursor.execute("SELECT * FROM courses ORDER BY number LIMIT 2;") #print(cursor.fetchall()) # search for specific values # cursor.execute("Select * from courses where number=? or name=? or ects=?",("2327",12,6)) # rows = cursor.fetchall() # print(rows) #paramaterize search data into python variable # param ={'ects':10.0} # cursor.execute("SELECT number From courses WHERE ects=?",(param['ects'],)) # print(cursor.fetchall()) # Updating data in SQLlite # cursor.execute("update courses set name=?,ects=? where number=?",('MAX','99','2327')) # cursor.execute("SELECT * FROM courses;") # print(cursor.fetchall()) # deleting From database cursor.execute("DELETE FROM courses where number=?",("2345",)) conn.commit() cursor.execute("SELECT * FROM courses;") print(cursor.fetchall()) conn.close()
true
e0e7a657f21a92681dd5a061985bd454469759e1
Mayankjh/Python_ML_Training
/Python Training/Day 5/AssignQ1.py
258
4.21875
4
# program to find lcm of two numbers a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) if(a>b): min1=a else: min1=b while(1): if(min1%a==0 and min1%b==0): print("LCM is:",min1) break min1=min1+1
true
706f99e0a345762a7fa738e690c43c8b02ece22b
albastienex/TEST
/3-a.py
380
4.15625
4
a=int(input()) b=int(input()) c=int(input()) if a==b==c: print(3) elif a==b or b==c or a==c: print(2) else: print(0) #Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).
true
11273bfda40c3fb3b68805d5194897103dcaba83
albastienex/TEST
/test14.py
211
4.125
4
n=int(input()) i=1 while i*i<=n: print(i*i,end=' ') i+=1 # For a given integer N, # print all the squares of positive # integers where the square is less # than or equal to N, in ascending # order.
true
e861c10ffbd755ae683c7c3efb28d74a822eec39
jvanson/algorithims
/algodaily/majority_elements.py
1,189
4.21875
4
# Suppose we're given an array of numbers like the following: # [4, 2, 4] # Could you find the majority element? A majority is defined as "the greater part, # or more than half, of the total. It is a subset of a set consisting of more than half of the set's elements." # Let's assume that the array length is always at least one, and that there's always a majority element. # In the example above, the majority element would be 4. import math def find_majority(a): print(a) majority_threshold = math.floor(len(a) / 2) print('threshold', majority_threshold) counter = {} for i in range(0, len(a)): print(a[i]) temp = counter.get(a[i], 0) temp += 1 counter.update({a[i]: temp}) for key, value in counter.items(): if value > majority_threshold: print('majority:', key) return key return 'no majority' print(counter) # another way that is faster # sort the array and find the middle # if 0 to middle +1 are equal, then # it's the majority # [5,3,5,4,22,5,5] # sorted [3,4,5,5,5,5,22] result = find_majority([4, 2, 4, 2, 1, 1, 1, 1, 1]) 1,1,1,1,2,2 print(result) assert result == 1
true