blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d2de097ee33f0060830681df81f87f600f5da69c
Scott-Dixon-Dev-Team-Organization/cs-guided-project-linked-lists
/src/demonstration_3.py
804
4.1875
4
""" Given a non-empty, singly linked list with a reference to the head node, return a middle node of linked list. If there are two middle nodes, return the second middle node. Example 1: Input: [1,2,3,4,5] Output: Node 3 from this list The returned node has value 3. Note that we returned a `ListNode` object `ans`, such that: `ans.val` = 3, `ans.next.val` = 4, `ans.next.next.val` = 5, and `ans.next.next.next` = NULL. Example 2: Input: [1,2,3,4,5,6] Output: Node 4 from this list Since the list has two middle nodes with values 3 and 4, we return the second one. *Note: The number of nodes in the given list will be between 1 and 100.* """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def middleNode(self, head): # Your code here
true
00ead084fe729599aeedba61cc88fc277e7726ad
menezesluiz/MITx_-_edX
/week1/exercise/exercise-for.py
442
4.34375
4
""" Exercise: for Finger Exercises due Aug 5, 2020 20:30 -03 Completed Bookmark this page Exercise: for exercise 1 5.0/5.0 points (graded) ESTIMATED TIME TO COMPLETE: 5 minutes In this problem you'll be given a chance to practice writing some for loops. 1. Convert the following code into code that uses a for loop. prints 2 prints 4 prints 6 prints 8 prints 10 prints Goodbye! """ for i in range(2, 12, 2): print(i) print("Goodbye!")
true
36e8464800601f9fc4553aacc2f48369940393df
menezesluiz/MITx_-_edX
/week1/exercise/exercise04.py
2,056
4.40625
4
""" Exercise 4 Finger Exercises due Aug 5, 2020 20:30 -03 Completed Bookmark this page Exercise 4 5/5 points (graded) ESTIMATED TIME TO COMPLETE: 8 minutes Below are some short Python programs. For each program, answer the associated question. Try to answer the questions without running the code. Check your answers, then run the code for the ones you get wrong. This question is going to ask you what some simple loops print out. If you're asked what code like this prints: """ # Exemplo num = 5 if num > 2: print(num) num -= 1 print(num) # write what it prints out, separating what appears on a new line by a comma # and a space. So the answer for the above code would be: # Resposta: 5, 4 """ If a given loop will not terminate, write the phrase 'infinite loop' (no quotes) in the box. Recall that you can stop an infinite loop in your program by typing CTRL+c in the console. Note: What does +=, -=, *=, /= stand for? a += b is equivalent to a = a + b a -= b is equivalent to a = a - b a *= b is equivalent to a = a * b a /= b is equivalent to a = a / b """ # 1 num = 0 while num <= 5: print(num) num += 1 print("Outside of loop") print(num) # Minha resposta: # 0, 1, 2, 3, 4, 5, Outside of loop, 5 ou 6 # 2 numberOfLoops = 0 numberOfApples = 2 while numberOfLoops < 10: numberOfApples *= 2 numberOfApples += numberOfLoops numberOfLoops -= 1 print("Number of apples: " + str(numberOfApples)) # Minha resposta: # Infinite Loop # 3 num = 10 while True: if num < 7: print("Breaking out of loop") break print(num) num -= 1 print("Outside of loop") """ Note: If the command break is executed within a loop, it halts evaluation of the loop at that point and passes control to the next expression. Test some break statements inside different loops if you don't understand this concept! """ # Minha resposta: # Breaking out of loop, 10, 9, Outside Of loop # 5 num = 100 while not False: if num < 0: break print('num is: ' + str(num)) # Minha resposta: # Infinit loop
true
c142beb40fb5f0bf1527f2a5fc3172165d0d4d09
yonggyulee/gitpython
/02/07.operater_logical.py
744
4.3125
4
#일반적으로 피연산자(operand)는 True 또는 False 값을 가지는 연산 a = 20 print(not a < 20) print(a < 30 and a !=30) b = a > 1 # 다른 타입의 객체도 bool 타입으로 형변환이 가능하다 print(bool(10), bool(0)) print(bool(3.14), bool(0.)) print(bool('hello'), bool('')) print(bool([0,1]), bool([])) print(bool((0,1)), bool(())) print(bool({'k1':'v1', 'k2':'v2', 'k3':'v3'}), bool({})) print(bool(None)) # 논리식의 계산순서 t = True or bool('logical') print(t) print(True or 'logical') print(False or 'logical') print([] or 'logical') print([] and 'logical') print([0,1] or 'logical') def f(): print('hello world') a = 11 a > 10 or f() if a > 10: f() s1 = '' s = 'Hello World' s1 and print(s)
false
8d6d347432112c3884102402bf0c269bcbd2ab89
Preet2fun/Cisco_Devnet
/Python_OOP/encapsulation_privateMethod.py
1,073
4.4375
4
""" Encapsulation = Abstraction + data hiding encapsulation means we are only going to show required part and rest will keep as private """ class Data: __speed = 0 #private variable __name = '' def __init__(self): self.a = 123 self._b = 456 # protected self.__c = 789 # private self.__updatesoftware() self.__speed = 200 self.__name = "I10" def __updatesoftware(self): print("Updating software") def updatespeed(self,speed): self.__speed = speed def drive(self): print("Max speed of car is : " + str(self.__speed)) num = Data() """print(num.a, num._b, num.__c) --> we can not directly acces __C as it is define as private for class and no object of that class has access to it""" print(num.a, num._b, num._Data__c) #print(num.__updatesoftware) --> not able to access as its proivate method print(num.drive()) print(num._Data__speed) num.__speed = 300 print(num.drive()) num.updatespeed(300) print(num.drive())
true
cd9c959a5bc604f523799d07470931d281d79698
paulc1600/Python-Problem-Solving
/H11_staircase.py
1,391
4.53125
5
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: Consider a staircase of size n: # # # ## # ### # #### # # Observe that its base and height are both equal to n, and # the image is drawn using # symbols and spaces. The last # line is not preceded by any spaces. # # Write a program that prints a staircase of size n. # # Function Description # Complete the staircase function in the editor below. It # should print a staircase as described above. staircase has # the following parameter(s): # o n: an integer # # --------------------------------------------------------------------- # PPC | 08/26/2019 | Original code. # --------------------------------------------------------------------- import math import os import random import re import sys # Print a staircase where the image is drawn using # symbols and spaces. def staircase(MySteps): air_fill = ' ' for step in range(MySteps): step_len = step + 1 wood_step = step_len * '#' whole_step = wood_step.rjust(MySteps, air_fill) print(whole_step) if __name__ == '__main__': n = 15 result = staircase(n)
true
2cc6154799ccae67f873423a981c6688dc9fb2b5
paulc1600/Python-Problem-Solving
/H22_migratoryBirds_final.py
1,740
4.375
4
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: You have been asked to help study the population of birds # migrating across the continent. Each type of bird you are # interested in will be identified by an integer value. Each # time a particular kind of bird is spotted, its id number # will be added to your array of sightings. You would like # to be able to find out which type of bird is most common # given a list of sightings. Your task is to print the type # number of that bird and if two or more types of birds are # equally common, choose the type with the smallest ID # number. # --------------------------------------------------------------------- # PPC | 09/02/2019 | Original code. # --------------------------------------------------------------------- import math import os import random import re import sys # migration def migratoryBirds(myArr): migStats = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} maxBird = 0 maxCount = 0 for birdType in myArr: migStats[birdType] = migStats[birdType] + 1 if migStats[birdType] > maxCount: maxBird = birdType maxCount = migStats[birdType] elif migStats[birdType] == maxCount and birdType < maxBird: maxBird = birdType return maxBird if __name__ == '__main__': n = 6 # ar = [1, 4, 4, 4, 5, 3] # result = migratoryBirds(ar) ar = [1, 2, 3, 4, 5, 4, 3, 2, 1, 3, 4] result = migratoryBirds(ar) # ar = [5, 5, 2, 2, 1, 1] # result = migratoryBirds(ar) print(result)
true
e955679387cd90ad3e5dfbbff7f941478063823d
Hajaraabibi/s2t1
/main.py
1,395
4.1875
4
myName = input("What is your name? ") print("Hi " + myName + ", you have chosen to book a horse riding lesson, press enter to continue") input("") print("please answer the following 2 questions to ensure that you will be prepared on the day of your lesson.") input("") QuestionOne = None while QuestionOne not in ("yes" , "no"): QuestionOne = str(input("have you got your own helmet? ")) if QuestionOne == "yes": print("great!") elif QuestionOne == "no": input("To rent a riding hat, you will have to pay a fee of £4 every lesson. Are you size small, medium or large? ") print("thank you") else: print("please enter yes or no") input("") QuestionTwo = None while QuestionTwo not in ("yes" , "no"): QuestionTwo = str(input("have you got your own riding shoes? ")) if QuestionTwo == "yes": print("great!") elif QuestionTwo == "no": print("To rent riding shoes, you will have to pay a fee of £5 every lesson.") else: print("please enter yes or no") input("") print("SUMMARY: For riding hat you chose: " + QuestionOne + " for riding shoes you chose: " + QuestionTwo + ".") Payment = input("To continue to payment, please type 'yes': ") if Payment == "yes": print("Thank you!") else: print("you have chosen not to go ahead with payment. see you again next time!")
true
a3b8127727aab91acb49a0c57c81aa5bf8b7ea4a
atishay640/python_core
/comparison_oprators.py
363
4.28125
4
# Comparison operators in python # == , != , > , < >= ,<= a= 21 b= 30 c= a print(a==b) print(c==a) print(a>=b) print(a<=b) print(a<b) print('------------------------------------') # Chaining comparison operators in python # 'and' , 'or' , and 'not' print(a == b and b == c) print(a == b or a == c) print(not a == 21) print(True and True ) print(not False)
false
fd7715910c9fee1405c6599869252b112b098520
atishay640/python_core
/dictionary.py
891
4.4375
4
# Dictionary in python # It is an unordered collection # Used 'key'-'value' pairs to store values. # it is identified with {} print("**********dictionary in python") students_dic = {1 : 'Atishay' ,2 : 'Vikas' ,3 : 'Aakash' } print(students_dic) print("**********fetch value in python") print(students_dic[2]) print("**********nested list in dictionary in python") students_dic[4] = ['107 Simran sun' , 'indore' ,'mp'] print(students_dic) print("********** fetch nested list element in dictionary in python") print(students_dic[4][1]) print("********** modify nested list element in dictionary in python") students_dic[4][2] = 'M.P.' print(students_dic[4][2]) print("********** dictionary methods in python") print("********** keys()") print(students_dic.keys()) print("********** values()") print(students_dic.values()) print("********** items()") print(students_dic.items())
false
2599892f0d1edf3a23907bad202b1d1b0f10328f
atishay640/python_core
/polymorphism.py
922
4.15625
4
# Inheritance in python class Person: def __init__(self,name,mob_no,address): self.name = name self.mob_no = mob_no self.address = address def eat(self): print('I eat food') class Employee(Person): def __init__(self,name,mob_no,address,company_name): Person.__init__(self,name,mob_no,address) self.company_name = company_name def eat(self): print('I eat healthy and lit food') class Student(Person): def __init__(self,name,mob_no,address,school): Person.__init__(self,name,mob_no,address) self.school = school def eat(self): print('I eat spicy and junk food') person = Person("Atishay Sharma" , 8899779988 , 'Indore') student = Student("Rahul Rai",4565656665 , "Indore",school='NDPS') employee = Employee("Priyanka" , 898989889 ,"Mhow", company_name='GWL') for human in [person,student,employee]: human.eat()
false
0d0892bf443e39c3c5ef078f2cb846370b7852e9
JakobLybarger/Graph-Pathfinding-Algorithms
/dijkstras.py
1,297
4.15625
4
import math import heapq def dijkstras(graph, start): distances = {} # Dictionary to keep track of the shortest distance to each vertex in the graph # The distance to each vertex is not known so we will just assume each vertex is infinitely far away for vertex in graph: distances[vertex] = math.inf distances[start] = 0 # Distance from the first point to the first point is 0 vertices_to_explore = [(0, start)] # Continue while heap is not empty while vertices_to_explore: distance, vertex = heapq.heappop(vertices_to_explore) # Pop the minimum distance vertex off of the heap for neighbor, e_weight in graph[vertex]: new_distance = distance + e_weight # If the new distance is less than the current distance set the current distance as new distance if new_distance < distances[neighbor]: distances[neighbor] = new_distance heapq.heappush(vertices_to_explore, (new_distance, neighbor)) return distances # The dictionary of minimum distances from start to each vertex graph = { 'A': [('B', 10), ('C', 3)], 'C': [('D', 2)], 'D': [('E', 10)], 'E': [('A', 7)], 'B': [('C', 3), ('D', 2)] } print(dijkstras(graph, "A"))
true
b9bb7deb73be996ec847225a3c10f9f8c063b7c8
jglantonio/learning_python
/curso001/03_strings.py
562
4.375
4
#!/usr/bin/env python3 # Strings y funciones para trabajar con ellos variable = "Tengo un conejo "; print(variable); variable2 = "llamado POL"; print(variable2); print(variable + variable2); print(variable*2); # function len length_variable = len(variable); print("La variable "+variable+", tiene ",length_variable); # primera letra del string print(variable[0]); # Poner todas las letras en capital. variable3 = variable+variable2; print(variable3.title()); # islower(); son todo minusculas print(variable3.islower()); print((variable3.lower()).islower());
false
026526ddd9c38e990d966a0e3259edcb2c438807
arlionn/readit
/readit/utilities/filelist.py
1,003
4.21875
4
import glob from itertools import chain def filelist(root: str, recursive: bool = True) -> [str]: """ Defines a function used to retrieve all of the file paths matching a directory string expression. :param root: The root directory/file to begin looking for files that will be read. :param recursive: Indicates whether or not glob should search for the file name string recursively :return: Returns a list of strings containing fully specified file paths that will be consumed and combined. """ listoffiles = [ glob.glob(filenm, recursive=recursive) for filenm in root ] return unfold(listoffiles) def unfold(filepaths: [str]) -> [str]: """ Defines a function that is used to convert a list of lists into a single flattened list. :param filepaths: An object containing a list of lists of file paths that should be flattened into a single list. :return: A single list containing all of the file paths. """ return list(chain(*filepaths))
true
0d012a23dfd3e68024f560287226171040c2ca67
EthanReeceBarrett/CP1404Practicals
/prac_03/password_check.py
941
4.4375
4
"""Password check Program checks user input length and and print * password if valid, BUT with functions""" minimum_length = 3 def main(): password = get_password(minimum_length) convert_password(password) def convert_password(password): """converts password input to an equal length "*" output""" for char in password: print("*", end="") def get_password(minimum_length): """takes a users input and checks that it is greater than the minimum length if not, repeats till valid then returns the password""" valid = False while not valid: password = input("Please enter password greater than 3 characters long: ") password_count = 0 for char in password: password_count += 1 if password_count <= minimum_length: print("invalid password") else: print("valid password") valid = True return password main()
true
262d7b72a9b8c8715c1169b9385dd1017cb2632b
EthanReeceBarrett/CP1404Practicals
/prac_06/programming_language.py
800
4.25
4
"""Intermediate Exercise 1, making a simple class.""" class ProgrammingLanguage: """class to store the information of a programing language.""" def __init__(self, field="", typing="", reflection="", year=""): """initialise a programming language instance.""" self.field = field self.typing = typing self.reflection = reflection self.year = year def __str__(self): """returns output for printing""" return "{}, {} typing, reflection = {}, First appeared in 1991".format(self.field, self.typing, self.reflection, self.year) def is_dynamic(self): if self.typing == "Dynamic": return True else: return False
true
8aa1cf81834abd2a7cb368ffdb9510ae7f0039e4
nobleoxford/Simulation1
/testbubblesort.py
1,315
4.46875
4
# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test above arr1 = [64, 34, 25, 12, 22, 11, 90] arr2 = [64, 34, 25, 12, 22, 11] arr3 = [-64, 34, 25] arr4 = [] bubbleSort(arr1) bubbleSort(arr2) bubbleSort(arr3) bubbleSort(arr4) print ("Sorted array1 is:") print(arr1) print ("Sorted array2 is:") print(arr2) print ("Sorted array3 is:") print(arr3) print ("Sorted array4 is:") print(arr4) cards = ['5♣', '8♠', '4♠', '9♣', 'K♣', '6♣', '5♥', '3♣', '8♥', 'A♥', 'K♥', 'K♦', '10♣', 'Q♣', '7♦', 'Q♦', 'K♠', 'Q♠', 'J♣', '5♦', '9♥', '6♦', '2♣', '7♠', '10♠', '5♠', '4♣', '8♣', '9♠', '6♥', '9♦', '3♥', '3♠', '6♠', '2♥', '10♦', '10♥', 'A♠', 'A♣', 'J♥', '7♣', '4♥', '2♦', '3♦', '2♠', 'Q♥', 'A♦', '7♥', '8♦', 'J♠', 'J♦', '4♦'] bubbleSort(cards) print("Sorted cards:" ) print(cards)
true
b29b3de7434393fca62ea01898df1015e7a8871f
iamkarantalwar/tkinter
/GUI Sixth/canvas.py
1,080
4.21875
4
#tkinter program to make screen a the center of window from tkinter import * class Main: def __init__(self): self.tk = Tk() #these are the window height and width height = self.tk.winfo_screenheight() width = self.tk.winfo_screenwidth() #we find out the center co ordinates y = (height - 600)//2 x = (width - 600)//2 #place the window at the center co ordinate self.tk.geometry('600x600+'+str(x)+'+'+str(y)+'') #these lines of code are for placing picture as background self.can = Canvas(self.tk,height=600,width=600,bg="red") self.can.pack() self.img = PhotoImage(file='./images/obama.gif') self.can.create_image(0,0,image=self.img,anchor=NW) self.fr = Frame(self.tk,height=200,width=200) #we make resizable false to restrict user from resizing the window self.fr.place(x=200,y=200) self.tk.resizable(height=False,width=False) self.tk.mainloop() d = Main()
true
5765384a784ac51407757564c0cbafa06cedb83b
divyaprabha123/programming
/arrays/set matrix zeroes.py
1,059
4.125
4
'''Set Matrix Zeroes 1. Time complexity O(m * n) 2. Inplace ''' def setZeroes(matrix): """ Do not return anything, modify matrix in-place instead. """ #go through all the rows alone then is_col = False nrows = len(matrix) ncols = len(matrix[0]) for r in range(nrows): if matrix[r][0] == 0: is_col = True for c in range(1,ncols): if matrix[r][c] == 0: matrix[0][c] = 0 matrix[r][0] = 0 for r in range(1, nrows): for c in range(1, ncols): if not matrix[r][0] or not matrix[0][c]: matrix[r][c] = 0 if matrix[0][0] == 0: for c in range(ncols): matrix[0][c] = 0 if is_col: for r in range(nrows): matrix[r][0] = 0 return matrix
true
47040df315ac09b44047e645f8f988b5a1142342
falcoco/pythonstudy
/ex7.py
299
4.25
4
age = 7 if age >= 18: print 'your age is ',age print 'adult' #else: # print 'your age is ',age # print 'teenager' elif age >= 6: print 'your age is ',age print 'teenager' else: print 'kid' #age = 20 #if age >= 6: # print 'teenager' #elif age >= 18: # print 'adult' #else: # print 'kid'
false
9a3b9864abada3b264eeed335f6977e61b934cd2
willzhang100/learn-python-the-hard-way
/ex32.py
572
4.25
4
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] #first for loop goes through a list for number in the_count: print "This is count %d" % number #same for fruit in fruits: print "A fruit of type: %s" % fruit #mixed list use %r for i in change: print "I got %r" % i #built lists, start with empty elements = [] """ for i in range(0,6): print "Adding %d to the list." % i #append elements.append(i) """ elements = range(0,6) #print for i in elements: print "Element was: %d." % i
true
d6c2b9f271797e580226702c6ec843e00eea3508
SMinTexas/work_or_sleep
/work_or_sleep_in.py
428
4.34375
4
#The user will enter a number between 0 and 6 inclusive and given #this number, will make a decision as to whether to sleep in or #go to work depending on the day of the week. Day = 0 - 4 go to work #Day = 5-6 sleep in day = int(input('Day (0-6)? ')) if day >= 5 and day < 7: print('Sleep in') elif day >= 0 and day <= 4: print('Go to work') else: print('You are outside the range of available days of the week!')
true
d0db003c65b5b4bb5d08db8d23f49b29d15a2d9b
mariaKozlovtseva/Algorithms
/monotonic_check.py
798
4.3125
4
def monotonic(arr, if_true_false=False): """ Check whether array is monotonic or not :param arr: array of different numbers :return: string "Monotonic" / "Not monotonic" or if True / False """ decreasing = False increasing = False idx = 0 while not increasing and idx < len(arr)-1: # use abs() as we may have negative values if abs(arr[idx]) > abs(arr[idx+1]): increasing = True else: decreasing = True idx += 1 if if_true_false: return True if (decreasing and not increasing) else False return "Monotonic" if (decreasing and not increasing) else "Not monotonic" if __name__ == '__main__': print(monotonic([1,-2,-4,-10,-100])) print(monotonic([0,-1,-2,1,4], if_true_false=True))
true
b300d785046b93cc5829c98ede2cdb5bfd12e105
grgoswami/Python_202011
/source/Tista3.py
818
4.21875
4
colors = { 'Tista': 'Purple', 'Gia' : 'Turquoise', 'Anya':'Minty Green' } print(colors) for name , color in colors.items(): print(name + "'s favorite color is " + color) print(name + ' has ' + str(len(name)) + ' letters in her or his name') print('\n') #Survey name1 = input("What's your name ? ") color1 = input('Favorite Color : ') name2 = input("What's your name ? ") color2 = input('Favorite Color : ') name3 = input("What's your name ? ") color3 = input('Favorite Color : ') survey = { name1: color1, name2: color2, name3: color3 } print('\n') for name, color in survey.items(): print(name + "'s favorite color is " + color) print(name + ' has ' + str(len(name)) + ' letters in her name') print('\n')
false
41c3f5039e71c2ea562a61ddb37987b3e80ad0fc
grgoswami/Python_202011
/source/reg17.py
465
4.28125
4
def Fibonacci0(num): """ The following is called the docstring of the function. Parameters ---------- num : int The number of elements from the Fibonacci sequence. Returns ------- None. It prints the numbers. """ a = 1 print(a) b = 1 print(b) for i in range(2, num): c = a + b print(c) a = b b = c Fibonacci0(3) Fibonacci0(5) Fibonacci0(10) Fibonacci0(100)
true
c0dfe2aa84bf9cc8e5e33ecdd36a8712e3601f13
grgoswami/Python_202011
/source/reg6.py
442
4.21875
4
# String indexing str0 = 'Tista loves chocolate' print(len(str0)) print(str0[3]) # String slicing print(str0[5:7]) print(str0[4:7]) # String mutation # Strings are not 'mutable'; they are called immutable str0[3] = 'z' print(str0) s2 = 'New York' zip_code = 10001 # The following is called string concatenation print(s2 + zip_code) print(s2 + str(zip_code)) print(s2 + ' ' + str(zip_code)) s3 = 'New York ' print(s3 + str(zip_code))
false
8a0fcd96d2e7a22e2ef1d45af7dd914f4492d856
vamsikrishnar161137/DSP-Laboratory-Programs
/arrayoperations.py
1,774
4.28125
4
#SOME OF THE ARRAY OPERATIONS import numpy as np a=np.array([(1,4,2,6,5),(2,5,6,7,9)])#defining the array. print '1.The predifined first array is::',a b=np.size(a)#finding size of a array. print '2.Size of the array is::',b c=np.shape(a)#finding shape of an array print '3.Shape of the array is::',c d=np.ndim(a) print '4.Dimension of the array is::',d e=a.reshape(5,2) print '5.Reshaping of an array is::\n',e #Slicing(getting a specific digit from digit::) f=a[0,3] print '6.The digit is::',f g=np.linspace(1,3,5) print '7.The result is::',g h=np.max(a) print '8.Max of the array::',h i=np.min(a) print '9.Min of the array::',i j=np.sum(a)#sum of the digits in a array. print '10.The sum of the digits in the array is::',j k=np.sqrt(a)#finding square roots of the digits in the array. print '11.The square roots of the digits in an array is::\n',k l=np.std(a)#finding standard deviation for digits in the array. print '12.The standard deviation of the array::',l #doing sum,sub,mul,div to two arraya with their respective elements. m=np.array([(1,2,3,4,5),(4,5,6,7,8)]) n=a+m print '13.The sum of the two arrays is::\n',n o=a-m print '14.The subtraction of the two arrays is::\n',o p=a*m print '15.The multiplication of the two arrays is::\n',p q=a/m print '16.The division of the two arrays is::\n',q #placing second array in the first array.(called as stacking processes) r=np.vstack((a,m))#vertical stacking print '17.The concatenation of the two arrays is::\n',r s=np.hstack((a,m))#horizontal stacking print '18.The concatenation of the two arrays is::\n',s #converting all in one column t=a.ravel() print '19.The result is::',t u=m.ravel() print '20.The result is::',u #finding data type of the array. print '21.The data type of the array is::' print (a.dtype)
true
bc16a054e3eee1730211763fe3d0b71be4d41019
shevdan/programming-group-209
/D_bug_generate_grid.py
2,259
4.375
4
""" This module contains functions that implements generation of the game grid. Function level_of_dif determines the range (which is the representation of the level of difficulty which that will be increased thorough the test) from which the numbers will be taken. Function generate_grid generates grid, with a one specific number of needed type and 9 more random numbers. """ from random import sample, randint, shuffle from typing import List from D_bug_number_type import user_number_type as check def level_of_dif(num_of_iterations): """ This functions determines the range from which the numbers will be taken. 0 - 3 iterations : easy level of game: range of numbers [0, 20] 4 - 6 iterations : medium level of game: range of numbers [20, 50] 7 - 9 iterations : hard level of game: range of numbers [50, 100] >>> level_of_dif(0) [10, 20] >>> level_of_dif(4) [20, 50] >>> level_of_dif(6) [20, 50] >>> level_of_dif(9) [50, 100] """ range_of_nums = [] if -1 < num_of_iterations < 4: range_of_nums = [10, 20] if 3 < num_of_iterations < 7: range_of_nums = [20, 50] if 6 < num_of_iterations < 10: range_of_nums = [50, 100] return range_of_nums def generate_grid(range_of_nums: List[int], num_type: str) -> List[int]: """ This function generates the game grid, which consist of 10 numbers. Args : range_of_nums: a list of two ints, which represent the level of difficulty, which increases thorough the test. num_type: a string, which represents what type of num has to be present in the game grid. Returns: a list of 10 positive ints, which represents the game grid. Args are given by the other functions, therefore no exceptions should be rose. """ right_num = randint(range_of_nums[0], range_of_nums[1]) # checks whether a num of desired type will be present in the grid. while not check(right_num, num_type): right_num = randint(range_of_nums[0], range_of_nums[1]) range_of_generation = [i for i in range(range_of_nums[0], range_of_nums[1])] grid = sample(range_of_generation, 9) grid.append(right_num) shuffle(grid) return grid
true
3da0639a03ae3f87446ad57a859b97af60384bc4
blafuente/SelfTaughtProgram_PartFour
/list_comprehension.py
2,397
4.65625
5
# List Comprehensions # Allows you to create lists based on criteria applied to existing lists. # You can create a list comprehension with one line of code that examins every character in the original string # Selects digigts from a string and puts them in a list. # Or selects the right-most digit from the list. # Example: # return [c for c in input_string if c.isdigigt()][-1] input_string = "Buy 1 get 2 free" # A simple use of list comprehension is to create a new list from a string new_list = [c for c in input_string] # Basically says to loop through each character in input_string to create a new list print(new_list) # [c for c in input_string if c.isdigit()] # You can also add a conditional statement to the list comprehension # The 'if' clause only allows digits to go into the new list # The output will be a list containing only digits from the input_string # You can tack on a negative index to select only the last digit from the new list. # [c for c in input_string if c.isdigit()][-1] # new_list = [expression(i) for i in input_list if filter(i)] # The general syntax for a list comprehension contains a flexible collection of tools that can be applied to lists # Expression(i) is based on the variable used for each elelment in the input_string # You can simply step through each item using an expression such as "c for c" or you can manipulate # those items mathematically or character wise. # For example, the expression price*3 for price would step through each value of price at the # same time multiplying each price by three. # The word[0] for word would step through a list of words, taking the first letter of each # in input_list # This part of the list comprehension specifies the input string or list the last part of the # list comprehension # if filter(i) # The last part of the list comprehension allows you to add a conditional statement to filter out list items that match # specified critera such as being a digit ,if c.isdigit(), or being an even number (if n%2 == 0) # recap # List comprehension create lists based on criteria that iterate, processes, or filters an existing list # The general syntax for a list comprehension statement can contain an expression for stepping through an input list # based on a for loop and then expression to use as a filter to select specific items from the input_list to be added # to the new_list
true
d2f172a112ec5a30ab4daff10f08c5c4c5bc95a1
AAKASH707/PYTHON
/binary search tree from given postorder traversal.py
2,332
4.21875
4
# Python program to construct binary search tree from given postorder traversal # importing sys module import sys # class for creating tree nodes class Node: def __init__(self, data): self.data = data self.left = None self.right = None # initializing MIN and MAX MIN = -sys.maxsize - 1 MAX = sys.maxsize # recurrsive function for creating binary search tree from postorder def constructBST(postorder, postIndex, key, min, max, size): # base case if postIndex[0] < 0: return None root = None # If current element of postorder is in range(min to max), then only it is part # of current subtree if key > min and key < max: # creating a new node and assigning it to root, decrementing postIndex[0] by 1 root = Node(key) postIndex[0] -= 1 if (postIndex[0] >= 0): # all the nodes in the range(key to max) will be in the right subtree, # and first such node will be the root of the right subtree. root.right = constructBST(postorder, postIndex, postorder[postIndex[0]], key, max, size) # all the nodes in the range(min to key) will be in the left subtree, # and first such node will be the root of the left subtree. root.left = constructBST(postorder, postIndex, postorder[postIndex[0]], min, key, size) return root # function for printing the inorder traversal of the binary search tree def printInorder(root): if (root == None): return printInorder(root.left) print(root.data, end=" ") printInorder(root.right) # Driver code def main(): # asking the user for postorder sequence postorder = list(map(int, input('Enter the postorder traversal: ').split())) size = len(postorder) # postIndex is used to keep track of index in postorder postIndex = [size - 1] # calling function constructBST root = constructBST(postorder, postIndex, postorder[postIndex[0]], MIN, MAX, size) print("The inorder traversal of the constructed binary search tree: ") # calling function printInorder printInorder(root) if __name__ == "__main__": main()
true
a079327ad1c4c1fcc01c22dc9e1e8f335f119958
AAKASH707/PYTHON
/Print Square Number Pattern.py
234
4.25
4
# Python Program to Print Square Number Pattern side = int(input("Please Enter any Side of a Square : ")) print("Square Number Pattern") for i in range(side): for i in range(side): print('1', end = ' ') print()
true
5b90a261a667a86387e49463f49a8855b477174c
AAKASH707/PYTHON
/Count Words in a String using Dictionary Example.py
639
4.34375
4
# Python Program to Count words in a String using Dictionary string = input("Please enter any String : ") words = [] words = string.split() frequency = [words.count(i) for i in words] myDict = dict(zip(words, frequency)) print("Dictionary Items : ", myDict) *********************************************************************************************** # Python Program to Count words in a String using Dictionary 2 string = input("Please enter any String : ") words = [] words = string.split() # or string.lower().split() myDict = {} for key in words: myDict[key] = words.count(key) print("Dictionary Items : ", myDict)
true
35d76db2c786b8d4bec786699466b294d98b9855
dnsdigitaltech/aulas-de-python3
/funcoes.py
755
4.46875
4
#Funções permitem as chamadas modularizações do meu códigos #São blocos de códigos que spá serão chamados executados quando forem chamados #Em python as funções são definidas pela palavra reservada def """ Definição def NOME(parâmetros): COMANDOS Chamada NOME(argumentos) """ #Função que faz a soma de dois valores def soma(x, y): print(x) print(y) print(x + y) soma(6, 2) #Exibir resultado fora da função é necessrio ter p return def soma(x, y): return x + y def multiplicacao(x, y): return x * y s = soma(6, 2) # é necessário cria o valor para armazenar a variavel retorno print(s) m = multiplicacao(3,4) print(m) #Também pode chamar várias funções recursivamente print(soma(s,m))
false
ab975ef466da96fb72d1996b1df0c8ee155934c5
dnsdigitaltech/aulas-de-python3
/lista-parte-2-ordenar-lista.py
509
4.15625
4
#ordenar as listas lista = [124,345,72,46,6,7,3,1,7,0] #para ordenar a lista usa-se o método sort lista.sort() # altera ardenadamente a lista que já existe print(lista) lista = sorted(lista) # retorno uma lista ordenada print(lista) #Ordenar decrescente lista.sort(reverse=True) print(lista) #Inverter a lista lista.reverse() print(lista) lista2 = ["bola", "abacate", "dinheiro"] lista2.sort() #ordena a lista alfabeticamente print(lista2) lista2.sort(reverse=True) print(lista2)#ordenação de strigs
false
5d464a64a9d8ef963da82b64fba52c598bc2b56c
josh-folsom/exercises-in-python
/file_io_ex2.py
402
4.4375
4
# Exercise 2 Write a program that prompts the user to enter a file name, then # prompts the user to enter the contents of the file, and then saves the # content to the file. file_name = input("Enter name of file you would like to write: ") def writer(file_name): file_handle = open(file_name, 'w') file_handle.write(file_name) file_handle.close() print(file_name) writer(file_name)
true
f36220a4caae8212e34ff5070b9a203f4b5814f8
josh-folsom/exercises-in-python
/python_object_ex_1.py
2,486
4.375
4
# Write code to: # 1 Instantiate an instance object of Person with name of 'Sonny', email of # 'sonny@hotmail.com', and phone of '483-485-4948', store it in the variable sonny. # 2 Instantiate another person with the name of 'Jordan', email of 'jordan@aol.com', # and phone of '495-586-3456', store it in the variable 'jordan'. # 3 Have sonny greet jordan using the greet method. # 4 Have jordan greet sonny using the greet method. # 5 Write a print statement to print the contact info (email and phone) of Sonny. # 6 Write another print statement to print the contact info of Jordan. class Person(): greeting_count = 0 def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.friends = [] self.num_unique_people_greeted = 0 self.uniquecounter = [] def greet(self, other_person): print ('Hello {}, I am {}!'.format(other_person, self.name)) self.greeting_count += 1 # for other_person in list1: if other_person not in self.uniquecounter: self.uniquecounter.append(other_person) self.num_unique_people_greeted += 1 def print_contact_info(self): print("{}'s email: {} , {}'s phone number: {}".format(self.name, self.email, self.name, self.phone)) def add_friend(self, other): self.friends.append(other) def __str__(self): return"Contact info for {} : email - {} | phone - {}".format(self.name, self.email, self.phone) # print('Person: {} {} {}'.format(self.name, self.email, self.phone)) # def greeting_count(self, greeting_count): # newcount = [] # if self.name.greet() == True: # newcount = count + 1 # print(newcount) sonny = Person('Sonny', 'sonny@hotmail.com', '483-485-4948') jordan = Person('Jordan', 'jordan@aol.com', '495-586-3456') print(jordan.greeting_count) print(sonny.greeting_count) sonny.greet('Jordan') sonny.greet('Jordan') #jordan.greet('Sonny') #sonny.print_contact_info() #jordan.print_contact_info() #print(sonny.email, sonny.phone) #print(jordan.email, jordan.phone) #jordan.friends.append(sonny) #sonny.friends.append(jordan) #print(len(jordan.friends)) #print(len(sonny.friends)) #print(sonny.friends) #print(jordan.friends) #jordan.add_friend(sonny) #print(len(jordan.friends)) #print(len(sonny.friends)) #print(jordan.greeting_count) #print(sonny.greeting_count) #print(jordan) print(sonny.num_unique_people_greeted) #jordan.__str__()
true
953751722d3d968d169e147a78ea2716fcb573ce
Chadlo13/pythonTutorials
/Test13-Compare.py
279
4.21875
4
def maxFunc (num1,num2,num3): return max(num1,num2,num3) input1 = input("Enter a number: ") input2 = input("Enter a number: ") input3 = input("Enter a number: ") maxNum = maxFunc(int(input1),int(input2),int(input3)) print("the largest value is: " + str(maxNum))
false
26f2d3651294e73420ff40ed603baf1ac2abb269
Rohitjoshiii/bank1
/read example.py
439
4.21875
4
# STEP1-OPEN THE FILE file=open("abc.txt","r") #STEP2-READ THE FILE #result=file.read(2) # read(2) means ir reads teo characters only #result=file.readline() #readline() it print one line only #result=file.readlines() #readlines() print all lines into list line=file.readlines() # for loop used when we dont want our text into list form for result in line: print(result) #STEP3-CLOSE THE FILE file.close()
true
cefd70520471331df28cce805b8041f465f8d24a
Pasha-Ignatyuk/python_tasks
/task_5_7.py
912
4.15625
4
"""Дана целочисленная квадратная матрица. Найти в каждой строке наибольший элемент и поменять его местами с элементом главной диагонали.[02-4.2-ML22]""" import random n = 4 m = 4 matrix = [[random.randrange(0, 10) for y in range(m)] for x in range(n)] print(matrix) def print_matrix(matrix): for i in range(len(matrix)): for j in range(len(matrix[i])): print("{:4d}".format(matrix[i][j]), end="") print() print_matrix(matrix) print("") # для разделения матриц, чтобы не сливались в глазах for i in range(len(matrix)): for j in range(len(matrix[0])): max_elem = max(matrix[i]) if i != j: continue else: matrix[i][j] = matrix[i][j] * 0 + max_elem print_matrix(matrix)
false
db3c248cd270dad58a6386c4c9b6dc67e6ae4fab
AK-1121/code_extraction
/python/python_20317.py
208
4.1875
4
# Why mutable not working when expression is changed in python ? y += [1,3] # Means append to y list [1,3], object stays same y = y+[1,3] # Means create new list equals y + [1,3] and write link to it in y
true
b3a16e0f14a5221be418de9d5162ad97cff9fba0
JoelDarnes88/primer_programa
/2.0.-Come_helado.py
532
4.1875
4
apetece_helado = input("¿Te apetece helado? (Si/No): ") tiene_dinero = input("Tienes dinero (Si/No): ") esta_el_señor_de_los_helados = input("esta el señor de los helados (Si/No) ") esta_tu_tia = input("¿Estás con tu tía? (Si/No)") Te_apetece_helado = apetece_helado == "Si" puedes_permitirtelo = tiene_dinero == "Si" or esta_tu_tia == "Si" esta_el_señor = esta_el_señor_de_los_helados == "Si" if Te_apetece_helado and puedes_permitirtelo and esta_el_señor: print("pues_comete_un_helado") else: print("pues_nada")
false
6f2581f4fafe6f3511327d5365f045ba579a46b1
CdavisL-coder/automateTheBoringStuff
/plusOne.py
372
4.21875
4
#adds one to a number #if number % 3 or 4 = 0, double number #this function takes in a parameter def plus_one(num): num = num + 1 #if parameter is divided by 2 and equal zero, the number is doubled if num % 2 == 0: num2 = (num + 1) * 2 print(num2) #else print the number else: print(num) plus_one(4) plus_one(80) plus_one(33)
true
73c96ebcfebcf11ad7fde701f001d8bdbd921b00
poljkee2010/python_basics
/week_2/2.3 max_of_three.py
215
4.1875
4
a, b, c = (int(input()) for _ in range(3)) if a < b > c: print(b) elif a < c > b: print(c) elif b < a > c: print(a) elif a > b or a > c: print(a) elif b > a or b > c: print(b) else: print(c)
false
17e5dcdb6b83c5023ea428db1e93cc494d6fe405
Parashar7/Introduction_to_Python
/Celsius_to_farenheight.py
217
4.25
4
print("This isa program to convert temprature in celcius to farenheight") temp_cel=float(input("Enter the temprature in Celsius:")) temp_faren= (temp_cel*1.8) +32 print("Temprature in Farenheight is:", temp_faren)
true
ebefd9d3d3d7139e0e40489bb4f3a022ee790c19
vatasescu-predi-andrei/lab2-Python
/Lab 2 Task 2.3.py
215
4.28125
4
#task2.3 from math import sqrt a=float(input("Enter the length of side a:")) b=float(input("Enter the length of side b:")) h= sqrt(a**2 + b**2) newh=round(h, 2) print("The length of the hypotenuse is", newh)
true
8eea3adf0682985a99b7276a0cc720cbeec98d0b
scalpelHD/Study_python
/课堂/car.py
1,239
4.125
4
class Car(): """一次模拟汽车的尝试""" def __init__(self,make,model,year): """初始化描述汽车的属性""" self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): """返回整洁的描述性信息""" long_name=str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): """打印一条指出汽车里程的消息""" print('This car has '+str(self.odometer_reading)+' miles on it.') def update_odometer(self,mileage): """ 将里程表读数设置为指定的值 禁止将里程表读数往回调 """ if mileage>+self.odometer_reading: self.odometer_reading=mileage else: print('You can\'t roll back an odometer!') def increment_odometer(self,miles): """将里程表读数增加指定的量""" if miles>=0: self.odometer_reading+=miles else: print('The incresement can\'t smaller than zero!') def fill_gas_tank(self,scale): """描述油箱大小""" print('The car has a '+str(scale)+' L tank.')
false
1179a03075ab98c1e6727b067074bb3f67d4ba38
scalpelHD/Study_python
/课堂/5 if 语句.py
1,153
4.21875
4
cars=['AUDI','Toyota','bmw','honda','beijing','jeep','beiJING']#if语句 for car in cars: if car=='bmw': print(car.upper()) else: print(car.title()) if car.lower()=='audi' or car.upper()=='TOYOTA':#或 print(car.title()) if car.lower()=='beijing' and car!='beiJING':#与 print(car) if 'honda' in cars:#检查特定值是否包含在列表中 print('The honda is existed in the list!') if 'auto' not in cars:#检查特定值是否不包含在列表中 print('The auto is not existed in the list!') #if-else语句 ages=[19,18,17,20] names=['peter','tony','tom','jhon'] i=0 for age in ages: if age>=18: print('MR.'+names[i].title()+',you are old enough to vote!') print('Have you registered to vote yet?\n') else: print('MR.'+names[i].title()+',sorry,you are too young to vote.') print('Please register to vote as soon as you turn 18\n') i+=1 #if-elif-else语句 for age in ages: if age<=18: print('Your admission cost is $0.') elif age<20: print('Your admission cost is $5.') else: print('Your admission cost is $10.')
false
f235e7b36ac48915e7e0750af1fb6621a971f227
yadavpratik/python-programs
/for_loops_programs.py
1,901
4.28125
4
# normal number print with for and range function '''n=int(input("enter the number : ")) print("normal number print with for and range function") for i in range(n): print(i) # ============================================================================================================================= # print number with space print("print horizontal with spaces :") for i in range(n): print(i,end=" ") # ============================================================================================================================= #print number with increment 2 print("\nprint with increment 2 :") for i in range(0,n,2): print(i,end=" ") # ============================================================================================================================= #print number with decrement 2 print("\nprint with decrement 2 :") for i in range(n,0,-2): print(i,end=" ") print() # ============================================================================================================================= name = "pratik" #by for loop print vertical string for i in name: print(i) #by for loop print horizontal string for i in name: print(i,end=" ") list1=list(name) print("\n",list1) for i in list1: print(i,end=" ")''' # ============================================================================================================================= # n=int(input("enter the number of rows :")) '''for i in range(5): #Represnts row for j in range(5): #Represents columns if i<j: print(j,end=" ") print()''' # ============================================================================================================================= '''for i in range(1,n+1): for j in range(1,n+1): print(n+1-i,end=" ") print()'''
true
a1ee1c5cfa1a83dfa4c2ca2dc2ec204b201ed1f2
NatalieBeee/PythonWithMaggie
/algorithms/printing_patterns.py
1,218
4.28125
4
''' #rows for i in range(0,5): #columns for j in range(0,i+1): print ('*', end ='') print ('\r') ''' # half_pyramid() is a function that takes in the number of rows def half_pyramid(num_r): #for each row -vertical for i in range(0,num_r): #for each column -horizontal for j in range(0,i+1): print ('*', end ='') print ('\r') def tree_log(log_length,log_width): #for each row -vertical for i in range(0,log_length): #for each column -horizontal for j in range(0,log_width): print ('*',end ='') print ('\r') half_pyramid(6) half_pyramid(8) half_pyramid(15) half_pyramid(19) tree_log(6,8) ''' Extra fun! 1) Add a base to the tree - DONE! tree_log() * ** *** * ** *** **** ***** * * 2) Add "|" to the top of the tree | * ** *** * ** *** **** 3) Add a star to the top of the tree * ** * * ** *** **** ***** * ** *** 4) Get the user to input the number of rows instead (hint: input()) 5) Instead of a Christmas tree, let's make a ball instead * ** *** ** * 6) Let's make a snow man * ** * * ** *** **** ***** **** *** ** * 7) Use "/" and "\" instead of "*" - let's get creative! 8) Free style! '''
true
3cacfde1db19a4f7b8ccf3fca55c579fc8fc7313
smith-sanchez/validadores_en_python
/Boleta 17.py
682
4.125
4
#INPUT cliente=(input("ingrese el nommbre del cliente: ")) precio_mochila=float(input("ingrese el precio de la mochila:")) numero=int(input("numero de mochilas:")) #procesing total=(precio_mochila*numero) #vereficador cliente_necesario=(total>120) #OUTPUT print("############################") print("# BOLETA DE VENTA") print("############################") print("#") print("# el nombre el ciente es: :",cliente) print("# precio de la mochila es :s/",precio_mochila) print("# numero de mochilas :",numero) print("total :s/",total) print("############################") print("cliente necesariopara el negocio?",cliente_necesario)
false
754cd0a9c3159b2eb91350df0f5d2907c543a6ad
sbishop7/DojoAssignments
/Python/pythonAssignments/funWithFunctions.py
639
4.21875
4
#Odd/Even def odd_even(): for count in range(1,2001): if count % 2 == 1: print "Number is ", count, ". This is an odd number." else: print "Number is ", count, ". This is an even number." #Multiply def multiply(arr, x): newList = [] for i in arr: newList.append(i*x) return newList #Hacker Challenge def layered_multiples(arr): new_array = [] for i in arr: count = 0 x=[] while count < i: x.append(1) count += 1 new_array.append(x) return new_array x = layered_multiples(multiply([2,4,5],3)) print x
true
9535c83847a12174fc9d6002e19f70c163876af5
LdeWaardt/Codecademy
/Python/1_Python_Syntax/09_Two_Types_of_Division.py
1,640
4.59375
5
# In Python 2, when we divide two integers, we get an integer as a result. When the quotient is a whole number, this works fine # However, if the numbers do not divide evenly, the result of the division is truncated into an integer. In other words, the quotient is rounded down to a whole number. This can be surprising when you expect to receive a decimal and you receive a rounded-down integer To yield a float as the result instead, programmers often change either the numerator or the denominator (or both) to be a float quotient1 = 7./2 # the value of quotient1 is 3.5 quotient2 = 7/2. # the value of quotient2 is 3.5 quotient3 = 7./2. # the value of quotient3 is 3.5 # An alternative way is to use the float() method: quotient1 = float(7)/2 # the value of quotient1 is 3.5 # PROBLEM : You have come home from the grocery store with 100 cucumbers to split amongst yourself and your 5 roommates (6 people total). Create a variable cucumbers that holds 100 and num_people that holds 6. Create a variable called whole_cucumbers_per_person that is the integer result of dividing cucumbers by num_people. Print whole_cucumbers_per_person to the console. You realize that the numbers don't divide evenly and you don't want to throw out the remaining cucumbers. Create a variable called float_cucumbers_per_person that holds the float result of dividing cucumbers by num_people. Print float_cucumbers_per_person to the console. cucumbers = 100 num_people = 6 whole_cucumbers_per_person = cucumbers / num_people print whole_cucumbers_per_person float_cucumbers_per_person = float(cucumbers)/num_people print float_cucumbers_per_person
true
86ea818619a81d0034994f0c9c70d326b5972d56
Sanakhan29/PythonPrograms
/if_elif_else.py
260
4.125
4
ali_age = int(input('Input Ali Age:')) sara_age = int(input('Input Sara Age:')) if ali_age == sara_age: print('They both have same age') elif ali_age < sara_age: print('Ali is younger than Sara') else: print('Ali is elder than Sara')
false
1e34f96001b049c57de96ba8aef944d7aa5268da
ShrutiBhawsar/practice-work
/MapFilterLambda_part4.py
1,502
4.25
4
numbers = [1,2,3,4,5,6,7,8,9,10] def EvenFunction1(): evenList = [] for number in numbers: if number % 2 == 0: evenList.append(number) print(numbers) print("Even Number List is {}".format(evenList)) # EvenFunction1() def OddFunction1(): oddList = [] for number in numbers: if number != 0: oddList.append(number) print(numbers) print("Odd Number List is {}".format(oddList)) # OddFunction1() def EvenFunction2(): evenList = list(filter(lambda number : number % 2 == 0,numbers)) print(numbers) print("Even Number List using filter method is {}".format(evenList)) # EvenFunction2() def OddFunction2(): oddList = list(filter(lambda number : number %2 != 0, numbers)) print(numbers) print("Odd Number List using filter method is {}".format(oddList)) # OddFunction2() def SquareOfEven(): evenList = list(filter(lambda number : number % 2 == 0,numbers)) print("Even Number List using filter method is {}".format(evenList)) squareOfEven = list(map(lambda n: n* n , evenList)) print("Square of Even Number List using map method is {}".format(squareOfEven)) # SquareOfEven() def SquareOfOdd(): oddList = list(filter(lambda number : number % 2 != 0,numbers)) print("Odd Number List using filter method is {}".format(oddList)) squareOfOdd = list(map(lambda n: n* n , oddList)) print("Square of Odd Number List using map method is {}".format(squareOfOdd)) SquareOfOdd()
false
ea14d5de2d43b1f19eb612dea929a612ebfed717
Ottermad/PythonNextSteps
/myMagic8BallHello.py
819
4.15625
4
# My Magic 8 Ball import random # put answers in a tuple answers = ( "Go for it" "No way, Jose!" "I'm not sure. Ask me again." "Fear of the unkown is what imprisons us." "It would be madness to do that." "Only you can save mankind!" "Makes no difference to me, do or don't - whatever" "Yes, I think on balance that is the right choice" ) print("Welcome to MyMagic8Ball.") name = input("What is your name?") # get the user's question question = input("Ask me for advice, " + name + " then press ENTER to shake me.\n") print("shaking ...\n" * 4) # use the randint function to select the correct answer choice = random.randint(0,7) # print the answer to the screen print(answers[choice]) # exit nicely input("\n\nThanks for playing, " + name + ". Press the RETURN key to finish.")
true
9f4a1f9c1e212efe17186287746b7b4004ac037a
Col-R/python_fundamentals
/fundamentals/Cole_Robinson_hello_world.py
762
4.21875
4
# 1. TASK: print "Hello World" print('Hello World!') # 2. print "Hello Noelle!" with the name in a variable name = "Col-R" print('Hello', name) # with a comma print('Hello ' + name) # with a + # # 3. print "Hello 42!" with the number in a variable number = 24 print('Hello', number) # with a comma print('Hello '+ str(number)) # with a + -- this one should give us an error! # # 4. print "I love to eat sushi and pizza." with the foods in variables fave_food1 = "ramen" fave_food2 = "cake" print("I love to eat {} and {}".format(fave_food1, fave_food2)) # with .format() print(f'I love to eat {fave_food1} and {fave_food2}') # with an f string eats = (f'I love to eat {fave_food1} and {fave_food2}') print (len(eats)) print (eats.upper()) print (eats.title())
true
768d5acc06bf952cb396c18ceea1c6f558634f6f
Col-R/python_fundamentals
/fundamentals/strings.py
1,874
4.4375
4
#string literals print('this is a sample string') #concatenation - The print() function inserts a space between elements separated by a comma. name = "Zen" print("My name is", name) #The second is by concatenating the contents into a new string, with the help of +. name = "Zen" print("My name is " + name) number = 5 print('My number is', number) # print('My number is'+ number) throws an error # Type Casting or Explicit Type Conversion # print("Hello" + 42) # output: TypeError print("Hello" + str(42)) # output: Hello 42 total = 35 user_val = "26" # total = total + user_val output: TypeError total = total + int(user_val) # total will be 61 # f-strings: Python 3.6 introduced f-strings for string interpolation. To construct a f-string, place an f right before the opening quotation. Then within the string, place any variables within curly brackets. first_name = "Zen" last_name = "Coder" age = 27 print(f"My name is {first_name} {last_name} and I am {age} years old.") # string.format() Prior to f-strings, string interpolation was accomplished with the .format() method. first_name = "Zen" last_name = "Coder" age = 27 print("My name is {} {} and I am {} years old.".format(first_name, last_name, age)) # output: My name is Zen Coder and I am 27 years old. print("My name is {} {} and I am {} years old.".format(age, first_name, last_name)) # output: My name is 27 Zen and I am Coder years old. # %-formatting - an even older method, the % symbol is used to indicate a placeholder, a %s for a string and %d for a number. hw = "Hello %s" % "world" # with literal values py = "I love Python %d" % 3 print(hw, py) # output: Hello world I love Python 3 name = "Zen" age = 27 print("My name is %s and I'm %d" % (name, age)) # or with variables # output: My name is Zen and I'm 27 # Built in methods x = "hello world" print(x.title()) # output: "Hello World"
true
66d04eb4ab92c922cd8f9ae2d60699b1eb6947c3
Bikryptorchosis/PajtonProj
/TestSets.py
2,338
4.15625
4
# farm_animals = {"sheep", "cow", "hen"} # print(farm_animals) # # for animal in farm_animals: # print(animal) # # print('-' * 40) # # wild_animals = set(['lion', 'panther', 'tiger', 'elephant', 'hare']) # print(wild_animals) # # for animal in wild_animals: # print(animal) # # farm_animals.add('horse') # wild_animals.add('horse') # print(farm_animals) # print(wild_animals) # even = set(range(0, 40, 2)) # print(even) # # squares_tuple = (4, 6, 9, 16, 25) # squares = set(squares_tuple) # print(squares) # even = set(range(0, 40, 2)) # print(even) # print(len(even)) # # squares_tuple = (4, 6, 9, 16, 25) # squares = set(squares_tuple) # print(squares) # print(len(squares)) # print(even.union(squares)) # print(len(even.union(squares))) # # print('-' * 20) # # print(even.intersection(squares)) # print(even & squares) # even = set(range(0, 40, 2)) # print(sorted(even)) # # squares_tuple = (4, 6, 9, 16, 25) # squares = set(squares_tuple) # print(sorted(squares)) # # print('e - s') # print(sorted(even.difference(squares))) # print(sorted(even - squares)) # # print('s - e') # print(sorted(squares.difference(even))) # print(sorted(squares - even)) # # print('-' * 20) # # print(sorted(even)) # print(squares) # # even.difference_update(squares) # # print(sorted(even)) # even = set(range(0, 40, 2)) # print(even) # squares_tuple = (4, 6, 9, 16, 25) # squares = set(squares_tuple) # print(squares) # # # print('symmetric diff') # # print(sorted(even.symmetric_difference(squares))) # # squares.discard(4) # squares.remove(16) # squares.discard(8) #does nothing # print(squares) # # try: # squares.remove(8) # except KeyError: # print("Awesome m8, the 8 is not gr8") # # # fucklist = [x for x in squares] # print(fucklist) # even = set(range(0, 40, 2)) # print(even) # squares_tuple = (4, 6, 16) # squares = set(squares_tuple) # print(squares) # if squares.issubset(even): # print("squares is a subsset of even") # # if even.issuperset(squares): # print("even is a superset of squares") # even = frozenset(range(0, 100, 2)) # print(even) # program that takes some text and returns # a list of all the characters in the text that are not vowels, sorted in alphabetical order sent = set(input('Text to do stuff on: ')) chars = sorted(list(sent.difference('aeiou'))) print(chars)
false
7ddac6a6f3770cacd02645e29e1058d885e871f2
dburr698/week1-assignments
/todo_list.py
1,924
4.46875
4
# Create a todo list app. tasks = [] # Add Task: # Ask the user for the 'title' and 'priority' of the task. Priority can be high, medium and low. def add_task(tasks): name = input("\nEnter the name of your task: ") priority = input("\nEnter priority of task: ") task = {"Task": name, "Priority": priority} tasks.append(task) return tasks # Delete Task: # Show user all the tasks along with the index number of each task. User can then enter the index number of the task to delete the task. def delete_task(tasks): for index in range(len(tasks)): print(f"{index + 1} - {tasks[index]['Task']} - {tasks[index]['Priority']}") num = int(input("\nEnter the number of the task you would like to delete: ")) for index in range(len(tasks)): if tasks[index] == tasks[num - 1]: print(f"\nThe task {tasks[num -1]['Task']} has been deleted from your To-Do list.") del tasks[index] break return tasks # View all tasks: # Allow the user to view all the tasks in the following format: def view_tasks(tasks): if len(tasks) == 0: print("\nYou have no tasks.") for index in range(len(tasks)): print(f"{index + 1} - {tasks[index]['Task']} - {tasks[index]['Priority']}") # When the app starts it should present user with the following menu: # Press 1 to add task # Press 2 to delete task # Press 3 to view all tasks # Press q to quit # The user should only be allowed to quit when they press 'q'. while True: choice = input( "\nPress 1 to add task \nPress 2 to delete task \nPress 3 to view all tasks \nPress q to quit \n" ) if choice == "q": print("\nGoodbye\n") break elif choice == "1": add_task(tasks) elif choice == "2": delete_task(tasks) elif choice == "3": view_tasks(tasks) else: print("\nInvalid option\n")
true
7d6aef42709ca67f79beed472b3b1049efd73513
chriklev/INF3331
/assignment6/_build/html/_sources/temperature_CO2_plotter.py.txt
2,237
4.1875
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt def plot_temperature(months, time_bounds=None, y_bounds=None): """Plots the temperatures of given months vs years Args: months (string): The month for witch temperature values to plot. Can also be list of strings with several month names. time_bounds (tuple or list): Optional argument with minimum and maximum for the years to plot. Must be tuple or list, of integers or floats on the form: (minimum, maximum) y_bounds (tuple or list): Optional argument with minimum and maximum for the y-axis. Must be tuple or list, of integers or floats on the form: (minimum, maximum) """ temperatures = pd.read_csv( "temperature.csv", usecols=["Year"].append(months)) if time_bounds: bounds = temperatures["Year"].map( lambda x: x >= time_bounds[0] and x <= time_bounds[1]) temperatures = temperatures[bounds] temperatures.plot("Year", months, ylim=y_bounds) plt.title("Temperature vs. year for given months") plt.xlabel("time [years]") plt.ylabel("temperature [celsius]") def plot_CO2(time_bounds=None, y_bounds=None): """Plots global carbon emmissions vs years Args: time_bounds (tuple or list): Optional argument with minimum and maximum for the years to plot. Must be tuple or list, of integers or floats on the form: (minimum, maximum) y_bounds (tuple or list): Optional argument with minimum and maximum for the y-axis. Must be tuple or list, of integers or floats on the form: (minimum, maximum) """ co2 = pd.read_csv("co2.csv") if time_bounds: bounds = co2["Year"].map( lambda x: x >= time_bounds[0] and x <= time_bounds[1]) co2 = co2[bounds] co2.plot("Year", "Carbon", ylim=y_bounds, legend=False) plt.title("Global carbon emmissions vs. year") plt.xlabel("time [years]") plt.ylabel("carbon emmissions [million metric tons]") if __name__ == "__main__": plot_CO2() plt.show() plot_temperature( ["January", "February", "March"]) plt.show()
true
3b343e3551776f7ea952f039008577bdfc36ae9c
ewertonews/learning_python
/inputs.py
222
4.15625
4
name = input("What is your name?\n") age = input("How old are you?\n") live_in = input("Where do you live?\n") string = "Hello {}! Good to know you are {} years old and live in {}" print(string.format(name, age, live_in))
true
9c3254d781dda926a1050b733044a62dd1325ec7
kevinsu628/study-note
/leetcode-notes/easy/array/27_remove_element.py
2,103
4.1875
4
''' Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example 1: Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. ''' ''' Approach 1: two pointers i: slow pointer j: fast pointer Intuition: we assign nums[i] to be nums[j] as long as nums[j] is different than the target The whole intuition of two pointer is to replace the array with unique values met by faster pointer ''' def removeElement(nums, val): i = 0; for j in range(len(nums)): if (nums[j] != val): nums[i] = nums[j]; i+=1 return i ''' Approach 2: Two Pointers - when elements to remove are rare Intuition Now consider cases where the array contains few elements to remove. For example, nums = [1,2,3,5,4], val = 4nums=[1,2,3,5,4],val=4. The previous algorithm will do unnecessary copy operation of the first four elements. Another example is nums = [4,1,2,3,5], val = 4nums=[4,1,2,3,5],val=4. It seems unnecessary to move elements [1,2,3,5][1,2,3,5] one step left as the problem description mentions that the order of elements could be changed. Algorithm When we encounter nums[i] = valnums[i]=val, we can swap the current element out with the last element and dispose the last one. This essentially reduces the array's size by 1. Note that the last element that was swapped in could be the value you want to remove itself. xBut don't worry, in the next iteration we will still check this element. ''' def removeElement(nums, val): i = 0 n = len(nums) while (i < n): if (nums[i] == val): nums[i] = nums[n - 1] # reduce array size by one n -= 1 else: i += 1 return n;
true
880f3286c2b5052bd5972a9803db32fd1581c68d
devilsaint99/Daily-coding-problem
/product_of_array_exceptSelf.py
680
4.3125
4
"""Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].""" import numpy as np def product_of_Array(nums): product_list=[] prod=np.prod(nums) for item in nums: product=prod//item product_list.append(product) return product_list num_list=[1,2,3,4,5] num_list1=[3,2,1] print(product_of_Array(num_list)) print(product_of_Array(num_list1)) #GG
true
d997ee82822d758eddcedd6d47059bae5b7c7cac
akassharjun/basic-rsa-algorithm
/app.py
1,320
4.15625
4
# To create keys for RSA, one does the following steps: # 1. Picks (randomly) two large prime numbers and calls them p and q. # 2. Calculates their product and calls it n. # 3. Calculates the totient of n ; it is simply ( p −1)(q −1). # 4. Picks a random integer that is coprime to ) φ(n and calls this e. A simple way is to # just pick a random number ) > max( p,q . # 5. Calculates (via the Euclidean division algorithm) the multiplicative inverse of e # modulo ) φ(n and call this number d. from math import gcd import random def isPrime(x): return 2 in [x,2**x%x] def coprime(a, b): return gcd(a, b) == 1 def modinv(e, phi): d_old = 0; r_old = phi d_new = 1; r_new = e while r_new > 0: a = r_old // r_new (d_old, d_new) = (d_new, d_old - a * d_new) (r_old, r_new) = (r_new, r_old - a * r_new) return d_old % phi if r_old == 1 else None p, q = 13, 17 print("p =", p) print("q =", q) n = p * q print("n =", n) phi_n = (p-1)*(q-1) print("φ(n) =", phi_n) primes = [i for i in range(1,n) if isPrime(i)] coprimes = [] for x in primes: if (coprime(x, n)): coprimes.append(x) e = random.choice(coprimes) print("e =",e) d = modinv(e, phi_n) print("d =",d) print("Public Key is (", n, ",", e, ")") print("Private Key is (", n, ",", d, ")")
true
5d6d8d557279b809dba055dc702c186c0a5abebd
carlson9/KocPython2020
/in-classMaterial/day4/exception.py
375
4.1875
4
raise Exception print("I raised an exception!") raise Exception('I raised an exception!') try: print(a) except NameError: print("oops name error") except: print("oops") finally: print("Yes! I did it!") for i in range(1,10): if i==5: print("I found five!") continue print("Here is five!") else: print(i) else: print("I went through all iterations!")
true
901e7a3327f2da3817d48f0cd748031a7361c1ae
workready/pythonbasic
/sources/t06/t06ejer06.py
824
4.1875
4
class Item: pass # Tu codigo aqui. Estos son los elementos a guardar en las cajas class Box: pass # Tu codigo aqui. Esta clase va a actuar como abstracta class ListBox(Box): pass # Tu codigo aqui class DictBox(Box): pass # Tu codigo aqui # Esto prueba las clases i1 = Item("Item 1", 1) i2 = Item("Item 2", 2) i3 = Item("Item 3", 3) listbox = ListBox() dictbox = DictBox() listbox.add(i1, i2, i3) dictbox.add(i1) dictbox.add(i2) dictbox.add(i3) assert(listbox.count() == 3) assert(dictbox.count() == 3) for i in listbox.items(): print(i) for k, item in dictbox.items().items(): print(i) listbox.empty() dictbox.empty() assert(listbox.count() == 0) assert(dictbox.count() == 0) for i in listbox.items(): print(i) for k, item in dictbox.items().items(): print(i)
false
aa3ce5e3f0253d2065b99dd809b0fe29992dd954
workready/pythonbasic
/sources/t04/t04ej04.py
297
4.28125
4
# Una lista es un iterable a_list = [1, 2, 3] for a in a_list: # Tip: para que print no meta un salto de línea al final de cada llamada, pasarle un segundo argumento end=' ' print (a, end=' ') # Un string también es un iterable a_string = "hola" for a in a_string: print(a, end=' ')
false
5dfd71362ded3403b553bc743fab89bab02e2d38
BluFox2003/RockPaperScissorsGame
/RockPaperScissors.py
1,684
4.28125
4
#This is a Rock Paper Scissors game :) import random def aiChoice(): #This function generates the computers choice of Rock, Paper or Scissors x = random.randint(0,2) if x == 0: choice = "rock" if x == 1: choice = "paper" if x == 2: choice = "scissors" return choice def gameLoop(choice): #Main Game Loop playerChoice = input("Choose Rock, Paper or Scissors ") playerChoice = playerChoice.lower() if playerChoice == "rock": #If the player chooses Rock if choice == "rock": print("AI chose Rock, DRAW") elif choice == "paper": print("AI chose Paper, YOU LOSE") elif choice == "scissors": print("AI chose Scissors, YOU WIN") elif playerChoice == "paper": #If the player chooses Paper if choice == "rock": print("AI chose Rock, YOU WIN") elif choice == "paper": print("AI chose Paper, DRAW") elif choice == "scissors": print("AI chose Scissors, YOU LOSE") elif playerChoice == "scissors": #If the player chooses Scissors if choice == "rock": print("AI chose Rock, YOU LOSE") elif choice == "paper": print("AI chose Paper, YOU WIN") elif choice == "scissors": print("AI chose Scissors, DRAW") else: print("Oops you did a fuckywucky") #If the player chose none of the options repeat = input("Would you like to play again? Y/N ") #Asks the user if they wanna play again if repeat == "Y" or repeat == "y": gameLoop(choice) #Repeats the game loop elif repeat == "N" or repeat == "n": exit() #Ends the program print("Welcome to Rock, Paper, Scissors") ai = aiChoice() aiChoice() gameLoop(ai)
true
690c1fc35fdd3444d8e27876d9acb99e471b296b
gridl/cracking-the-coding-interview-4th-ed
/chapter-1/1-8-rotated-substring.py
686
4.34375
4
# Assume you have a method isSubstring which checks if one # word is a substring of another. Given two strings, s1 and # s2, write code to check if s2 is a rotation of s1 using only # one call to isSubstring (i.e., "waterbottle" is a rotation of # "erbottlewat"). # # What is the minimum size of both strings? # 1 # Does space complexity matter? # Not initially # Time complexity is the priority? # Yes def rotated_substr(word, rotat): if len(word) != len(rotat): return False rotat_conc = rotat + rotat return word in rotat_conc if __name__ == "__main__": print(rotated_substr("thisis", "isthis")) print(rotated_substr("hihiho", "hihole"))
true
f4890c20a78d87556d0136d38d1a1a40ac18c087
AlbertGithubHome/Bella
/python/list_test.py
898
4.15625
4
#list test print() print('list test...') classmates = ['Michael','Bob', 'Tracy'] print('classmates =', classmates) print('len(classmates) =', len(classmates)) print('classmates[1] =', classmates[1]) print('classmates[-1] =', classmates[-1]) print(classmates.append('Alert'), classmates) print(classmates.insert(2,'Bella'), classmates) print(classmates.pop(), classmates) #list 内容可以不一致 classmates[3] = 100 print(classmates) subclassmates = ['zhuzhu', 'xiaoshandian'] classmates[2] = subclassmates print(classmates) print('len(classmates) =', len(classmates)) #tuple test # the elements can not change print() print('tuple test...') numbers = (1, 2, 3) print(numbers) new_num = (1) print(new_num) new_num2 = (1,) print(new_num2) print('len(new_num2) =',len(new_num2)) #if the element of tuple is list, you can change the list elemnet #but you can not change tuple pointer
true
4740f88aedeb28db6bfb615af36dfed7d76fda0f
vincent-kangzhou/LeetCode-Python
/380. Insert Delete GetRandom O(1).py
1,434
4.1875
4
import random class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.valToIndex = dict() self.valList = list() def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool """ if val in self.valToIndex: return False self.valToIndex[val] = len(self.valList) self.valList.append(val) return True def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool """ if val not in self.valToIndex: return False lastVal = self.valList[-1] valIndex = self.valToIndex[val] if lastVal != val: self.valToIndex[lastVal] = valIndex self.valList[valIndex] = lastVal self.valList.pop() self.valToIndex.pop(val) return True def getRandom(self): """ Get a random element from the set. :rtype: int """ return random.choice( self.valList ) # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.delete(val) # param_3 = obj.getRandom()
true
b3b008d706062e0b068dd8287cfb101a7e268dd9
vincent-kangzhou/LeetCode-Python
/341. Flatten Nested List Iterator.py
2,132
4.21875
4
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ # class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.stack = [ [nestedList, 0] ] def _moveToValid(self): """ move stack to a valid position, so that the last place is an integer """ while self.stack: lastList, lastIdx = self.stack[-1] if lastIdx<len(lastList) and lastList[lastIdx].isInteger(): return elif lastIdx == len(lastList): self.stack.pop() if self.stack: self.stack[-1][1] += 1 elif lastList[lastIdx].isInteger() == False: self.stack.append( [ lastList[lastIdx].getList(), 0 ] ) def next(self): """ :rtype: int """ self._moveToValid() lastList, lastIdx = self.stack[-1] ret = lastList[lastIdx].getInteger() self.stack[-1][1] += 1 return ret def hasNext(self): """ :rtype: bool """ self._moveToValid() return bool(self.stack) # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
true
eb36a1f18bb74176c9e5d3739f2a7b7353af4afe
bhavin-rb/Mathematics-1
/Multiplication_table_generator.py
655
4.6875
5
''' Multiplication generator table is cool. User can specify both the number and up to which multiple. For example user should to input that he/she wants to seea table listing of the first 15 multiples of 3. Because we want to print the multiplication table from 1 to m, we have a foor loop at (1) that iterates over each of these numbers, printing the product itself and the number, a. ''' def multi_table(a): for i in range(1, int(m)): # for loop --- (1) print('{0} x {1} = {2}'.format(a, i, a * i)) if __name__ == '__main__': a = input('Enter a number: ') m = input('Enter number of multiples: ') multi_table(float(a))
true
ac5acc74b5275738bd8a5eb40161f5098ea681ff
andytanghr/python-exercises
/PyPart1/madlib.py
285
4.25
4
print('Please fill in the blanks below:') print('Hello, my name is ____(name)____, and today, I\'m going to ____(verb)____.') name = input('What is your name? ') verb = input('What action do you take? ' ) print('Hello, my name is {}, and today, I\'m going to {}.'.format(name, verb))
false
4bde10e50b2b57139aed6f6f74b915a0771062dd
Ayesha116/cisco-assignments
/assigment 5/fac1.py
869
4.6875
5
# Write a Python function to calculate the factorial of a number (a non-negative # integer). The function accepts the number as an argument. def fact(number): factorial = 1 for i in range(1,number+1): factorial = factorial*i print(factorial) fact(4) # # Python program to find the factorial of a number provided by the user. # # change the value for a different result # num = 3 # # To take input from the user # #num = int(input("Enter a number: ")) # factorial = 1 # # check if the number is negative, positive or zero # if num < 0: # print("Sorry, factorial does not exist for negative numbers") # elif num == 0: # print("The factorial of 0 is 1") # else: # for i in range(1,num + 1): # factorial = factorial*i # print("The factorial of",num,"is",factorial)
true
4801ff9cb5d83bd385b3f650a3ba808d7f3cf229
Ayesha116/cisco-assignments
/assigment 5/market6.py
670
4.34375
4
# Question: 6 # Suppose a customer is shopping in a market and you need to print all the items # which user bought from market. # Write a function which accepts the multiple arguments of user shopping list and # print all the items which user bought from market. # (Hint: Arbitrary Argument concept can make this task ease) def marketitem(*shoppinglist): for elements in shoppinglist: print("you brought:", elements) shoppinglist = [] while True: a = input(shoppinglist) print(a, "you buy from market if you leave enter quit:") if shoppinglist == "quit": break shoppinglist.append(a) marketitem(shoppinglist)
true
737c8d15876ea1c6cf897d21b9e96dd7be2fe5d8
Ayesha116/cisco-assignments
/assigment 3/calculator.py
504
4.1875
4
# 1. Make a calculator using Python with addition , subtraction , multiplication , # division and power. a =int(input("enter first value:")) b =int(input("enter second value:")) operator =input("enter operator:") if operator=="+": print("answer=",a+b) elif operator=="-": print("answer=",a-b) elif operator=="*": print("answer=",a*b) elif operator=="/": print("answer=",a/b) elif operator=="**": print("answer=",a**b) else: ("enter correct operator")
false
d7f20fbdee7d28a99591ab6bc4d3baf14f4a1920
aarizag/Challenges
/LeetCode/Algorithms/longest_substring.py
747
4.1875
4
""" Given a string, find the length of the longest substring without repeating characters. """ """ Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. """ def lengthOfLongestSubstring(s: str) -> int: letter_locs = {} cur, best, from_ind = 0, 0, 0 for i, l in enumerate(s): if l in letter_locs: from_ind = from_ind if from_ind > letter_locs[l] else letter_locs[l] cur = i - from_ind else: cur += 1 letter_locs[l] = i best = cur if cur > best else best return best print(lengthOfLongestSubstring("abccbade")) print(lengthOfLongestSubstring("abba")) print(lengthOfLongestSubstring(""))
true
052bcd3e8b2293371303450d3281f56c98498521
harish-515/Python-Projects
/Tkinter/script1.py
1,203
4.375
4
from tkinter import * #GUI are generated using window & widgets window = Tk() """ def km_to_miles(): print(e1_value.get()) miles = float(e1_value.get())*1.6 t1.insert(END,miles) b1=Button(window,text="Execute",command=km_to_miles) # pack & grid are used to make these button to visible b1.grid(row=0,column=0) e1_value=StringVar() e1=Entry(window,textvariable=e1_value) e1.grid(row=0,column=1) t1 = Text(window,height=1,width=20) t1.grid(row=0,column=2) """ def kg_to_others(): grams.delete("1.0",END) pounds.delete("1.0",END) ounces.delete("1.0",END) grams.insert(END,float(kg.get())*1000) pounds.insert(END,float(kg.get())*2.20426) ounces.insert(END,float(kg.get())*35.274) kg_label = Label(window,text="Kgs : ") kg_value = StringVar() kg = Entry(window,textvariable=kg_value) grams = Text(window,height=1,width=20) pounds = Text(window,height=1,width=20) ounces = Text(window,height=1,width=20) convertbtn = Button(window,text="Convert",command=kg_to_others) kg_label.grid(row=0,column=0) kg.grid(row=0,column=1) convertbtn.grid(row=0,column=2) grams.grid(row=1,column=0) pounds.grid(row=1,column=1) ounces.grid(row=1,column=2) window.mainloop()
true
c932c15d1ecdfe595d96f532b83a11d02a9ef341
oclaumc/Python
/ex001ex002.py
431
4.3125
4
#Desafio 1 e 2 #Hello World / Exibir / inserção de variaves / formatação de objetos nome = input ("Qual seu nome?") print ("olá {}, prazer te conhecer!".format(nome)) print ("Qual sua data de nascimento?") dia = input ("Dia:") mes = input ("Mês:") ano = input ("Ano") #print ("Você nasceu no dia",dia,"do mês",mes,"do ano de",ano,".""Correto?") print ('Você nasceu no dia {} de {} de {}, correto?'.format(dia, mes, ano))
false
51f27da75c6d55eeddacaa9cef05a3d1d97bb0db
r-fle/ccse2019
/level3.py
1,500
4.21875
4
#!/usr/bin/env python3 from pathlib import Path import string ANSWER = "dunno_yet" ########### # level 3 # ########### print("Welcome to Level 3.") print("Caeser cipher from a mysterious text file") print("---\n") """ There is text living in: files/mysterious.txt You've got to try and figure out what the secret message contained in it is. The enemy have hidden it in between lots of junk, but one of our operatives suspects it may contain references to a computer scientist born in 1815. """ # TASK: # Load the file. Find the hidden message and decrypt it. # Feel free to copy in any code from previous levels that you need. # EXAMPLE CODE: # 1. Tell python where our file is # 2. Read in the file content # 3. Split the file content up into lines f = Path(__file__).parent / "files" / "mysterious.txt" content = f.read_text() all_lines = content.split("\n") # Let's check out the first 5 lines. What's in this file? for i in range(5): print(all_lines[i]) print() # Time to do some secret message hunting... for line in all_lines: # Something goes here, right? print(".", end="") print("\n") print("The solution is:", ANSWER) ################### # level 3 - bonus # ################### # TASK # Depending how you accomplished the above, there might have been another solution. # Did you encrypt first, or decrypt first? # TASK # What would you do if you didn't know any of the plaintext content? # Is there a way to score how likely it is that a given result is correct?
true
8b8bd85ec48ddd120a6438354affb7372e689c99
Sparkoor/learning
/start/collectionsTest.py
1,708
4.125
4
""" collections测试 """ from collections import namedtuple p = (1, 2, 3, 4, 5) print(type(p)) print(p) # 可以定义坐标之类的,并且保证不可变,Point tuple的一个子类 Point = namedtuple('name', ['x', 'y']) print(Point) # <class '__main__.name'> name的一个实例 print(type(Point)) p = Point(1, 2) print(p) q = Point(2, 3) print(q) # 使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了, # 因为list是线性存储,数据量大的时候,插入和删除效率很低。 # deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈: from collections import deque l = deque(['a', 'b', 'c']) print(type(l)) # 不是list的子类 print(isinstance(l, list)) print(type(deque)) print(isinstance(deque, list)) # 双向插入 l.append('f') l.appendleft('g') # 主要作用插入时,不用检查已经存在的key,当存在时直接进行插入 from collections import defaultdict s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('yellow', 3), ('blue', 4), ('red', 1)] # 接受一个对象 d = defaultdict(list) for key, value in s: d[key].append(value) # 保持Key的顺序 from collections import OrderedDict # 简单的计数器,统计字符出现的次数,key-value 的形式,是dict的子类 from collections import Counter c = Counter() for ch in 'programming': # c[ch] = c[ch] + 1 c.update(ch) c.update('p') c.update('p') print(c['p']) print(sum(c.values())) d = Counter() print(c) for i in c: d.update(i) for i in c: d.update(i) print(d) print(len(d.keys())) print(sum(d.values())) l=Counter() for i in [1,2,3,3]: l.update(str(i)) print(l) print(sum(l.values()))
false
59b53e13a6f8bb9d2d606de898fc92738e5bd10b
imyoungmin/cs8-s20
/W3/p6.py
692
4.125
4
''' Write a program which takes 5 strings as inputs and appends them to a list l. Swap each element in l with its mirror - that is, for some element at index i, swap l[i] with l[4-i] if i < 3. For instance, if l = ['Alex', 'Bob', 'Charlie', 'David', 'Ethan'], then after swapping, l should read ['Ethan', 'David', 'Charlie', 'Bob', 'Alex'] Finally, finish the program by creating a dictionary mapping each name to its length. ''' # Solution here l = [] while len(l) < 5: l.append(input("Enter a name: ")) temp = l[0] temp1 = l[1] l[0] = l[4] l[1] = l[3] l[3] = temp1 l[4] = temp print(l) name_to_length = {} for name in l: name_to_length[name] = len(name) print(name_to_length)
true
952628cbcb0b3bcffc567eebd19a4b4b2477fa1f
Grace-TA/project-euler
/solutions/problem_004.py
611
4.125
4
from utils import is_palindromic def problem_004(n_digits: int = 3): """ In a loop from sqrt(n) to 1 check if i is factor of n and i is a prime number. - O(n^2) time-complexity - O(1) space-complexity """ result = 0 for i in range(10**n_digits - 1, 10**(n_digits - 1) - 1, -1): for j in range(10**n_digits - 1, 10**(n_digits - 1) - 1, -1): n = i * j if n < result: continue if is_palindromic(n): result = n return result if __name__ == '__main__': print(f'Problem 4 solution: {problem_004()}')
false
73f585596248ef1b48fab824d5d8204911acf857
ssong86/UdacityFullStackLecture
/Python/Drawing_Turtles/draw_shapes_no_param.py
701
4.125
4
import turtle def draw_square(): window = turtle.Screen() window.bgcolor("pink") # creates a drawing GUI with red background color brad = turtle.Turtle() # drawing module brad.shape("turtle") brad.color("blue") brad.speed(2) for x in range (0,4): # runs from 0 to 3 (4-1) brad.forward(100) brad.right(90) x = x+1 angie = turtle.Turtle() angie.shape("arrow") angie.color("blue") angie.circle(100) scott = turtle.Turtle() scott.shape("turtle") scott.color("blue") scott.speed(2) for y in range (0,3): scott.forward(100) scott.left(120) y=y+1 window.exitonclick() draw_square()
false
c46fc22351db7e3fdafadde09aea6ae45b7c6789
rajatthosar/Algorithms
/Sorting/qs.py
1,682
4.125
4
def swap(lIdx, rIdx): """ :param lIdx: Left Index :param rIdx: Right Index :return: nothing """ temp = array[lIdx] array[lIdx] = array[rIdx] array[rIdx] = temp def partition(array, firstIdx, lastIdx): """ :param array: array being partitioned :param firstIdx: head of the array :param lastIdx: tail of the array :return: index of pivot element after sorting """ pivot = array[lastIdx] # Counter i is used as a marker to fill the array with all # elements smaller than pivot. At the end of the loop # pivot is swapped with the next position of i as all the # elements before pivot are smaller than it lowIdx = firstIdx - 1 # Note that range function stops the sequence generation at # lastIdx. This means that there will be # (lastIdx - firstIdx) - 1 elements in the sequence. # The last item generated in the sequence will be lastIdx - 1 for arrayIdx in range(firstIdx, lastIdx): if array[arrayIdx] <= pivot: lowIdx += 1 swap(lowIdx, arrayIdx) swap(lowIdx + 1, lastIdx) return lowIdx + 1 def quickSort(array, firstIdx, lastIdx): """ :param array: Array to be sorted :param firstIdx: head of the array :param lastIdx: tail of the array :return: sorted array """ if firstIdx < lastIdx: pivot = partition(array, firstIdx, lastIdx) quickSort(array, firstIdx, pivot - 1) quickSort(array, pivot + 1, lastIdx) print(array) if __name__ == "__main__": array = [10, 80, 30, 90, 40, 50, 70] firstIdx = 0 lastIdx = len(array) - 1 quickSort(array, firstIdx, lastIdx)
true
68fc5fd6c86607595d5eb547218c7a55781f3389
manjulive89/JanuaryDailyCode2021
/DailyCode01092021.py
1,381
4.5625
5
# ------------------------------------------- # Daily Code 01/09/2021 # "Functions" Lesson from learnpython.org # Coded by: Banehowl # ------------------------------------------- # Functions are a convenient way to divide your code into useful blocks, allowing order in the code, make it # more readable, reuse it, and save some time. Also fuctions are a key way to define interfaces so # programmers can share their code. # How to write functions in Python def my_function(): # Functions are define using the block keyword "def" print("Hello From My Function!") # Functions may also receive arguments (variables passed from the caller to the function) def my_function_with_args(username, greeting): print("Hello, %s, From My Function! I wish you %s" % (username, greeting)) # Fuctions may return a value to the caller, using the keyword "return" def sum_two_number(a, b): return a + b # To call functions in Python, simply write teh function's the name followed by (), placing any required # arguments within the bracket. Using the previous functions we defined: # print(a simple greeting) my_function() # prints - "Hello, Joe Doe, From My Function! I wish you a great year!" my_function_with_args("John Doe", "a great year!") # after this line x will hold the value 3 x = sum_two_number(1, 2) print(x)
true
9d1b835fd8b5e6aeadb4ff23d54c2bc0b5435b2f
manjulive89/JanuaryDailyCode2021
/DailyCode01202021.py
1,831
4.3125
4
# ----------------------------------------------- # Daily Code 01/20/2021 # "Serialization" Lesson from learnpython.org # Coded by: Banehowl # ----------------------------------------------- # Python provides built-in JSON libraries to encode and decode JSON # Python 2.5, the simplejson module is used, whereas in Python 2.7, the json module is used. # In order to use the json module, it must be imported: import json # There are two basic formats for JSON data. Either in a string or the object datastructure. # The object datastructure, in Python, consists of lists and dictionaries nested inside each other. # The object datastructure allows one to use python methods (for lists and dictionaries) to add, list, # search and remove elements from the datastructure. # # The String format is mainly used to pass the data into another program or load into a datastructure. # To load JSON back to a data structure, use the "loads" method. This method takes a string and turns # it back into the json object datastructure. To encode a data structure to JSON, use the "dumps" method. # This method takes an object and returns a String: json_string = json.dumps([1, 2, 3, "a", "b", "c"]) print(json.loads(json_string)) # Sample Code using JSON: # import json #it's already imported so... # fix this function, so it adds the given name # and salary pair to salaries_json, and return it def add_employee(salaries_json, name, salary): salaries = json.loads(salaries_json) salaries[name] = salary return json.dumps(salaries) # test code salaries = '{"Alfred" : 300, "Jane" : 400 }' new_salaries = add_employee(salaries, "Me", 800) decoded_salaries = json.loads(new_salaries) print(decoded_salaries["Alfred"]) print(decoded_salaries["Jane"]) print(decoded_salaries["Me"])
true
5cac576e1c3b2e1ecd67bfd71ab20bc765b4eee3
jtm192087/Assignment_8
/ps1.py
960
4.46875
4
#!/usr/bin/python3 #program for adding parity bit and parity check def check(string): #function to check for a valid string p=set(string) s={'0','1'} if s==p or p=={'0'} or p=={'1'}: print("It is a valid string") else: print("please enter again a valid binary string") if __name__ == "_main_" : string=input("please enter a valid binary string\n") check(string) #calling check function substring='1' count=string.count(substring) print("count is:",count) if count%2==0: #to add parity bit at the end of the binary data if no. one,s is even string=string+'1' print("The parity corrected data is: ",string) #print corrected data else: string=string+'0' print("The parity corrected data is: ",string) print("\n") string2=string.replace("010","0100") #replacing the '010' substring by '0100' print("The transmitting data is: ",string2)
true
a0c94fff02953dd66974b2476f299a4417e7605c
Gabrielgjs/python
/AnoAlistamento.py
600
4.1875
4
from datetime import date ano = int(input('Ano de nascimento: ')) atual = date.today().year alistamento = 18 idade: int = atual - ano print(f'Quem nasceu em {ano} tem {idade} anos em {atual}.') if idade == 18: print('voê tem que se alistar IMEDIATAMENTE!') elif idade > alistamento: saldo = idade - alistamento print(f'você deveria ter se alistado há {saldo} anos.') print(f'Seu alistamento foi em {atual - saldo}') elif idade < alistamento: saldo = alistamento - idade print(f'Seu alistamento será em {saldo} anos') print(f'Seu alistamento será em {atual + saldo}')
false
be982a03905d0ca95fe7e1b8c6bcdf7300b3a0e0
vit050587/Python-homework-GB-2
/lesson4.4.py
847
4.25
4
# 2. Вычисляет урон по отношению к броне. # Примечание. Функция номер 2 используется внутри функции номер 1 для вычисления урона и вычитания его из здоровья персонажа. player_name = input('Введите имя игрока') player = { 'name': player_name, 'health': 100, 'damage': 50, 'armor' : 1.2 } enemy_name = input('Введите врага') enemy = { 'name': enemy_name, 'health': 50, 'damage': 30, 'armor' : 1 } def get_damage(damage, armor): return damage / armor def attack(unit, target): damage = get_damage(unit['damage'], target['armor']) target['health'] -= unit['damage'] attack(player, enemy) print(enemy) attack(enemy, player) print(player)
false
578f3caf2d4247460b9331ae8f8b2a9cc56a4a74
EgorVyhodcev/Laboratornaya4
/PyCharm/individual.py
291
4.375
4
print("This program computes the volume and the area of the side surface of the Rectangular parallelepiped") a, b, c = input("Enter the length of 3 sides").split() a = int(a) b = int(b) c = int(c) print("The volume is ", a * b * c) print("The area of the side surface is ", 2 * c * (a + b))
true
2531327f966f606597577132fa9e54f7ed0be407
Rotondwatshipota1/workproject
/mypackage/recursion.py
930
4.1875
4
def sum_array(array): for i in array: return sum(array) def fibonacci(n): '''' this funtion returns the nth fibonacci number Args: int n the nth position of the sequence returns the number in the nth index of the fibonacci sequence '''' if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) def factorial(n): '''' this funtion returns the factorial of a give n intheger args: n it accepts an intger n as its argument returns : the number or the factorial of the given number '''' if n < 1: return 1 else: return n * factorial(n-1) def reverse(word): '''' this funtion returns a word in a reverse order args : word it accepts a word as its argument return: it returns a given word in a reverse order '''' if word == "": return word else: return reverse(word[1:]) + word[0]
true
338f94f012e3c673777b265662403e5ef05a5366
alyssaevans/Intro-to-Programming
/Problem2-HW3.py
757
4.3125
4
#Author: Alyssa Evans #File: AlyssaEvans-p2HW3.py #Hwk #: 3 - Magic Dates month = int(input("Enter a month (MM): ")) if (month > 12) or (month < 0): print ("Months can only be from 01 to 12.") day = int(input("Enter a day (DD): ")) if (month % 2 == 0) and (day > 30) or (day < 0): print("Incorrect amount of days for that month.") if (month % 2 != 0) and (day > 31) or (day < 0): print("Incorrect amount of days for that month") if (month == 2) and (day > 29): print("February has a maximum of 29 days.") year = int(input("Enter a year (YY): ")) if (year > 10): print("You have to enter a two digit year.") if (month * day == year): print("The date you chose is magic!") else: print("The date you chose isn't magic.")
true
ef8b3da9c09b5ca1ceb6acc12bd70209fa6dac39
alexandrelff/mundo1
/ex035.py
420
4.15625
4
#Desenvolva um programa que leia o comprimento de trÊs retas e diga ao usuário se elas podem ou não formar um triângulo r1 = int(input('Digite o valor da reta 1: ')) r2 = int(input('Digite o valor da reta 2: ')) r3 = int(input('Digite o valor da reta 3: ')) if (r1 < r2 + r3) and (r2 < r1 + r3) and (r3 < r1 + r2): print('As retas formam um triângulo!!') else: print('As retas não formam um triângulo.')
false
3b0f3bd8d100765ae7cb593a791c9f2908b1ce76
rossvalera/inf1340_2015_asst2
/exercise1.py
2,159
4.1875
4
#!/usr/bin/env python """ Assignment 2, Exercise 1, INF1340, Fall, 2015. Pig Latin This module converts English words to Pig Latin words """ __author__ = 'Sinisa Savic', 'Marcos Armstrong', 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def pig_latinify(word): """ This function will translate any English word to Pig latin :param word: Any word using the alphabet :return: The word will get translated to Pig Latin If the first letter is a vowel will add "yay" to the end If the first letter is a consonant will take all consonants up until teh worst vowel and add them to the end with "ay" added """ # variables defined and used within code original = word.lower() pig = "yay" # For this assignment we will consider y a vowel always vowel = ["a", "e", "i", "o", "u"] index = 0 found_letter = -1 # Makes sure that all inputs are actual letters and not numbers if len(original) > 0 and original.isalpha(): # Checks each letter of a given word to until first vowel is found for i in original: if i in vowel: found_letter = index break index += 1 # no vowel found thus will return given word with "ay" at the end if found_letter == -1: no_vowel = original + pig[1:] return no_vowel # When first letter in the given word is a vowel will return the word with "yay" at the end elif found_letter == 0: first_vowel = original + pig return first_vowel # Will take all consonants up until the vowel in a word # Will return the word starting with the vowel and will add the removed consonants and "ay" to the end else: first_consonant = original[found_letter:] + original[0:found_letter] + pig[1:] return first_consonant # Any word that doesnt only use alphabetical characters will return "try again" # No input will also return "try again" else: return "try again" # Function Commented out # print(pig_latinify(""))
true
2591ae068b28c4d9e92470dd0348fabd32ee814a
CooperMetts/comp110-21f-workspace
/exercises/ex01/numeric_operators.py
852
4.25
4
"""Numeric operators practice.""" __author__ = "730336784" number_one: int = int(input("Pick a number ")) number_two: int = int(input("Pick another number ")) number_one_to_the_power_of_number_two: int = number_one ** number_two number_one_divided_by_number_two: float = number_one / number_two number_one_int_divided_by_number_two: int = number_one // number_two number_one_remainder_division_number_two: int = number_one % number_two print(str(number_one) + " ** " + str(number_two) + " is " + str(number_one_to_the_power_of_number_two)) print(str(number_one) + " / " + str(number_two) + " is " + str(number_one_divided_by_number_two)) print(str(number_one) + " // " + str(number_two) + " is " + str(number_one_int_divided_by_number_two)) print(str(number_one) + " % " + str(number_two) + " is " + str(number_one_remainder_division_number_two))
false
a00293978a88a612e4b7a3ea532d334f43a279d5
CooperMetts/comp110-21f-workspace
/sandbox/dictionaries.py
1,329
4.53125
5
"""Demonstrations of dictonary capabilities.""" # Declaring the type of a dictionary schools: dict[str, int] # Intialize to an empty dictonary schools = dict() # set a key value pairing in the dictionary schools["UNC"] = 19400 schools["Duke"] = 6717 schools["NCSU"] = 26150 # Print a dictonary literal representation print(schools) # Access a value by its key -- "lookup" print(f"UNC has {schools['UNC']} students.") # Remove a key-value pair from a dictonary by its key schools.pop("Duke") # Test for existence of a key # This is a boolean expression saying 'Duke' (the key) in schools (the dictonary) is_duke_present: bool = "Duke" in schools print(f"Duke is present: {is_duke_present}.") # Update / Reassign a key-value pair schools["UNC"] = 20000 schools["NCSU"] = schools["NCSU"] + 200 print(schools) # Demonstration of dictonary literals # Empty dictionary literal # This --> schools = {} is a dictionary literal and this --> dict() is a dictionary constructor schools = {} # Same as dict() # Alternatively, intiatlize key-value pairs schools = {"UNC": 19400, "Duke": 6717, "NCSU": 26150} print(schools) # What happens when a you try to access a key that does not exist: print(schools["UNCC"]) # Gives you KeyError: "UNCC" for school in schools: print(f"Key: {school} -> Value: {schools[school]}")
true
590cab46ee48d2e7380fd4025683f4321d9a1a34
dipak-pawar131199/pythonlabAssignment
/Introduction/SetA/Simple calculator.py
642
4.1875
4
# Program to make simple calculator num1=int(input("Enter first number: ")) num2=int(input("Enter second number: ")) ch=input(" Enter for opration symbol addition (+),substraction (-),substraction (*),substraction (/), % (get remainder) and for exit enter '$' ") if ch=='+': print("Sum is : ",num1+num2) if ch== "-": print("Difference is : ",num1-num2) if ch=='*': print("Multiplication is : ",num1*num2) if ch=='/': print("Division is : ",num1-num2) if ch=='%': print("Moduls is : ",num1%num2) if ch=='$': print("Buy");
true
86c83cf3af2c57cc3250540ec848a3d5924b6d4b
dipak-pawar131199/pythonlabAssignment
/Functions/Sumdigit.py
691
4.15625
4
(""" 1) Write a function that performs the sum of every element in the given number unless it comes to be a single digit. Example 12345 = 6 """) def Calsum(num): c=0;sum=0 while num>0: # loop for calcuating sum of digits of a number lastdigit=num%10 sum+=lastdigit num=num//10 k=sum while k>0:# loop for count number of digit of sum c=c+1 k=k//10 if c>1: # if digit count 'c' >1 Calsum(sum) # recursive call to Calsum() function else: print(sum) # display sum whose digit count is 1 num=int(input("Enter number: ")) Calsum(num)
true