blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
639d50d4d0579ee239adf72a08d7b4d78d9b91b6
blaise594/PythonPuzzles
/weightConverter.py
424
4.21875
4
#The purpose of this program is to convert weight in pounds to weight in kilos #Get user input #Convert pounds to kilograms #Display result in kilograms rounded to one decimal place #Get user weight in pounds weightInPounds=float(input('Enter your weight in pounds. ')) #One pound equals 2.2046226218 kilograms weightInKilos=weightInPounds/2.2046226218 print('Your weight in kilograms is: '+format(weightInKilos, '.1f'))
true
53439bc9fed95069408cec769fddd8fc2fc9376d
BryCant/Intro-to-Programming-MSMS-
/Chapter13.py
2,435
4.34375
4
# Exception Handling # encapsulation take all data associated with an object and put it in one class # data hiding # inheritance # polymorphism ; function that syntactically looks same is different based on how you use it """ # basic syntax try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except: # If any exception was raised, then execute this code block # catching specific exceptions try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except ExceptionName: # If ExceptionName was raise, then execute this block # catching multiple specific exceptions try: # Your normal code goes here. # Your code should include function calls which might raise exceptions. except Exception_one: # If Exception_one was raised, then execute this block except Exception_two: # If Exception_two was raised, then execute this block else: # If there was no exception, then execute this block # clean-up after exceptions (if you have code that you want to be executed even if exceptions occur) try: # Your normal code goes here. # Your code might include functions which might raise exceptions. # If an exception is raised, some of these statements might not be executed finally: # This block of code WILL ALWAYS execute, even if there are exceptions raised """ # example with some file I/O (great place to include exception handling try: # the outer try:except: block takes care of a missing file or the fact that the file can't be opened for writing f = open("my_file.txt", "w") try: # the inner: except: block protects against output errors, such as trying to write to a device that is full f.write("Writing some data to the file") finally: # the finally code guarantees that the file is closed properly, even if there are errors during writing f.close() except IOError: print("Error: my_file.txt does not exist or it can't be opened for output.") # as long as a function that is capable of handling an exception exists above where the exception is raised in the stack # the exception can be handled def main() A() def A(): B() def B(): C() def C(): # processes try: if condition: raise MyException except MyException: # what to do if this exception occurs
true
2679e524fb70ea8bc6a8801a3a9149ee258d9090
daviscuen/Astro-119-hw-1
/check_in_solution.py
818
4.125
4
#this imports numpy import numpy as np #this step creates a function called main def main(): i = 0 #sets a variable i equal to 0 x = 119. # sets a variable x equal to 119 and the decimal makes it a float (do you need the 0?) for i in range(120): #starting at i, add one everytime the program gets to the end of the for loop if (i%2) == 0: #if the value of i divided by 2 is exactly 0, then do the below part x += 3.0 #resets the variable x to 3 more than it was before else: # if the above condition is not true, do what is below x -= 5.0 #resets the variable x to 5 less than it was before s = "%3.2e" % x #puts it in sci notation (need help with why) print(s) #prints the above string s if __name__ == "__main__": main()
true
0d4aad51ef559c9bf11cd905cf14de63a6011457
mvinovivek/BA_Python
/Class_3/8_functions_with_return.py
982
4.375
4
#Function can return a value #Defining the function def cbrt(X): """ This is called as docstring short form of Document String This is useful to give information about the function. For example, This function computes the cube root of the given number """ cuberoot=X**(1/3) return cuberoot #This is returning value to the place where function is called print(cbrt(27)) #calling using a variable number=64 print("Cube root of {} is {}".format(number,cbrt(number))) #Mentioning Type of the arguments #Defining the function def cbrt(X: float) -> float: cuberoot=X**(1/3) return cuberoot #This is returning value to the place where function is called print(cbrt(50)) #Mutiple returns def calculation(X): sqrt=X**0.5 cbrt=X**(1/3) return sqrt,cbrt # print(calculation(9)) # values=calculation(9) # print(values) # values=calculation(9) # print(values[0]) # sqrt,cbrt=calculation(9) # print(sqrt,cbrt)
true
53cee6f939c97b0d84be910eee64b6e7f515b12f
mvinovivek/BA_Python
/Class_3/7_functions_with_default.py
680
4.1875
4
# We can set some default values for the function arguments #Passing Multiple Arguments def greet(name, message="How are you!"): print("Hi {}".format(name)) print(message) greet("Bellatrix", "You are Awesome!") greet("Bellatrix") #NOTE Default arguments must come at the last. All arguments before default are called positional arguments def greet(message="How are you!", name): #This will Throw error print("Hi {}".format(name)) print(message) #You can mix the positional values when using their name #Passing Multiple Arguments def greet(name, message): print("Hi {}".format(name)) print(message) greet( message="You are Awesome!",name="Bellatrix")
true
3cb1bc2560b5771e4c9ec69d429fcfd9c0eadd2c
mvinovivek/BA_Python
/Class_2/7_for_loop_2.py
1,009
4.625
5
#In case if we want to loop over several lists in one go, or need to access corresponding #values of any list pairs, we can make use of the range method # # range is a method when called will create an array of integers upto the given value # for example range(3) will return an array with elements [0,1,2] #now we can see that this is an array which can act as control variables #Combining this with the len function, we can iterate over any number of lists #Simple range example numbers=[1,2,3,4,6,6,7,8,9,10] squares=[] cubes=[] for number in numbers: squares.append(number**2) cubes.append(number**3) for i in range(len(numbers)): print("The Square of {} is {}".format(numbers[i], squares[i])) for i in range(len(numbers)): print("The Cube of {} is {}".format(numbers[i], cubes[i])) #Finding sum of numbers upto a given number number = 5 sum_value=0 for i in range(number + 1): sum_value = sum_value + i print("The sum of numbers upto {} is {}".format(number,sum_value))
true
c9a6c2f6b8f0655b3e417057f7e52015794d26d6
316126510004/ostlab04
/scramble.py
1,456
4.40625
4
def scramble(word, stop): ''' scramble(word, stop) word -> the text to be scrambled stop -> The last index it can extract word from returns a scrambled version of the word. This function takes a word as input and returns a scrambled version of it. However, the letters in the beginning and ending do not change. ''' import random pre, suf = word[0], word[stop:] word = list(word) mid_word = word[1:stop] random.shuffle(mid_word) word = pre + ''.join(mid_word) + suf return word def unpack_and_scramble(words): ''' unpack_and_scramble(words) words -> a list of words to be scrambled. returns a list of scrambled strings This function unpacks all the words and checks if len(word) < 3 If true then it scrambles the word Now, it will be appended to a new list ''' words = words.split() scrambled_words = [] for word in words: if len(word) <3: scrambled_words.append(word) continue if word.endswith((',', '?', '.', ';', '!')): stop = -2 else: stop = -3 scrambled_word = scramble(word, stop) scrambled_words.append(scrambled_word) return ' '.join(scrambled_words) file_name = input('Enter file name:') try: file = open(file_name, 'r') new_file = file.name + 'Scrambled' words = file.read() file.close() scrambed_words = unpack_and_scramble(words) file_name = open(new_file, 'w') file_name.write(scrambed_words) file_name.close() except OSError as ose: print('Please enter file name properly')
true
d24514f8bed4e72aaaee68ae96076ec3921f5898
ChanghaoWang/py4e
/Chapter9_Dictionaries/TwoIterationVariable.py
429
4.375
4
# Two iteration varibales # We can have multiple itertion variables in a for loop name = {'first name':'Changhao','middle name':None,'last name':'Wang'} keys = list(name.keys()) values = list(name.values()) items = list(name.items()) print("Keys of the dict:",keys) print("Values of the dict:",values) print("Items of the dict:",items) for key,value in items: # Two Itertion Values print('Keys and Values of the dict:',key)
true
6d325039a3caa4c331ecc6fa6bb058ff431218f8
ChanghaoWang/py4e
/Chapter8_Lists/note.py
921
4.21875
4
# Chapter 8 Lists Page 97 a = ['Changhao','Wang','scores',[100,200],'points','.'] # method: append & extend a.append('Yeah!') #Note, the method returns None. it is different with str a.extend(['He','is','so','clever','!']) # method : sort (arranges the elements of the list from low to high) b= ['He','is','clever','!'] b.sort() print(b) # method : delete (pop) retrus the element we removed. c = ['a',1,'c'] x = c.pop(0) print('After remove:',c) print('What we removed is:',x) # method : del c = ['a',1,'c'] del c[0] print(c) # method : remove attention: it can only remove one element c = ['a',1,'c',1] c.remove(1) print(c) # convert string to List d = 'Changhao' e = list(d) print(e) f = 'Changhao Wang' g = f.split() print(g) # string method : split() s = 'spam-spam-spam' s_new = s.split('-') print(s_new) # convert lists to string t = ['pining','for','the','fjords'] delimiter = ' ' t_str = delimiter.join(t) print(t_str)
true
d593ffafc59015480c713c213b59f6304914d660
Ayush10/python-programs
/vowel_or_consonant.py
1,451
4.40625
4
# Program to check if the given alphabet is vowel or consonant # Taking user input alphabet = input("Enter any alphabet: ") # Function to check if the given alphabet is vowel or consonant def check_alphabets(letter): lower_case_letter = letter.lower() if lower_case_letter == 'a' or lower_case_letter == 'e' or lower_case_letter == 'i' or lower_case_letter == 'o' \ or lower_case_letter == 'u': # or lower_case_letter == 'A' or lower_case_letter == 'E' or lower_case_letter == \ # 'I' or lower_case_letter == 'U': return "vowel" else: return "consonant" # Checking if the first character is an alphabet or not: if 65 <= ord(alphabet[0]) <= 90 or 97 <= ord(alphabet[0]) <= 122: # Checking if there are more than 1 characters in the given string. if len(alphabet) > 1: print("Please enter only one character!") print("The first character {0} of the given string {1} is {2}.".format(alphabet[0], alphabet, check_alphabets(alphabet[0]))) # If only one character in the given string. else: print("The given character {0} is {1}.".format(alphabet, check_alphabets(alphabet))) # If the condition is not satisfied then returning the error to the user without calculation. else: print("Please enter a valid alphabet. The character {0} is not an alphabet.".format(alphabet[0]))
true
2676477d211e0702d1c44802f9295e8457df21a8
Ayush10/python-programs
/greatest_of_three_numbers.py
492
4.3125
4
# Program to find greatest among three numbers # Taking user input a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = int(input("Enter third number: ")) # Comparison Algorithm and displaying result if a > b > c: print("%d is the greatest number among %d, %d and %d." % (a, a, b, c)) elif b > a > c: print("%d is the greatest number among %d, %d and %d." % (b, a, b, c)) else: print("%d is the greatest number among %d, %d and %d." % (c, a, b, c))
true
e50f8e37210054df2e5c54eb55e7dee381a91aff
super468/leetcode
/python/src/BestMeetingPoint.py
1,219
4.15625
4
class Solution: def minTotalDistance(self, grid): """ the point is that median can minimize the total distance of different points. the math explanation is https://leetcode.com/problems/best-meeting-point/discuss/74217/The-theory-behind-(why-the-median-works) the more human language version is that there are two groups of people, it will decrease the distance if you put the point closer to the group with more people. At end of the day, the two sides will be equal. :type grid: List[List[int]] :rtype: int """ list_y = [] list_x = [] for row in range(0, len(grid)): for col in range(0, len(grid[row])): if grid[row][col] == 1: list_y.append(row) list_x.append(col) list_y.sort() list_x.sort() median_y = list_y[int(len(list_y) / 2)] median_x = list_x[int(len(list_x) / 2)] sum_y = 0 for y in list_y: sum_y += median_y - y if median_y > y else y - median_y sum_x = 0 for x in list_x: sum_x += median_x - x if median_x > x else x - median_x return sum_x + sum_y
true
63825db8fd9cd5e9e6aaa551ef7bfec29713a925
Rohit439/pythonLab-file
/lab 9 .py
1,686
4.28125
4
#!/usr/bin/env python # coding: utf-8 # ### q1 # In[2]: class Triangle: def _init_(self): self.a=0 self.b=0 self.c=0 def create_triangle(self): self.a=int(input("enter the first side")) self.b=int(input("enter the second side")) self.c=int(input("enter the third side")) def print_sides(self): print("first side:",self.a,"second side:",self.b,"third side",self.c) x=Triangle() x.create_triangle() x.print_sides() # ### q2 # In[4]: class String(): def _init_(self): self.str1="" def inputstr(self): self.str1=input("enter the string") def printstr(self): print(self.str1) x=String() x.inputstr() x.printstr() # ### q3 # In[4]: class Rectangle: length=0.0 width=0.0 per=0.0 def rect_values(self,l,w): self.length=l self.width=w def perimeter(self): self.per=2*self.length+self.width return(self.per) r1=Rectangle() r1.rect_values(10,20) k=r1.perimeter() print("the perimeter of rectangle is",k) # ### q4 # In[6]: class Circle: radius=0.0 area=0.0 peri=0.0 def _init_(self,radius): self.radius=radius def area(self): self.area=3.14*self.radius*self.radius return(self.area) def perimeter(self): self.peri=2*3.14*self.radius return(self.peri) c1=Circle() c1._init_(4) a=c1.area() p=c1.perimeter() print("the area and perimeter of circle are:",a,p) # ### q5 # In[7]: class Class2: pass class Class3: def m(self): print("in class3") class Class4(Class2,Class3): pass obj=Class4() obj.m() # In[ ]:
true
2991c345efe646cedda8aeaeeebe06b2a4cc6842
drmason13/euler-dream-team
/euler1.py
778
4.34375
4
def main(): """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ test() print(do_the_thing(1000)) def do_the_thing(target): numbers = range(1, target) answer = [] for i in numbers: #print(i) if is_multiple_of(i, 3) or is_multiple_of(i, 5): answer.append(i) #ends here => i won't be a thing after this return(sum(answer)) def test(): result = do_the_thing(10) if result == 23: print("success") print(result) else: print("check again pinhead") print(result) def is_multiple_of(num, multiple): #print("is_multiple_of") return num % multiple == 0 main()
true
6f1aa43d0614cd211b0c92a48b182cf662e230fa
nmaswood/Random-Walk-Through-Computer-Science
/lessons/day4/exercises.py
720
4.25
4
def fib_recursion(n): """ return the nth element in the fibonacci sequence using recursion """ return 0 def fib_not_recursion(n): """ return the nth element in the fibonacci sequence using not recursion """ return 0 def sequence_1(n): """ return the nth element in the sequence S_n = S_{n-1} * 2 + 1 """ return 0 def factorial_recursive(n): """ Calculate the factorial of n using recursion """ return 0 class LinkedList(): def __init__(self, val): self.val = val self.next = None """ Use the LinkedList Data Type Create a linked list with the elements "fee" -> "fi" -> "foo" -> "fum" and print it backwards """
true
b976f86e302748c97bcd5033499a0f2a928bcbdc
taddes/python-blockchain
/data_structures_assignment.py
1,053
4.40625
4
# 1) Create a list of “person” dictionaries with a name, age and list of hobbies for each person. Fill in any data you want. person = [{'name': 'Taddes', 'age': 30, 'hobbies': ['bass', 'coding', 'reading', 'exercise']}, {'name': 'Sarah', 'age': 30, 'hobbies': ['exercise', 'writing', 'crafting']}, {'name': 'Pepper', 'age': 5, 'hobbies': ['hunting', 'eating plants', 'napping']}] # 2) Use a list comprehension to convert this list of persons into a list of names (of the persons). name_list = [name['name'] for name in person ] print(name_list) # 3) Use a list comprehension to check whether all persons are older than 20. age_check = all([age['age'] > 20 for age in person ]) print(age_check) # 4) Copy the person list such that you can safely edit the name of the first person (without changing the original list). copied_person = person[:] print(copied_person) print(person) # 5) Unpack the persons of the original list into different variables and output these variables. name, age, hobbies = person print(name) print(age)
true
7cdaebe77cfb044dfc16e01576311244caae283f
roshna1924/Python
/ICP1/Source Code/operations.py
590
4.125
4
num1 = int(input("Enter first number: ")) num2 = int(input("Enter Second number: ")) operation = int(input("Enter 1 for addition\n" "Enter 2 for Subtraction\n" "Enter 3 for multiplication\n" "Enter 4 for division\n")) def arithmeticOperations(op): switcher = { 1: "Result of addition : " + str(num1 + num2), 2: "Result of Subtraction : " + str(abs(num1 - num2)), 3: "Result of multiplication : " + str(num1 * num2), 4: "Result of division : " + str(num1 / num2) } print(switcher.get(op, "invalid operation\n")) arithmeticOperations(operation)
true
2185999943f7891d33a7519159d3d08feba8e14d
tim-jackson/euler-python
/Problem1/multiples.py
356
4.125
4
"""multiples.py: Exercise 1 of project Euler. Calculates the sum of the multiples of 3 or 5, below 1000. """ if __name__ == "__main__": TOTAL = 0 for num in xrange(0, 1000): if num % 5 == 0 or num % 3 == 0: TOTAL += num print "The sum of the multiples between 3 and 5, " \ "below 1000 is: " + str(TOTAL)
true
78b2dadaa067264258ed93da5a4e13ebf692ec6a
klq/euler_project
/euler41.py
2,391
4.25
4
import itertools import math def is_prime(n): """returns True if n is a prime number""" if n < 2: return False if n in [2,3]: return True if n % 2 == 0: return False for factor in range(3, int(math.sqrt(n))+1, 2): if n % factor == 0: return False return True def get_primes(maxi): """return a list of Booleans is_prime in which is_prime[i] is True if i is a prime number for every i <= maxi""" is_prime = [True] * (maxi + 1) is_prime[0] = False is_prime[1] = False # is_prime[2] = True and all other even numbers are not prime for i in range(2,maxi+1): if is_prime[i]: # if current is prime, set multiples to current not prime for j in range(2*i, maxi+1, i): is_prime[j] = False return is_prime def get_all_permutations(l): # returns n-length iterable object, n = len(l) # in lexical order (which means if input is [5,4,3,2,1], output will be in strictly decreasing order) return itertools.permutations(l) def list2num(l): s = ''.join(map(str, l)) return int(s) def get_sorted_pandigital(m): """returns a (reversed) sorted list of all pandigital numbers given m digits""" perms = get_all_permutations(range(m,0,-1)) for perm in perms: # per is a m-length tuple perm = list2num(perm) yield perm def euler41(): """https://projecteuler.net/problem=41 Pandigital Prime What is the largest n-digit pandigital prime that exists? """ # Method 1: -----Turns out 1.1 itself is too costly # 1. Get all the primes # 2. Get all the pandigital numbers (sorted) # 3. Test if prime from largest to smallest, stop when first one found # is_prime = get_primes(987654321) taking too long # Method 2: ---- # 1. Get all the pandigital numbers (sorted) # 2. Test if prime from largest to smallest, stop when first one found # !!! There will not be 8-digit or 9-digit pandigital prime numbers # !!! Because they are all divisible by 3! # !!! Only check 7-digit and 4-digit pandigital numbers for m in [7,4]: for pd in get_sorted_pandigital(m): if is_prime(pd): print pd return # Answer is: # 7652413 def main(): euler41() if __name__ == '__main__': main()
true
1ba8cda2d2376bd93a169031caa473825b3912da
QaisZainon/Learning-Coding
/Practice Python/Exercise_02.py
795
4.375
4
''' Ask the user for a number Check for even or odd Print out a message for the user Extras: 1. If number is a multiple of 4, print a different message. 2. Ask the users for two numbers, check if it is divisible, then print message according to the answer. ''' def even_odd(): num = int(input('Enter a number\n')) if num % 4 == 0: print('This number is divisible by 4') if num % 2 == 0: print('This is an even number') elif num % 2 == 1: print('This is an odd number') print('Give me two numbers,the first to check and the second to divide') check = int(input('Check number')) divide = int(input('Divider')) if num / divide == check: print('Correct!') else: print('Incorrect!') even_odd()
true
6426ac00f17c7d1c5879ddf994938cfa0a412e62
ChienSien1990/Python_collection
/Ecryption/Encrpytion(applycoder).py
655
4.375
4
def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers, and spaces. shift: 0 <= int < 26 returns: dict """ ### TODO myDict={} for i in string.ascii_lowercase: if((ord(i)+shift)>122): myDict[i] = chr(ord(i)+shift-26) else: myDict[i] = chr(ord(i)+shift) for i in string.ascii_uppercase: if((ord(i)+shift)>90): myDict[i] = chr(ord(i)+shift-26) else: myDict[i] = chr(ord(i)+shift) return myDict
true
1105fd4cb3e9b95294e5e918b0017e7f109d1aac
sujit4/problems
/interviewQs/InterviewCake/ReverseChars.py
1,023
4.25
4
# Write a function that takes a list of characters and reverses the letters in place. import unittest def reverse(list_of_chars): left_index = 0 right_index = len(list_of_chars) - 1 while left_index < right_index: list_of_chars[left_index], list_of_chars[right_index] = list_of_chars[right_index], list_of_chars[left_index] left_index += 1 right_index -= 1 # Tests class Test(unittest.TestCase): def test_empty_string(self): list_of_chars = [] reverse(list_of_chars) expected = [] self.assertEqual(list_of_chars, expected) def test_single_character_string(self): list_of_chars = ['A'] reverse(list_of_chars) expected = ['A'] self.assertEqual(list_of_chars, expected) def test_longer_string(self): list_of_chars = ['A', 'B', 'C', 'D', 'E'] reverse(list_of_chars) expected = ['E', 'D', 'C', 'B', 'A'] self.assertEqual(list_of_chars, expected) unittest.main(verbosity=2)
true
72f12e63fbac4561a74211964ab031f5ffb29212
derick-droid/pythonbasics
/files.py
905
4.125
4
# checking files in python open("employee.txt", "r") # to read the existing file open("employee.txt", "a") # to append information into a file employee = open("employee.txt", "r") # employee.close() # after opening a file we close the file print(employee.readable()) # this is to check if the file is readable print(employee.readline()) # this helps read the first line print(employee.readline()) # this helps to read the second line after the first line print(employee.readline()[0]) # accessing specific data from the array # looping through a file in python for employees in employee.readline(): print(employee) # adding information into a file employee = open("employee.txt", "a") print(employee.write("\n derrick -- for ICT department")) employee.close() # re writing a new file or overwriting a file employee = open("employee1.txt", "w") employee.write("kelly -- new manager")
true
95a9f725607b5acc0f023b0a0af2551bec253afd
derick-droid/pythonbasics
/dictexer.py
677
4.90625
5
# 6-5. Rivers: Make a dictionary containing three major rivers and the country # each river runs through. One key-value pair might be 'nile': 'egypt'. # • Use a loop to print a sentence about each river, such as The Nile runs # through Egypt. # • Use a loop to print the name of each river included in the dictionary. # • Use a loop to print the name of each country included in the dictionary. rivers = { "Nile": "Egypt", "Amazon": "America", "Tana": "Kenya" } for river, country in rivers.items(): print(river + " runs through " + country) print() for river in rivers.keys(): print(river) print() for country in rivers.values(): print(country)
true
935e0579d7cbb2da005c6c6b1ab7f548a6694a86
derick-droid/pythonbasics
/slicelst.py
2,312
4.875
5
# 4-10. Slices: Using one of the programs you wrote in this chapter, add several # lines to the end of the program that do the following: # • Print the message, The first three items in the list are:. Then use a slice to # print the first three items from that program’s list. # • Print the message, Three items from the middle of the list are:. Use a slice # to print three items from the middle of the list. # • Print the message, The last three items in the list are:. Use a slice to print # the last three items in the list. numbers = [1, 3, 2, 4, 5, 6, 7, 8, 9] slice1 = numbers[:3] slice2 = numbers[4:] slice3 = numbers[-3:] print(f"The first three items in the list are:{slice1}") print(f"The items from the middle of the list are:{slice2}") print(f"The last three items in the list are:{slice3}") print() # 4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1 # (page 60). Make a copy of the list of pizzas, and call it friend_pizzas . # Then, do the following: # • Add a new pizza to the original list. # • Add a different pizza to the list friend_pizzas . # • Prove that you have two separate lists. Print the message, My favorite # pizzas are:, and then use a for loop to print the first list. Print the message, # My friend’s favorite pizzas are:, and then use a for loop to print the sec- # ond list. Make sure each new pizza is stored in the appropriate list. print() pizzas = ["chicago pizza", "new york_style pizza", "greek pizza", "neapolitans pizza"] friends_pizza = pizzas[:] pizzas.append("sicilian pizza") friends_pizza.append("Detroit pizza") print(f"my favourite pizzas are:{pizzas}") print() print(f"my friend favourite pizzas are:{friends_pizza}") print() print("my favourite pizzas are: ") for pizza in pizzas: print(pizza) print() print("my favourite pizzas are: ") for items in friends_pizza: print(items) print() # # 4-12. More Loops: All versions of foods.py in this section have avoided using # for loops when printing to save space. Choose a version of foods.py, and # write two for loops to print each list of foods. food_stuff = ["cake", "rice", "meat", "ice cream", "banana"] food = ["goat meat", "pilau", "egg stew", "fried", "meat stew"] for foodz in food_stuff: print(foodz) print() for itemz in food: print(itemz)
true
5a827e2d5036414682f468fac5915502a784f486
derick-droid/pythonbasics
/exerdic.py
2,972
4.5
4
# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the # name of a pet. In each dictionary, include the kind of animal and the owner’s # name. Store these dictionaries in a list called pets . Next, loop through your list # and as you do print everything you know about each print it rex = { "name" : "rex", "kind": "dog", "owner's name" : "joe" } pop = { "name" :"pop", "kind" : "pig", "owner's name": "vincent" } dough = { "name": "dough", "kind" : "cat", "owner's name" : "pamna" } pets = [rex, pop, dough ] for item in pets: print(item) print() # 6-9. Favorite Places: Make a dictionary called favorite_places . Think of three # names to use as keys in the dictionary, and store one to three favorite places # for each person. To make this exercise a bit more interesting, ask some friends # to name a few of their favorite places. Loop through the dictionary, and print # each person’s name and their favorite places. favorite_places = { "derrick": { "nairobi", "mombasa", "kisumu" }, "dennis":{ "denmark", "thika", "roman" }, "john": { "zambia", "kajiado", "suna" } } for name, places in favorite_places.items(): # looping through the dictionary and printing only the name variable print(f"{name} 's favorite places are :") for place in places: # looping through the places variable to come up with each value in the variable print(f"-{place}") print() # 6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so # each person can have more than one favorite number. Then print each person’s # name along with their favorite numbers. favorite_number = { "derrick" : [1, 2, 3], "don" : [3, 5, 7], "jazzy" : [7, 8, 9] } for name, fav_number in favorite_number.items(): print(f"{name} favorite numbers are: ") for number in fav_number: print(f"-{number}") # 6-11. Cities: Make a dictionary called cities . Use the names of three cities as # keys in your dictionary. Create a dictionary of information about each city and # include the country that the city is in, its approximate population, and one fact # about that city. The keys for each city’s dictionary should be something like # country , population , and fact . Print the name of each city and all of the infor- # mation you have stored about it. cities = { "Nairobi" : { "population" : "1400000", "country" : "kenya", "facts" : "largest city in East Africa" }, "Dar-es-salaam" : { "population" : "5000000", "country" : "tanzania", "facts" : "largest city in Tanzania" }, "Kampala" : { "population" : "1000000", "country" : "Uganda", "facts" : "The largest city in Uganda" } } for city, information in cities.items(): print(f"{city}:") for fact,facts in information.items(): print(f"-{fact}: {facts}")
true
d65f32a065cc87e5de526a718aeea6d601e1ac06
derick-droid/pythonbasics
/iflsttry.py
2,930
4.5
4
# 5-8. Hello Admin: Make a list of five or more usernames, including the name # 'admin' . Imagine you are writing code that will print a greeting to each user # after they log in to a website. Loop through the list, and print a greeting to # each user: # • If the username is 'admin' , print a special greeting, such as Hello admin, # would you like to see a status report? # • Otherwise, print a generic greeting, such as Hello Eric, thank you for log- # ging in again. usernames = ["derick-admin", "Erick", "charles", "yusuf"] for name in usernames: if name == "derick-admin": print(f"Hello admin , would you like to see status report") else: print(f"Hello {name} , thank you for logging in again") # # 5-9. No Users: Add an if test to hello_admin.py to make sure the list of users is # not empty. # • If the list is empty, print the message We need to find some users! # • Remove all of the usernames from your list, and make sure the correct # message is printed. users = ["deno", "geogre", "mulla", "naomi"] users.clear() if users: for item in users: print(f"hello {item}") else: print("we need at least one user") print() # # 5-10. Checking Usernames: Do the following to create a program that simulates # how websites ensure that everyone has a unique username. # • Make a list of five or more usernames called current_users . # • Make another list of five usernames called new_users . Make sure one or # two of the new usernames are also in the current_users list. # • Loop through the new_users list to see if each new username has already # been used. If it has, print a message that the person will need to enter a # new username. If a username has not been used, print a message saying # that the username is available. # • # Make sure your comparison is case insensitive. If 'John' has been used, # 'JOHN' should not be accepted. web_users = ["derrick", "moses", "Raila", "john", "ojwang", "enock"] new_users = ["derrick", "moses", "babu", "vicky", "dave", "denver"] for user_name in new_users: if user_name in web_users: print("please enter a new user name ") else: print("the name already registered ") print() # 5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such # as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3. # • Store the numbers 1 through 9 in a list. # • Loop through the list. # • Use an if - elif - else chain inside the loop to print the proper ordinal end- # ing for each number. Your output should read "1st 2nd 3rd 4th 5th 6th # 7th 8th 9th" , and each result should be on a separate line ordinary_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for number in ordinary_numbers: if number == 1: print(f'{number}st') elif number == 2: print(f"{number}nd") elif number == 3: print(f"{number}rd") else: print(f"{number}th")
true
0ed70af907f37229379d7b38b7aaae938a7fc31a
adamkozuch/scratches
/scratch_4.py
584
4.15625
4
def get_longest_sequence(arr): if len(arr) < 3: return len(arr) first = 0 second = None length = 0 for i in range(1, len(arr)): if arr[first] == arr[i] or (second and arr[second]== arr[i]): continue if not second: second = i continue if i - first > length: length = i - first first = second second = i if len(arr) - first > length: length = len(arr) - first return length print(get_longest_sequence([1])) print(get_longest_sequence([5,1,2,1,2,5]))
true
0b303dde589390cf6795a2fc79ca473349c5e190
SeanLau/leetcode
/problem_104.py
1,203
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 此题可以先序遍历二叉树,找到最长的即可 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ depth = 0 if not root: return depth result = [] def preOrder(root, depth): # return root depth += 1 if root.left: preOrder(root.left, depth) if root.right: preOrder(root.right, depth) # yield depth if not (root.left and root.right): print("## depth in ===>", depth) result.append(depth) preOrder(root, depth) return max(result) if __name__ == '__main__': root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.right.right = TreeNode(3) root.right.left = TreeNode(4) so = Solution() print(so.maxDepth(root))
true
ef1ebb2ba1f95a2d8c09f3dc32af9d2ffec17499
CyberTaoFlow/Snowman
/Source/server/web/exceptions.py
402
4.3125
4
class InvalidValueError(Exception): """Exception thrown if an invalid value is encountered. Example: checking if A.type == "type1" || A.type == "type2" A.type is actually "type3" which is not expected => throw this exception. Throw with custom message: InvalidValueError("I did not expect that value!")""" def __init__(self, message): Exception.__init__(self, message)
true
c61d5128252a279d1f6c2b6f054e8ea1ead7b2af
rup3sh/python_expr
/general/trie
2,217
4.28125
4
#!/bin/python3 import json class Trie: def __init__(self): self._root = {} def insertWord(self, string): ''' Inserts word by iterating thru char by char and adding '*" to mark end of word and store complete word there for easy search''' node = self._root for c in string: if c not in node: node[c] = {} node = node[c] node['*'] = string def printTrie(self): node = self._root print(json.dumps(self._root, indent=2)) ##Utility methods def isWord(self, word): ''' check if word exists in trie''' node = self._root for c in word: if c not in node: return False node = node[c] # All chars were seen return True #EPIP, Question 24.20 def shortestUniquePrefix(self, string): '''shortest unique prefix not in the trie''' prefix = [] node = self._root for c in string: prefix.append(c) if c not in node: return ''.join(prefix) node = node[c] return '' def startsWithPrefix(self, prefix): ''' return suffixes that start with given prefix ''' # Simulating DFS def _dfs(node): stack = [] stack.append(node) temp = [] while stack: n = stack.pop() for c in n.keys(): if c == '*': #Word end found temp.append(n[c]) else: #Keep searching stack.append(n[c]) return temp ##Position node to the end of prefix list node = self._root for c in prefix: if c not in node: break node = node[c] return _dfs(node) def main(): t_list = "mon mony mont monty monday mondays tea ted teddy tom tony tori tomas tomi todd" words = t_list.split() trie = Trie() for word in words: trie.insertWord(word) #trie.printTrie() #Utility method test target = 'teal' #print(target, "Is in tree?", trie.isWord(target)) target = 'teddy' #print(target, "Is in tree?", trie.isWord(target)) target = 'temporary' #shortest_unique_not_in_trie = trie.shortestUniquePrefix(target) #print("shortest_unique_not_in_trie is :", shortest_unique_not_in_trie) suffixes = trie.startsWithPrefix('mon') print("Words starting with prefix:", suffixes) if __name__=="__main__":main()
true
23f20f17dc25cc3771922706260d43751f2584c5
rup3sh/python_expr
/generators/generator
1,446
4.34375
4
#!/bin/python3 import pdb import sys ##Reverses words in a corpus of text. def main(argv): generatorDemo() def list_of_even(n): for i in range(0,n+1): if i%2 == 0: yield i def generatorDemo(): try: x = list_of_even(10) print(type(x)) for i in x: print("EVEN:" + str(i)) the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"] #Print the reverse list print(the_list[::-1]) #list comprehension new_list = [ item.upper() for item in the_list ] print("NEWLIST:" + str(new_list)) #generator expression gen_object = (item.upper() for item in the_list) #You can also call next() on this generator object # Generator would call a StopIteration Execepton if you cannot call next anymore print(type(gen_object)) ##This yields the items one by one toa list newlist = list(gen_object) print("YET ANOTHER NEWLIST:" + str(new_list)) # As you can see, generator objects cannot be reused # So this would be empty one_more_list = list(gen_object) print("ONE MORE LIST:" + str(one_more_list)) # Capitalizes the word and reverses the word in one step ultimate_gen = (item[::-1] for item in (item.upper() for item in the_list)) print("ULTIMATE LIST:" + str(list(ultimate_gen))) except Exception as e: sys.stderr.write("Exception:{}".format(str(e))) if __name__ == "__main__":main(sys.argv[0:])
true
8fe1986f84ccd0f906095b651aa98ba62b2928b8
rup3sh/python_expr
/listsItersEtc/listComp
1,981
4.1875
4
#!/bin/python3 import pdb import sys ##Reverses words in a corpus of text. def main(argv): listComp() def listComp(): the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"] print(the_list[0:len(the_list)]) #Slicing #the_list[2:] = "paz" #['stanley', 'ave', 'p', 'a', 'z'] # This replaces everything from indexs 2 onwards #Everything except the last one #print(str(the_list[:-1])) #Prints 2, 3 only #print(str(the_list[2:4])) #Prints reverse -N onwards, but counting from 1 "los angeles", "istanbul", "moscow", "korea"] #print(str(the_list[-4:])) #Prints from start except last 4 ["stanley", "ave", "fremont", #print(str(the_list[:-4])) #Prints from start, skips odd positions ['ave', 'los angeles', 'moscow'] #print(str(the_list[1::2])) #Prints from reverse at 1, skips odd positions (only 'ave') #print(str(the_list[1::-2])) #the_list[3:3] = "California" #['stanley', 'ave', 'fremont', 'C', 'a', 'l', 'i', 'f', 'o', 'r', 'n', 'i', 'a', 'los angeles', 'istanbul', 'moscow', 'korea'] #Insert new list at a position #the_list[3:3] = ["California"] #['stanley', 'ave', 'fremont', 'California', 'los angeles', 'istanbul', 'moscow', 'korea'] # Modifies list to ['stanley', 'ave', 'fremont', 'California', 'moscow', 'korea'] #the_list[3:5] = ["California"] # Delete middle of the list ['stanley', 'ave', 'fremont','moscow', 'korea'] #the_list[3:5] = [] ##Add list to another list add_this = ["africa", "asia", "antarctica"] the_list.extend(add_this) #Insert in the list the_list.insert(4, 'alameda') #Delete an element by index x = the_list.pop(3) #Delete an element by name the_list.remove('moscow') print(str(the_list)) #In-place reversal the_list.reverse() print(str(the_list)) print("Index of africa is: "+ str(the_list.index('africa'))) # Count occurrence print(str(the_list.count('fremont'))) if __name__ == "__main__":main(sys.argv[0:])
true
3b597cae9208d703e6479525625da55ddc18b976
DahlitzFlorian/python-zero-calculator
/tests/test_tokenize.py
1,196
4.1875
4
from calculator.helper import tokenize def test_tokenize_simple(): """ Tokenize a very simple function and tests if it's done correctly. """ func = "2 * x - 2" solution = ["2", "*", "x", "-", "2"] assert tokenize.tokenize(func) == solution def test_tokenize_complex(): """ Tokenize a more complex function with different whitespaces and operators. It also includes functions like sin() and con(). """ func = "x*x- 3 /sin( x +3* x) + cos(9*x)" solution = [ "x", "*", "x", "-", "3", "/", "sin", "(", "x", "+", "3", "*", "x", ")", "+", "cos", "(", "9", "*", "x", ")", ] assert tokenize.tokenize(func) == solution def test_tokenize_exponential_operator(): """ Test if tokenizing a function including the exponential operator ** works as expected and that it does not add two times the multiplication operator to the final list. """ func = "2 ** 3 * 18" solution = ["2", "**", "3", "*", "18"] assert tokenize.tokenize(func) == solution
true
4b7dbbf640d118514fa306ca39a5ee336852aa05
francoischalifour/ju-python-labs
/lab9/exercises.py
1,777
4.25
4
#!/usr/bin/env python3 # coding: utf-8 # Lab 9 - Functional Programming # François Chalifour from functools import reduce def product_between(a=0, b=0): """Returns the product of the integers between these two numbers""" return reduce(lambda a, b: a * b, range(a, b + 1), 1) def sum_of_numbers(numbers): """Returns the sum of all the numbers in the list""" return reduce(lambda a, b: a + b, numbers, 0) def is_in_list(x, numbers): """Returns True if the list contains the number, otherwise False""" return any(filter(lambda n: n == x, numbers)) def count(numbers, x): """Returns the number of time the number occurs in the list""" return len(filter(lambda n: n == x, numbers)) def test(got, expected): """Prints the actual result and the expected""" prefix = '[OK]' if got == expected else '[X]' print('{:5} got: {!r}'.format(prefix, got)) print(' expected: {!r}'.format(expected)) def main(): """Tests all the functions""" print(''' ====================== LAB 9 ====================== ''') print('1. Multiplying values') test(product_between(0, 1), 0) test(product_between(1, 3), 6) test(product_between(10, 10), 10) test(product_between(5, 7), 210) print('\n2. Summarizing numbers in lists') test(sum_of_numbers([]), 0) test(sum_of_numbers([1, 1, 1]), 3) test(sum_of_numbers([3, 1, 2]), 6) print('\n3. Searching for a value in a list') test(is_in_list(1, []), False) test(is_in_list(3, [1, 2, 3, 4, 5]), True) test(is_in_list(7, [1, 2, 1, 2]), False) print('\n4. Counting elements in lists') test(count([], 4), 0) test(count([1, 2, 3, 4, 5], 3), 1) test(count([1, 1, 1], 1), 3) if __name__ == '__main__': main()
true
ba5bce618d68b7570c397bc50d6f96766b600fd9
francoischalifour/ju-python-labs
/lab4/exercises.py
1,024
4.1875
4
#!/usr/bin/env python3 # coding: utf-8 # Lab 4 - Dictionaries # François Chalifour def sums(numbers): """Returns a dictionary where the key "odd" contains the sum of all the odd integers in the list, the key "even" contains the sum of all the even integers, and the key "all" contains the sum of all integers""" sums = {'odd': 0, 'even': 0, 'all': 0} for x in numbers: if x % 2 == 0: sums['even'] += x else: sums['odd'] += x sums['all'] += x return sums def test(got, expected): """Prints the actual result and the expected""" prefix = '[OK]' if got == expected else '[X]' print('{:5} got: {!r}'.format(prefix, got)) print(' expected: {!r}'.format(expected)) def main(): """Tests all the functions""" print(''' ====================== LAB 4 ====================== ''') print('1. Computing sums') test(sums([1, 2, 3, 4, 5]), {"odd": 9, "even": 6, "all": 15}) if __name__ == '__main__': main()
true
a81ce65a4df9304e652af161f5a00534b35cc844
Abuubkar/python
/code_samples/p4_if_with_in.py
1,501
4.25
4
# IF STATEMENT # Python does not require an else block at the end of an if-elif chain. # Unlike C++ or Java cars = ['audi', 'bmw', 'subaru', 'toyota'] if not cars: print('Empty Car List') if cars == []: print('Empty Car List') for car in cars: if car == 'bmw': print(car.upper()) elif cars == []: # this condition wont run as if empty FOR LOOP won't run print('No car present') else: print(car.title()) age_0 = 10 age_1 = 12 if(age_0 > 1 and age_0 < age_1): print("\nYoung") if(age_1 > age_0 or age_1 >= 11): print("Elder") # Check presence in list car = 'bmw' print("\nAudi is presend in cars:- " + str('audi' in cars)) print(car.title()+" is presend in cars:- " + str(car in cars)+"\n") # Another way car = 'Suzuki' if car in cars: print(car+' is present') if car not in cars: print(car+' is not present\n') # it does not check presence in 'for loop' as output of cars is # overwritten by for loop # for car in cars : # print (car) # Checking Multiple List available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print("Adding " + requested_topping + ".") else: print("Sorry, we don't have " + requested_topping + ".") print("\nFinished making your pizza!")
true
b583554675d3ec46b424ac0e808a8281a339de67
NandanSatheesh/Daily-Coding-Problems
/Codes/2.py
602
4.21875
4
# This problem was asked by Uber. # # 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]. def getList(l): product = 1 for i in l: product *= i newlist = [product/i for i in l ] print(newList) return newList l = [1,2,3,4,5] getList(l) getList([3,2,1])
true
371ed66d667edb14d59347994462ddf30dde6a84
Liraz-Benbenishti/Python-Code-I-Wrote
/hangman/hangman/hangman-unit7/hangman-ex7.3.1.py
836
4.25
4
def show_hidden_word(secret_word, old_letters_guessed): """ :param secret_word: represent the hidden word the player need to guess. :param old_letters_guessed: the list that contain the letters the player guessed by now. :type secret_word: string :type old_letters_guessed: list :return: string that comprised of the letters and underscores. Shows the letter from the list that contained in the secret word in their location. rtype: string """ new_word = [] for letter in secret_word: if (letter in old_letters_guessed): new_word.append(letter) else: new_word.append("_") return " ".join(new_word) def main(): secret_word = "mammals" old_letters_guessed = ['s', 'p', 'j', 'i', 'm', 'k'] print(show_hidden_word(secret_word, old_letters_guessed)) if __name__ == "__main__": main()
true
fda16aa729c019888cb2305fcfb00d782e620db6
cnulenka/Coffee-Machine
/models/Beverage.py
1,434
4.34375
4
class Beverage: """ Beverage class represents a beverage, which has a name and is made up of a list of ingredients. self._composition is a python dict with ingredient name as key and ingredient quantity as value """ def __init__(self, beverage_name: str, beverage_composition: dict): self._name: str = beverage_name self._composition: dict = beverage_composition def get_name(self): return self._name def get_composition(self): return self._composition """ CANDIDATE NOTE: one other idea here was to make a abstract Beverage class and inherit and create child classes of hot_coffee, black_coffee, hot_tea etc where each of them over ride get_composition and store the composition info with in class. So orders will be a list of Beverage objects having child class instances. But this would hard code the composition and types of Beverages, hence extensibility will be affected, but may be we can have a custom child class also where user can create any beverage object by setting name and composition. Same approach can be followed for Ingredients Class. I don't have a Ingredients class though. Each ingredient can have a different warning limit, hence get_warning_limit will be implemented differently. For example water is most used resource so that can have a warning limit of 50% may be. -Shakti Prasad Lenka """
true
7762d9a8c0b8ebb97551f2071f9377fe896b686f
itstooloud/boring_stuff
/chapter_3/global_local_scope.py
922
4.1875
4
## ####def spam(): #### global eggs #### eggs = 'spam' #### ####eggs = 'global' ####spam() ####print(eggs) ## ####using the word global inside the def means that when you refer to that variable within ####the function, you are referring to the global variable and can change it. ## ####def spam(): #### global eggs #### eggs = 'spam' #this is a the global #### ####def bacon(): #### eggs = 'bacon' #this is a local variable #### ####def ham(): #### print(eggs) #this is the global #### ####eggs = 42 #this is the global ####spam() ####print(eggs) ## #### if you try to use a global variable inside a function without assigning a value to it, you'll get an error ## ##def spam(): ## print(eggs) #this will give an error ## ## eggs = 'spam local' ## ##eggs = 'global' ## ##spam() ## #### it only throws the error because the function assigns a value to eggs. Commenting it out should remove the error
true
f85f89d07de9f394d7f95646c0a490232bc3b7bc
whoismaruf/usermanager
/app.py
2,605
4.15625
4
from scripts.user import User print('\nWelcome to user management CLI application') user_list = {} def create_account(): name = input('\nSay your name: ') while True: email = input('\nEnter email: ') if '@' in email: temp = [i for i in email[email.find('@'):]] if '.' in temp: user = User(name, email) break else: print("\nInvalid Email address! Please enter the correct one.") continue else: print("\nInvalid Email address! Please enter the correct one.") continue uname = user.set_username() current_user = { 'name': name, 'email': email } while True: if uname in user_list: new_uname = input(f'\nSorry your username "{uname}" has been taken, choose another one: ') uname = new_uname.replace(" ", '') else: break user_list[f'{uname}'] = current_user print(f"\nHello, {name}! Your account has been created as {uname}.\n\nChoose what to do next - ") while True: user_input = input(''' A --> Create account S --> Show account info Q --> Quit ''') if user_input == 'A' or user_input == 'a': create_account() elif user_input == 'S' or user_input == 's': if len(user_list) == 0: print("\nThere is no account, please create one") continue else: while True: search = input('\nEnter username: ') if search not in user_list: print(f"\nYour searched '{search}' user not found.") pop = input(''' S --> Search again M --> Back to main menu ''') if pop == 'S' or pop == 's': continue elif pop == 'M' or pop == 'm': break else: print('Bad input') break else: res = user_list[search] print(f''' Account information for {search} Name: {res['name']} Email: {res['email']} ''') break elif user_input == 'Q' or user_input == 'q': break elif user_input == '': print('Please input something') continue else: print('\nBad input, try again\n')
true
4da19128caf20616ecbd36b297022b1d3ccb92ce
PraneshASP/LeetCode-Solutions-2
/234 - Palindrome Linked List.py
1,548
4.1875
4
# Solution: The idea is that we can reverse the first half of the LinkedList, and then # compare the first half with the second half to see if it's a palindrome. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if head is None or head.next is None: return True slow = head fast = head # Move through the list with fast and slow pointers, # when fast reaches the end, slow will be in the middle # Trick #1: At the same time we can also reverse the first half of the list tmp = slow.next while fast is not None and fast.next is not None: fast = fast.next.next prev = slow slow = tmp tmp = slow.next slow.next = prev head.next = None # Trick #2: If fast is None, the string is even length evenCheck = (fast is None) if evenCheck: if slow.val != slow.next.val: return False slow = slow.next.next else: slow = slow.next # Check that the reversed first half matches the second half while slow is not None: if tmp is None or slow.val != tmp.val: return False slow = slow.next tmp = tmp.next return True
true
869edf4c975e41ccdee0eacfbda1a636576578fc
jigarshah2811/Python-Programming
/Matrix_Print_Spiral.py
1,741
4.6875
5
""" http://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ Print a given matrix in spiral form Given a 2D array, print it in spiral form. See the following examples. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 spiral-matrix """ def print_spiral(matrix): '''matrix is a list of list -- a 2-d matrix.''' first_row = 0 last_row = len(matrix) - 1 first_column = 0 last_column = len(matrix[0]) - 1 while True: # Print first row for col_idx in range(first_column, last_column + 1): print(matrix[first_row][col_idx]) first_row += 1 if first_row > last_row: return # Print last column for row_idx in range(first_row, last_row + 1): print(matrix[row_idx][last_column]) last_column -= 1 if last_column < first_column: return # Print last row, in reverse for col_idx in reversed(range(first_column, last_column + 1)): print(matrix[last_row][col_idx]) last_row -= 1 if last_row < first_row: return # Print first column, bottom to top for row_idx in reversed(range(first_row, last_row + 1)): print(matrix[row_idx][first_column]) first_column += 1 if first_column > last_column: return if __name__ == '__main__': mat = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]] print_spiral(mat)
true
4a5fc85b209138408683797ef784cbd59dd978fe
jigarshah2811/Python-Programming
/LL_MergeSort.py
2,556
4.625
5
# Python3 program merge two sorted linked # in third linked list using recursive. # Node class class Node: def __init__(self, data): self.data = data self.next = None # Constructor to initialize the node object class LinkedList: # Function to initialize head def __init__(self): self.head = None # Method to print linked list def printList(self): temp = self.head while temp: print temp.data temp = temp.next # Function to add of node at the end. def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node def splitList(head): slow = fast = head while fast: fast = fast.next if fast is not None: fast = fast.next slow = slow.next # Now, Fast is at End and Slow is at Middle A = head B = slow slow.next = None return A, B def mergeSort(head): if head is None or head.next is None: return head # Split unsorted list into A and B A, B = splitList(head) # Indivudally sort A and B mergeSort(A) mergeSort(B) # Now we have 2 sorted lists, A & B, merge them return mergeLists(A, B) # Function to merge two sorted linked list. def mergeLists(A, B): tail = None if A is None: return B if B is None: return A if A.data < B.data: tail = A tail.next = mergeLists(A.next, B) else: tail = B tail.next = mergeLists(A, B.next) return tail # Driver Function if __name__ == '__main__': # Create linked list : # 10->20->30->40->50 list1 = LinkedList() list1.append(3) list1.append(5) list1.append(7) # Create linked list 2 : # 5->15->18->35->60 list2 = LinkedList() list2.append(1) list2.append(2) list2.append(4) list2.append(6) # Create linked list 3 list3 = LinkedList() # Merging linked list 1 and linked list 2 # in linked list 3 list3.head = mergeLists(list1.head, list2.head) print(" Merged Linked List is : ") list3.printList() print "Testing MergeSort" # Create linked list 4 : # 5->2->1->4->3 list3 = LinkedList() list3.append(5) list3.append(2) list3.append(1) list3.append(4) list3.append(3) sortedList = mergeSort(list3.head) sortedList.printList()
true
28a8e6ee2b125056cfe0c3056d6e3a92ba5e4a65
sabeeh99/Batch-2
/fathima_ashref.py
289
4.28125
4
# FathimaAshref-2-HelloWorldAnimation import time def animation(word): """this function takes the input and displays it character by character with a delay of 1 second""" for i in word: time.sleep(1) print(i, end="") animation("Hello World")
true
d2f96447565c188fcc5fb24a24254dc68a2f5b60
hanucane/dojo
/Online_Academy/python-intro/datatypes.py
763
4.3125
4
# 4 basic data types # print "hello world" # Strings # print 4 - 3 # Integers # print True, False # Booleans # print 4.2 # Floats # print type("hello world") # Identify data type # print type(1) # print type(True) # print type(4.2) # Variables name = "eric" # print name myFavoriteInt = 8 myBool = True myFloat = 4.2 # print myFavoriteInt # print myBool # print myFloat # Objects # list => array (referred to as list in Python) # len() shows the length of the variable / object myList = [ name, myFavoriteInt, myBool, myFloat, [myBool, myFavoriteInt, myFloat] ] print len(myList) # Dictionary myDictionary = { "name": "Eric", "title": "Entrepenuer", "hasCar": True, "favoriteNumber": 8 } print myDictionary["name"]
true
eb392b54023303e56d23b76a464539b70f8ee6e8
shamim-ahmed/udemy-python-masterclass
/section-4/examples/guessinggame6.py
507
4.1875
4
#!/usr/bin/env python import random highest = 10 answer = random.randint(1, highest) is_done = False while not is_done: # obtain user input guess = int(input("Please enter a number between 1 and {}: ".format(highest))) if guess == answer: is_done = True print("Well done! The correct answer is {}".format(answer)) else: suggestion = "Please guess higher" if guess < answer else "Please guess lower" print(f"Sorry, your guess is incorrect. {suggestion}")
true
3d1946247a3518c4bd2128786609946be2ae768c
shamim-ahmed/udemy-python-masterclass
/section-4/exercises/exercise11.py
638
4.21875
4
#!/usr/bin/env python3 def print_option_menu(options): print("Please choose your option from the list below:\n") for i, option in enumerate(options): print("{}. {}".format(i, option)) print() if __name__ == "__main__": options = ["Exit", "Learn Python", "Learn Java", "Go swimming", "Have dinner", "Go to bed"] print_option_menu(options) done = False while not done: choice = int(input()) if choice == 0: done = True elif 0 < choice < len(options): print("You have entered {}".format(choice)) else: print_option_menu(options)
true
a40410c97ef48d989ce91b6d23262720f60138dc
rajeshberwal/dsalib
/dsalib/Stack/Stack.py
1,232
4.25
4
class Stack: def __init__(self): self._top = -1 self.stack = [] def __len__(self): return self._top + 1 def is_empty(self): """Returns True is stack is empty otherwise returns False Returns: bool: True if stack is empty otherwise returns False """ return self._top == -1 def push(self, data): """Add data at the end of the stack. Args: data (Any): element that we want to add """ self.stack.append(data) self._top += 1 def pop(self): """Remove the last element from stack and returns it's value. Raises: IndexError: If stack is empty raise an Index error Returns: Any: element that we have removed from stack""" if self.is_empty(): raise IndexError("stack is empty") self._top += 1 return self.stack.pop() def peek(self): """returns the current top element of the stack.""" if self.is_empty(): raise IndexError("stack is empty") return self.stack[self._top] def __str__(self): return ''.join([str(elem) for elem in self.arr])
true
04d70de92bfca1f7b293f344884ec1e23489b7e4
rajeshberwal/dsalib
/dsalib/Sorting/insertion_sort.py
547
4.375
4
def insertion_sort(array: list) -> None: """Sort given list using Merge Sort Technique. Time Complexity: Best Case: O(n), Average Case: O(n ^ 2) Worst Case: O(n ^ 2) Args: array (list): list of elements """ for i in range(1, len(array)): current_num = array[i] for j in range(i - 1, -1, -1): if array[j] > current_num: array[j], array[j + 1] = array[j + 1], array[j] else: array[j + 1] = current_num break
true
6705bd7dfa677bd27dbcf200aaa3f7dc6cd6cb55
laurenc176/PythonCrashCourse
/Lists/simple_lists_cars.py
938
4.5
4
#organizing a list #sorting a list permanently with the sort() method, can never revert #to original order cars = ['bmw','audi','toyota','subaru'] cars.sort() print(cars) #can also do reverse cars.sort(reverse=True) print(cars) # sorted() function sorts a list temporarily cars = ['bmw','audi','toyota','subaru'] print("Here is the orginal list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the original list again:") print(cars) # Can print a list in reverse order using reverse() method, changes it permanently # doesnt sort backward alphabetically, simply reverses order of the list cars = ['bmw','audi','toyota','subaru'] print(cars) cars.reverse() print(cars) #other methods I already know: len(cars) # length of the list cars[-1] # using -1 as an index will always return the last item in a list unless list is empty, then will get an error
true
68654f6011396a2f0337ba2d591a7939d609b3ed
laurenc176/PythonCrashCourse
/Files and Exceptions/exceptions.py
2,711
4.125
4
#Handling exceptions #ZeroDivisionError Exception, use try-except blocks try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") #Using Exceptions to Prevent Crashes print("Give me two numbers, and I'll divide them") print("Enter 'q' to quit.") #This will crash if second number is 0 while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("\nSecond number: ") if second_number == 'q': break answer = int(first_number) / int(second_number) #Prevent crash: while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("\nSecond number: ") if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by zero!") else: print(answer) #FileNotFoundError Exception try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print(f"Sorry, the file {filename} does not exist") #Analyzing Text #Many classic lit are available as simple text files because they are in public domain #Texts in this section come from Project Gutenberg(http://gutenberg.org/) title = "Alice in Wonderland" title.split() filename = 'alice.txt' try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print(f"Sorry, the file {filename} does not exist") else: #Count the approx number of words in the file. words = contents.split() num_words = len(words) print(f"The file {filename} has about {num_words} words.") #Working with Multiple files, create a function def count_words(filename): """Count the approx number of words in the file.""" try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print(f"Sorry, the file {filename} does not exist") else: words = contents.split() num_words = len(words) print(f"The file {filename} has about {num_words} words.") filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: count_words(filename) #Fail silently - you don't need to report every exception #write a block as usual, but tell Python to do nothing in the except block: def count_words(filename): """Count the approx number of words in the file.""" try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: pass #will fail silently, acts as a placeholder else: words = contents.split() num_words = len(words) print(f"The file {filename} has about {num_words} words.")
true
fbc01f2c549fae60235064d839c55d98939ae775
martinskillings/tempConverter
/tempConverter.py
2,231
4.3125
4
#Write a program that converts Celsius to Fahrenheit or Kelvin continueLoop = 'f' while continueLoop == 'f': celsius = eval(input("Enter a degree in Celsius: ")) fahrenheit = (9 / 5 * celsius + 32) print(celsius, "Celsius is", format(fahrenheit, ".2f"), "Fahrenheit") #User prompt to switch to different temperature setting or terminate program continueLoop = input("Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: ") if continueLoop == 'k': celsius = eval(input("Enter a degree in Celsius: ")) kelvin = celsius + 273.15 print(celsius, "Celsius is", format(kelvin, ".2f"), "Kelvin") continueLoop = input("Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: ") if continueLoop == 'q': print ("Good-Bye") ''' Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> RESTART: C:/Users/marti/AppData/Local/Programs/Python/Python36-32/tempConverter.py Enter a degree in Celsius: 43 43 Celsius is 109.40 Fahrenheit Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k Enter a degree in Celsius: 43 43 Celsius is 316.15 Kelvin Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f Enter a degree in Celsius: 0 0 Celsius is 32.00 Fahrenheit Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k Enter a degree in Celsius: 0 0 Celsius is 273.15 Kelvin Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f Enter a degree in Celsius: 100 100 Celsius is 212.00 Fahrenheit Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k Enter a degree in Celsius: 100 100 Celsius is 373.15 Kelvin Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f Enter a degree in Celsius: 37 37 Celsius is 98.60 Fahrenheit Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k Enter a degree in Celsius: 37 37 Celsius is 310.15 Kelvin Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: q Good-Bye >>> '''
true
d5a296818f6bd02b8c03c76b2aa042abbcb4ee17
AlexanderOHara/programming
/week03/absolute.py
336
4.15625
4
# Give the absolute value of a number # Author Alexander O'Hara # In the question, number is ambiguous but the output implies we should be # dealing with floats so I am casting the input to a flat number = float (input ("Enter a number: ")) absoluteValue = abs (number) print ('The absolute value of {} is {}'. format (number, absoluteValue))
true
faf268ea926783569bf7e2714589f264ed4f3554
Teddy-Sannan/ICS3U-Unit2-02-Python
/area_and_perimeter_of_circle.py
606
4.1875
4
#!/usr/bin/env python3 # Created by: Teddy Sannan # Created on: September 16 # This program calculates the area and perimeter of a rectangle def main(): # main function print("We will be calculating the area and perimeter of a rectangle") print("") # input length = int(input("Enter the length (mm): ")) width = int(input("Enter the width (mm): ")) # process perimeter = 2 * (length + width) area = length * width print("") # output print("Perimeter is {} mm".format(perimeter)) print("Area is {} mm^2".format(area)) if __name__ == "__main__": main()
true
158450f4cb59c6890e6de4931de18e66a4f5ef48
FraserTooth/python_algorithms
/01_balanced_symbols_stack/stack.py
865
4.21875
4
class Stack: def __init__(self): self.items = [] def push(self, item): """Adds an item to end Returns Nothing Time Complexity = O(1) """ self.items.append(item) def pop(self): """Removes Last Item Returns Item Time Complexity = O(1) """ if self.items: return self.items.pop() return None def peek(self): """Returns Last Item Time Complexity = O(1) """ if self.items: return self.items[-1] return None def size(self): """Returns Size of Stack Time Complexity = O(1) """ return len(self.items) def is_empty(self): """Returns Boolean of whether list is empty Time Complexity = O(1) """ return self.items == []
true
14d98d23d3617c08a2aefd1b4ced2d80c5a9378c
168959/Datacamp_pycham_exercises2
/Creat a list.py
2,149
4.40625
4
# Create the areas list areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Print out second element from areas" print(areas[1]) "# Print out last element from areas" print(areas[9]) "# Print out the area of the living room" print(areas[5]) "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Sum of kitchen and bedroom area: eat_sleep_area" eat_sleep_area = areas[3] + areas[-3] "# Print the variable eat_sleep_area" print(eat_sleep_area) "#Subset and calculate" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Sum of kitchen and bedroom area: eat_sleep_area" eat_sleep_area = areas[3] + areas[-3] "# Print the variable eat_sleep_area" print(eat_sleep_area) "#Slicing and dicing" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Use slicing to create downstairs" downstairs = areas[0:6] "# Use slicing to create upstairs" upstairs = areas[6:10] "# Print out downstairs and upstairs" print(downstairs) print(upstairs) "# Alternative slicing to create downstairs" downstairs = areas[:6] "# Alternative slicing to create upstairs" upstairs = areas[-4:] "#Replace list elements" "# Create the areas list" areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] "# Correct the bathroom area" areas[-1] = 10.50 # Change "living room" to "chill zone" areas[4] = "chill zone" "#Extend a list" areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0, "bedroom", 10.75, "bathroom", 10.50] "# Add poolhouse data to areas, new list is areas_1" areas_1 = areas + ["poolhouse", 24.5] "# Add garage data to areas_1, new list is areas_2" areas_2 = areas_1 + ["garage", 15.45] "#Inner workings of lists" "# Create list areas" areas = [11.25, 18.0, 20.0, 10.75, 9.50] "# Create areas_copy" areas_copy = list(areas) "# Change areas_copy" areas_copy[0] = 5.0 "# Print areas" print(areas)
true
a65aa34ef32d7fced8a91153dae77e48f5cc1176
2019-fall-csc-226/a02-loopy-turtles-loopy-languages-henryjcamacho
/Camachoh- A02.py
1,133
4.15625
4
###################################################################### # Author: Henry Camacho TODO: Change this to your name, if modifying # Username: HenryJCamacho TODO: Change this to your username, if modifying # # Assignment: A02 # Purpose: To draw something we lie with loop ###################################################################### # Acknowledgements: # # original from # # licensed under a Creative Commons # Attribution-Noncommercial-Share Alike 3.0 United States License. ###################################################################### import turtle wn = turtle.Screen() circle = turtle.Turtle() circle.speed(10) circle.fillcolor("yellow") circle.begin_fill() for face in range(75): circle.forward(10) circle.right(5) circle.end_fill() eyes = turtle.Turtle() eyes.speed(10) eyes.penup() eyes.setpos(50, -50) eyes.shape("triangle") eyes.stamp() eyes.setpos (-50, -50) mouth = turtle.Turtle() mouth.speed(10) mouth.penup() mouth.setpos(-50, -100) mouth.pendown() mouth.right(90) for smile in range(30): mouth.forward(5) mouth.left(5) wn.exitonclick()
true
5c703ed90acda4eaba3364b6f510d28622ddc4a0
ndenisj/web-dev-with-python-bootcamp
/Intro/pythonrefresher.py
1,603
4.34375
4
# Variables and Concatenate # greet = "Welcome To Python" # name = "Denison" # age = 6 # coldWeather = False # print("My name is {} am {} years old".format(name, age)) # Concatenate # Comment: codes that are not executed, like a note for the programmer """ Multi line comment in python """ # commentAsString = """ # This is more like # us and you can not do that with me # or i will be mad # """ # print(commentAsString) # If statement # if age > 18: # print("You can VOTE") # elif age < 10: # print("You are a baby") # else: # print("You are too young") # FUNCTIONS # def hello(msg, msg2=""): #print("This is a function - " + msg) # hello("Hey") # hello("Hey 2") # LIST - Order set of things like array # names = ["Dj", "Mike", "Paul"] # names.insert(1, "Jay") # # print(names[3]) # # del(names[3]) # # print(len(names)) # length # names[1] = "Peter" # print(names) # LOOPS # names = ["Dj", "Mike", "Paul"] # for name in names: # #print(name) # for x in range(len(names)): # print(names[x]) # for x in range(0, 5): # print(x) # age = 2 # while age < 3: # print(age) # age += 1 # DICTIONARY # allnames = {'Paul': 23, 'Patrick': 32, 'Sally': 12} # print(allnames) # print(allnames['Sally']) # CLASSES # class Dog: # dogInfo = 'Dogs are cool' # # Constructor of the class # def __init__(self, name, age): # self.name = name # self.age = age # def bark(self): # print('Bark - ' + self.dogInfo) # myDog = Dog("Denis", 33) # create an instance or object of the Dog Class # myDog.bark() # print(myDog.age)
true
61e6633eeadf4384a18603640e30e0fa0a6998c8
suyash248/ds_algo
/Array/stockSpanProblem.py
959
4.28125
4
from Array import empty_1d_array # References - https://www.geeksforgeeks.org/the-stock-span-problem/ def stock_span(prices): # Stores index of closest greater element/price. stack = [0] spans = empty_1d_array(len(prices)) # Stores the span values, first value(left-most) is 1 as there is no previous greater element(price) available. spans[0] = 1 # When we go from day i-1 to i, we pop the days when the price of the stock was less than or equal to price[i] and # then push the value of day i back into the stack. for i in range(1, len(prices)): cur_price = prices[i] while len(stack) != 0 and prices[stack[-1]] <= cur_price: stack.pop() spans[i] = (i+1) if len(stack) == 0 else (i-stack[-1]) stack.append(i) return spans if __name__ == '__main__': prices = [10, 4, 5, 90, 120, 80] spans = stock_span(prices) print("Prices:", prices) print("Spans:", spans)
true
d21394227d4390b898fc1588593e43616ed7e502
suyash248/ds_algo
/Misc/sliding_window/substrings_with_distinct_elt.py
2,324
4.125
4
''' Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c. Example 1: Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). Example 2: Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". Example 3: Input: s = "abc" Output: 1 Constraints: 3 <= s.length <= 5 x 10^4 s only consists of a, b or c characters. ''' def __num_substrings_brute_force__(s: str) -> int: k = 3 res = 0 substr = dict() for i in range(min(k, len(s))): substr[s[i]] = substr.get(s[i], 0) + 1 if len(substr) == k: res += 1 for i in range(0, len(s) - k): left_elt = s[i] right_elt = s[i + k] substr[right_elt] = substr.get(right_elt, 0) + 1 if substr.get(left_elt) > 0: substr[left_elt] -= 1 else: substr.pop(left_elt) if len(substr) == k: res += 1 return res def num_substrings_brute_force(s: str) -> int: res = 0 for i in range(len(s)): res += __num_substrings_brute_force__(s[i:]) return res ############################################################################### def num_substrings_sliding_window(s: str) -> int: left = 0 right = 0 end = len(s) - 1 hm = dict() count = 0 while right != len(s): hm[s[right]] = hm.get(s[right], 0) + 1 while hm.get('a', 0) > 0 and hm.get('b', 0) > 0 and hm.get('c', 0) > 0: count += 1 + (end - right) hm[s[left]] -= 1 left += 1 right += 1 return count if __name__ == '__main__': s = "abcabc" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res) s = "aaacb" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res) s = "abc" res = num_substrings_brute_force(s) print(s, res) res = num_substrings_sliding_window(s) print(s, res)
true
12562fa1658d275e15075f71cff3fac681c119ab
green-fox-academy/Angela93-Shi
/week-01/day-4/data_structures/data_structures/product_database.py
715
4.34375
4
map={'Eggs':200,'Milk':200,'Fish':400,'Apples':150,'Bread':50,'Chicken':550} # Create an application which solves the following problems. # How much is the fish? print(map['Fish']) # What is the most expensive product? print(max(map,key=map.get)) # What is the average price? total=0 for key in map: total=total+map[key] average=total/len(map) print(average) # How many products' price is below 300? n=0 for key in map: if map[key] < 300: n+=1 print(n) # Is there anything we can buy for exactly 125? for key,value in map.items(): if map[key] == 125: print("yes") else: print("No") break # What is the cheapest product? print(min(map,key=map.get))
true
587a7726500b091aea4511e4036f8750c229ecaa
green-fox-academy/Angela93-Shi
/week-05/day-01/all_positive.py
319
4.3125
4
# Given a list with the following items: 1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14 # Determine whether every number is positive or not using all(). original_list=[1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14] def positive_num(nums): return all([num > 0 for num in nums]) print(positive_num(original_list))
true
8fcf16851182307c41d9c5dd77e8d42b783628c7
green-fox-academy/Angela93-Shi
/week-01/day-4/function/factorial.py
409
4.375
4
# - Create a function called `factorio` # that returns it's input's factorial num = int(input("Please input one number: ")) def factorial(num): factorial=1 for i in range(1,num + 1): factorial = factorial*i print("%d 's factorial is %d" %(num,factorial)) if num < 0: print("抱歉,负数没有阶乘") elif num == 0: print("0 的阶乘为 1") else: factorial(num)
true
c60df7c6d2aa3eaecdc1c95bc7bba9a96eff1add
kasemodz/RaspberryPiClass1
/LED_on_off.py
831
4.125
4
# The purpose of this code is to turn the led off and on. # The LED is connected to GPIO pin 25 via a 220 ohm resistor. # See Readme file for necessary components #! /usr/bin/python #We are importing the sleep from the time module. from time import sleep #We are importing GPIO subclass from the class RPi. We are referring to this subclass via GPIO. import RPi.GPIO as GPIO # Resets all pins to factory settings GPIO.cleanup() # Sets the mode to pins referred by "GPIO__" pins (i.e. GPIO24) GPIO.setmode(GPIO.BCM) # Configures GPIO Pin 25 as an output, because we want to # control the state of the LED with this code. GPIO.setup(25, GPIO.OUT) # Turns the LED state to ON by the HIGH command. To turn off the LED, change HIGH to LOW, # then run this file again. ie. GPIO.output(25, GPIO.LOW) GPIO.output(25, GPIO.HIGH)
true
e799fbff3d6be502d48b68fb1094b6dd4bcc4079
yihangx/Heart_Rate_Sentinel_Server
/validate_heart_rate.py
901
4.25
4
def validate_heart_rate(age, heart_rate): """ Validate the average of heart rate, and return the patient's status. Args: age(int): patient'age heart_rate(int): measured heart rates Returns: status(string): average heart rate """ status = "" if age < 1: tachycardia_threshold = -1 if age in range(1, 3): tachycardia_threshold = 151 if age in range(3, 5): tachycardia_threshold = 137 if age in range(5, 8): tachycardia_threshold = 133 if age in range(8, 12): tachycardia_threshold = 130 if age in range(12, 16): tachycardia_threshold = 119 if age > 15: tachycardia_threshold = 100 if tachycardia_threshold != -1: if heart_rate >= tachycardia_threshold: status = "tachycardia" else: status = "not tachycardia" return status
true
0f7cfefeb124d76ef25dc904500246c9e843658d
xg04tx/number_game2
/guessing_game.py
2,282
4.125
4
def main(): while True: try: num = int( input("Please, think of a number between 1 and 1000. I am about to try to guess it in 10 tries: ")) if num < 1 or num > 1000: print("Must be in range [1, 100]") else: computer_guess(num) except ValueError: print("Please put in only whole numbers for example 4") def computer_guess(num): NumOfTry = 10 LimitLow = 1 LimitHigh = 1000 NumToGuess = 500 while NumOfTry != 0: try: print("I try: ", NumToGuess) print("Please type: 1 for my try is too high") print(" 2 for my try is too low") print(" 3 I guessed your number") Answer = int(input("So did I guess right?")) if 1 < Answer > 3: print("Please enter a valid answer. 1, 2 and 3 are the valid choice") NumOfTry = NumOfTry + 1 if Answer == 1: LimitHigh = NumToGuess print("Hmm, so your number is between ", LimitLow, "and ", LimitHigh) NumOfTry = NumOfTry - 1 print(NumOfTry, "attempts left") NumToGuess = int(((LimitHigh - LimitLow) / 2) + LimitLow) if NumToGuess <= LimitLow: NumToGuess = NumToGuess + 1 if LimitHigh - LimitLow == 2: NumToGuess = LimitLow + 1 elif Answer == 2: LimitLow = NumToGuess print("Hmm, so your number is between ", LimitLow, "and ", LimitHigh) NumOfTry = NumOfTry - 1 print(NumOfTry, "attempts left") NumToGuess = int(((LimitHigh - LimitLow) / 2) + LimitLow) if NumToGuess <= LimitLow: NumToGuess = NumToGuess + 1 if LimitHigh - LimitLow == 2: NumToGuess = LimitLow + 1 elif num == NumToGuess: print("Don't cheat") NumOfTry = NumOfTry + 1 elif Answer == 3: print("I won!!!!") NumOfTry = 0 except: return main() if __name__ == '__main__': main()
true
4deedfe0dea559088f4d2652dfe71479fce81762
saman-rahbar/in_depth_programming_definitions
/errorhandling.py
965
4.15625
4
# error handling is really important in coding. # we have syntax error and exceptions # syntax error happens due to the typos, etc. and usually programming languages can help alot with those # exceptions, however, is harder to figure and more fatal. So in order to have a robust code you should # handle the errors and take care of the exceptions, and raise exceptions when necessary. """ Circuit failure example """ class Circuit: def __init__(self, max_amp): self.capacity = max_amp # max capacity in amps self.load = 0 # current load def connect(self, amps): """ function to check the connectivity :param amps: int :return: None """ if self.capacity += amps > max_amp: raise exceptions("Exceeding max amps!") elif self.capacity += amps < 0: raise exceptions("Capacity can't be negative") else: self.capacity += amps
true
0a8a9a0a4c6ca24fde6c09886c52d1d5c7817a24
Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way
/ex40b.py
974
4.53125
5
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." # ok pay attention! cities ['_find'] = find_city while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break #this line is the msot important ever! study! city_found = cities['_find'] (cities, state) print city_found """ 'CA' = key More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Continue with these: http://docs.python.org/2/tutorial/datastructures.html http://docs.python.org/2/library/stdtypes.html - mapping types """
true
5892f0c1c6cb36853a85e541cb6b3259346546e9
Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way
/ex06.py
898
4.1875
4
# Feed data directly into the formatting, without variable. x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" #Referenced and formatted variables, within a variable. y = "Those who know %s and those who %s." % (binary, do_not) print x print y #r puts quotes around string print "I said: %r." % x #s does not put quotes around string, so they are added manually print "I also said: '%s'." % y hilarious = False #variable anticipates formatting of yet unkown variable joke_evaluation = "Isn't that joke so funny?! %r" #joke_evaluation has formatting delclared in variable, when called formatting statement is completed by closing the formatting syntax print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side." #since variables are strings python concatenates, rather than perform mathmetic equation with error print w + e
true
71a2fe42585b7a6a2fece70674628c1b529f3371
pltuan/Python_examples
/list.py
545
4.125
4
db = [1,3,3.4,5.678,34,78.0009] print("The List in Python") print(db[0]) db[0] = db[0] + db[1] print(db[0]) print("Add in the list") db.append(111) print(db) print("Remove in the list") db.remove(3) print(db) print("Sort in the list") db.sort() print(db) db.reverse() print(db) print("Len in the list") print(len(db)) print("For loop in the list") for n_db in db: print(n_db) print(min(db)) print(max(db)) print(sum(db)) my_food = ['rice', 'fish', 'meat'] friend_food = my_food friend_food.append('ice cream') print(my_food) print(friend_food)
true
74bda556d528a9346da3bdd6ca7ac4e6bcac6654
adaoraa/PythonAssignment1
/Reverse_Word_Order.py
444
4.4375
4
# Write a program (using functions!) that asks the user for a long string containing multiple words. # Print back to the user the same string, except with the words in backwards order. user_strings = input('input a string of words: ') # prompts user to input string user_set = user_strings.split() # converts string to list print(user_set) backwards_list = user_set[::-1] # makes user_set list print backwards print(backwards_list)
true
7b35393252d51e721ffddde3007105546240e5df
adaoraa/PythonAssignment1
/List_Overlap.py
1,360
4.3125
4
import random # Take two lists, say for example these two:... # and write a program that returns a list that # contains only the elements that are common between # the lists (without duplicates). Make sure your program # works on two lists of different sizes. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] common_list=list(set(a).intersection(b)) # intersection: finds commonalities print(common_list) num1=int(input('How many numbers do you want list1 to have? ' 'enter a number between 5 and 12: ')) num2=int(input('How many numbers do you want list2 to have? ' 'enter a number between 5 and 12: ')) range_list1= int(input('Starting at 1, at what integer do ' 'you want your list to end?: ')) range_list2= int(input('Starting at 1, at what integer do ' 'you want your list to end?: ')) x=random.sample(range(range_list1),num1) y=random.sample(range(range_list2),num2) print(x) print(y) common_elements=list(set(x).intersection(y)) print(common_elements) # variable x generates random list given range the user inputs # variable y does the same as variable x # The varaible common_elements prints the common elements between the random lists # Sometimes there will be no common elements which is why this is impractical
true
7036212232a843fe184358c1b41e5e9cb096d31d
andrew5205/MIT6-006
/ch2/binary_search_tree.py
1,377
4.21875
4
class Node: # define node init def __init__(self, data): self.left = None self.right = None self.data = data # insert into tree def insert(self, data): # if provide data exist if self.data: # 1 check to left child # compare with parent node if data < self.data: # 1.1 if left child not yet exist if self.left is None: self.left = Node(data) # 1.2 if left child exist, insert to the next level(child) else: self.left.insert(data) # 2 check to right child # compare with parent node elif data > self.data: # 2.1 if right child not yet exist if self.right is None: self.right = Node(data) # 2.2 if right child exist, insert to the next level(child) else: self.right.insert(data) else: self.data = data # print func def print_tree(self): if self.left: self.left.print_tree() print(self.data), if self.right: self.right.print_tree() root = Node(12) root.insert(6) root.insert(14) root.insert(3) root.print_tree()
true
e9aa4621abbe5b8b60fa7bc02b3a54ba2f42531a
sharmar0790/python-samples
/misc/findUpperLowerCaseLetter.py
241
4.25
4
#find the number of upper and lower case characters str = "Hello World!!" l = 0 u=0 for i in str: if i.islower(): l+=1 elif i.isupper(): u+=1 else: print("ignore") print("Lower = %d, upper = %d" %(l,u))
true
ece16e9a25e880eaa3381b787b12cecf86625886
x223/cs11-student-work-Aileen-Lopez
/March21DoNow.py
462
4.46875
4
import random random.randint(0, 8) random.randint(0, 8) print(random.randint(0, 3)) print(random.randint(0, 3)) print(random.randint(0, 3)) # What Randint does is it accepts two numbers, a lowest and a highest number. # The values of 0 and 3 gives us the number 0, 3, and 0. # I Changed the numbers to (0,8) and the results where 1 0 1. # The difference between Randint and print is that print will continue giving a 3, while Randint stays the same of changes.
true
016c7e2da4516be168d3f51b34888d12e0be1c5d
adrian-calugaru/fullonpython
/sets.py
977
4.4375
4
""" Details: Whats your favorite song? Think of all the attributes that you could use to describe that song. That is: all of it's details or "meta-data". These are attributes like "Artist", "Year Released", "Genre", "Duration", etc. Think of as many different characteristics as you can. In your text editor, create an empty file and name it main.py Now, within that file, list all of the attributes of the song, one after another, by creating variables for each attribute, and giving each variable a value. Here's an example: Genre = "Jazz" Give each variable its own line. Then, after you have listed the variables, print each one of them out. For example: Artist = "Dave Brubeck" Genre = "Jazz" DurationInSeconds = 328 print(Artist) print(Genre) print(DurationInSeconds) Your actual assignment should be significantly longer than the example above. Think of as many characteristics of the song as you can. Try to use Strings, Integers and Decimals (floats)! """
true
4ce5c10eaf4a27ff54a1b12c87110659daf3f04a
aubreystevens/image_processing_pipeline
/text_files/Test.py
1,033
4.15625
4
#B.1 def complement(sequence): """This function returns the complement of a DNA sequence. The argument, 'sequence' represents a DNA sequence.""" for base in 'sequence': if 'A' in 'sequence': return 'T' elif 'G' in 'sequence': return 'C' elif 'T' in 'sequence': return 'A' else: return 'G' #B.2 def list_complement(dna): """This function returns the complement of a DNA sequence.""" if 'A': return 'T' elif 'G': return 'C' elif 'T': return 'A' else: return 'G' #B.3 def product(numbers): """Returns sum of all numbers in the list.""" for x in numbers: final += x return final #B.4 def factorial(x): """Returns factorial of number x.""" if x = 0 : return 1 else: return x = x * (x-1) #B.5
true
33d73944bf28351346ac72cbee3f910bcf922911
maneeshapaladugu/Learning-Python
/Practice/Armstrong_Number.py
763
4.46875
4
#Python program to check if a number is Armstrong or not #If the given number is 153, and 1^3 + 5 ^ 3 + 3 ^ 3 == 153, then 153 is an Armstrong number def countDigits(num): result = 0 while num > 0: result += 1 num //= 10 print(result) return result def isArmstrong(num): digitCount = countDigits(num) temp = num result = 0 while temp: result += pow(temp%10, digitCount) temp //= 10 if result == num: return 1 else: return 0 num = int(input("Enter a number:\n")) #Receive the input as an integer if isArmstrong(num): print("%d is an Armstrong Number" %(num)) else: print("%d is not an Armstrong number" %(num))
true
8071c3f0f77261cb68e0c36d09a814ba95fdb474
MyoMinHtwe/Programming_2_practicals
/Practical 5/Extension_1.py
248
4.3125
4
name_to_dob = {} for i in range(2): key = input("Enter name: ") value = input("Enter date of birth (dd/mm/yyyy): ") name_to_dob[key] = value for key, value in name_to_dob.items(): print("{} date of birth is {:10}".format(key,value))
true
a288abbab98175fb70e1c1a34c5c6f4eeeed438a
HarshKapadia2/python_sandbox
/python_sandbox_finished_(by_harsh_kapadia)/tuples_sets.py
1,269
4.25
4
# A Tuple is a collection which is ordered and unchangeable. Allows duplicate members. # create tuple fruit_1 = ('mango', 'watermelon', 'strawberry', 'orange', 'dragon fruit') # using constructor fruit_2 = tuple(('mango', 'watermelon', 'strawberry', 'orange', 'dragon fruit')) print(fruit_1, fruit_2) fruit_3 = ('apple') print(fruit_3, type(fruit_3)) # type str fruit_4 = ('blueberry',) # single value needs trailing comma to be a tuple print(fruit_4, type(fruit_4)) # type tuple # get value print(fruit_1[0]) # values cannot be changed in tuples # fruit_1[0] = 'water apple' # error # deleting a tuple del fruit_2 # print(fruit_2) # o/p: error. 'fruit_2' not defined # length of tuple print(len(fruit_1)) # A Set is a collection which is unordered and unindexed. No duplicate members. fruit_5 = {'mango', 'apple'} # check if in set print('mango' in fruit_5) # RT: bool # add to set fruit_5.add('watermelon') print(fruit_5) # add duplicte member fruit_5.add('watermelon') # doesn't give err, but doesn't insert the duplicate val print(fruit_5) # remove from set fruit_5.remove('watermelon') print(fruit_5) # clear the set (remove all elements) fruit_5.clear() print(fruit_5) # delete set del fruit_5 # print(fruit_5) # o/p: error. 'fruit_5' not defined
true
828e176b7aae604d3f4d38a206d4f1cfa5d49197
HarshKapadia2/python_sandbox
/python_sandbox_finished_(by_harsh_kapadia)/loops.py
854
4.1875
4
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). people = ['Selena', 'Lucas', 'Felix', 'Brad'] # for person in people: # print(person) # break # for person in people: # if person == 'Felix': # break # print(person) # continue # for person in people: # if person == 'Felix': # continue # print(person) # range # for i in range(len(people)): # print(i) # print(people[i]) # for i in range(0, 5): # 0 is included, but 5 is not # print(i) # for i in range(6): # starts from 0, goes till 5 # print(i) # While loops execute a set of statements as long as a condition is true. count = 10 while count > 0: print(count) count -= 1 # count-- does not exist in python (ie, post/pre increment ops do not exist in python)
true
622589e96be15dc7e742ce2a1dc83ea91507b5dc
DeepanshuSarawagi/python
/ModulesAndFunctions/dateAndTime/datecalc.py
354
4.25
4
import time print(time.gmtime(0)) # This will print the epoch time of this system which is usually January 1, 1970 print(time.localtime()) # This will print the local time print(time.time()) # This will print the time in seconds since epoch time time_here = time.localtime() print(time_here) for i in time_here: print(i) print(time_here[0])
true
91bfc92d73cf257344dc1260e433bdbd9d6cb4d5
DeepanshuSarawagi/python
/freeCodeCamp/ConditionalExecution/conditionalExecution.py
309
4.1875
4
# This is a python exercise on freeCodeCamp's python certification curriculum x = 5 if x < 5: print("X is less than 5") for i in range(5): print(i) if i <= 2: print("i is less than or equal to 2") if i > 2: print("i is now ", i) print("Done with ", i) print("All done!")
true
7384fbb693486ec0f00158292487d6a2086fc2ac
DeepanshuSarawagi/python
/Data Types/numericOperators.py
485
4.34375
4
# In this lesson we are going to learn about the numeric operators in the Python. a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) # We will learn about the operator precedence in the following example. print(a + b / 3 - 4 * 12) # This should evaluate to -35.0 as per the BODMAS rule. If you have got it 12, you are wrong. print(a + (b/3) - (4 * 12)) print((((a + b) / 3) - 4) * 12) # This will evaluate to 12.0. print(a / (b * a) / b)
true
6d34356e7e6d161aa6e838b8ca588e3dce3b01f4
DeepanshuSarawagi/python
/100DaysOfPython/Day2/DataTypes/typeConversion.py
944
4.25
4
# In this lesson we are going to convert the int data type to string data type num_char = len(input("What is your name?\n")) print("Your name has " + str(num_char) + " characters") # Type conversion happens here. Where we convert # the type integer to string # Or we can use the fStrings print("Your name has {} characters".format(num_char)) print(70 + float("170.5")) # Day 2 - Exercise 1 - Print the sum of digits of a number two_digit_number = input("Type a two digit number of your choice: ") print(int(two_digit_number[0]) + int(two_digit_number[1])) # Better solution sum_of_numbers = 0 for i in range(0, len(str(two_digit_number))): sum_of_numbers += int(two_digit_number[i]) print(sum_of_numbers) # Remembering the PEMDASLR rule (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction, Left to Right) print(3 * 3 + 3 / 3 - 3) print(3 * 3 / 3 + 3 - 3)
true
a9aaf4e426597e6a54aff443fdadefad6e4fb9d6
DeepanshuSarawagi/python
/100DaysOfPython/Day1/main.py
647
4.375
4
print("Print something") print("Hello World!") print("Day 1 - Python Print Function") print("print('what to print')") print("Hello World!\nHello World again!\nHellooo World!!") print() # Day 1. Exercise 2 Uncomment below and debug the errors # print(Day 1 - String Manipulation") # print("String Concatenation is done with the "+" sign.") # print('e.g. print("Hello " + "world")') # print(("New lines can be created with a backslash and n.") print("Day 1 - String Manipulation") print("String Concatenation is done with the " + "+" + " sign.") print('e.g. print("Hello " + "world")') print("New lines can be created with a backslash and n.")
true
34c3bcf8c09826d88ff52370f8c9ae9735d2f966
DeepanshuSarawagi/python
/100DaysOfPython/Day19/Turtle-GUI-2/main.py
796
4.21875
4
from turtle import Turtle, Screen tim = Turtle() screen = Screen() def move_forward(): tim.forward(10) screen.listen() # In order for our turtle to listen to the screen events, we need to call this screen method screen.onkey(fun=move_forward, key="Up") # The Screen.onkey() method accepts two arguments, 1. Function and 2. Kwy. # We need to ensure that when we pass a function as an argument, it is coded without parentheses. Passing the function # with parentheses calls the function immediately, instead we want it listen to an event and call the function when an # event occurs. Like for example, in our case, when a key is presses. screen.exitonclick() # Higher Order Functions. A higher Order Function is called when a function accepts another function as an # input/argument
true
e9e42890ea221e41dd51181364f24590d1b0ce6e
DeepanshuSarawagi/python
/whileLoop/whileLoop.py
423
4.125
4
# In this lesson we are going to learn about while loops in Python. # Simple while loop. i = 0 while i < 10: print(f"i is now {i}") i += 1 available_exit =["east", "west", "south"] chosen_exit = "" while chosen_exit not in available_exit: chosen_exit = input("Please enter a direction: ") if chosen_exit == "quit": print("Game over") break else: print("Glad that you got out of here")
true
ad0cf84f3a01da48c32aa7efae44cf3b964d44d1
DeepanshuSarawagi/python
/100DaysOfPython/Day2/DataTypes/BMICalculator.py
209
4.28125
4
height = float(input("Enter your height in meters: ")) weight = float(input("Enter your weight in kilograms: ")) print("Your BMI is {}".format(round(weight / (height * height), 2))) print(8 // 3) print(8 / 3)
true
31a342ddff6fade8595b45f6127868b7525feca1
DeepanshuSarawagi/python
/DSA/Arrays/TwoDimensionalArrays/main.py
2,074
4.40625
4
import numpy # Creating two dimensional arrays # We will be creating it using a simple for loop two_d_array = [] for i in range(1, 11): two_d_array.append([i * j for j in range(2, 6)]) print(two_d_array) twoDArray = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]) print(twoDArray) # Insertion in 2D array new2DArray = numpy.insert(twoDArray, 1, [[21, 22, 23, 24]], axis=1) # The first int parameter is the position # where we want to add. And axis=1 denotes we want to add new values as columns, if axis=0, add it as rows # Important Note: While using numpy library to insert elements in a 2-D array is that we meed to match the # row/column size while inserting new elements in array print(new2DArray) # We will now use the append function to insert a new row/column at the end of the array new2D_Array = numpy.append(twoDArray, [[97], [98], [99], [100]], axis=1) print(new2D_Array) print(len(new2D_Array)) # This prints the no. of rows in an array print(len(new2D_Array[0])) # This prints the no. of columns in an array def access_elements(array, rowIndex: int, colIndex: int) -> None: if rowIndex >= len(array) and colIndex >= len(array[0]): print("You are trying to access an element which is not present in the array") else: print(array[rowIndex][colIndex]) access_elements(new2D_Array, 3, 5) # Traversing through the 2-D array def traverse_array(array): for i in range(len(array)): for j in range(len(array[0])): print(array[i][j], end="\t") print() traverse_array(new2D_Array) def search_element(element, array): for i in range(len(array)): for j in range(len(array[0])): if array[i][j] == element: return "{} found at row {} and column {}".format(element, i + 1, j + 1) return "The element {} is not found in given array.".format(element) print(search_element(15, new2D_Array)) # How to delete a row/column in 2-D array new2D_Array = numpy.delete(twoDArray, 0, axis=0) print(new2D_Array)
true
c32944fc92021af6a9aab1d68844287921f5f7dd
DeepanshuSarawagi/python
/100DaysOfPython/Day21/InheritanceBasics/Animal.py
563
4.375
4
class Animal: def __init__(self): self.num_eyes = 2 def breathe(self): print("Inhale, Exhale") # Now we are going to create a class Fish which will inherit properties from the Animal class and also has it's own # properties class Fish(Animal): def __init__(self): super().__init__() # Initializing all the attributes in super class self.num_eyes = 3 # Here we are changing the field num_eyes to 3 def swim(self): print("I can swin in water") def print_eyes(self): print(self.num_eyes)
true
1117ab86b491eca4f879897af51ccc69112e854b
shaonsust/Algorithms
/sort/bubble_sort.py
1,074
4.40625
4
""" Python 3.8.2 Pure Python Implementation of Bubble sort algorithm Complexity is O(n^2) This algorithm will work on both float and integer type list. Run this file for manual testing by following command: python bubble_sort.py Tutorial link: https://www.geeksforgeeks.org/bubble-sort/ """ def bubble_sort(arr): """ Take an unsorted list and return a sorted list. Args: arr (integer) -- it could be sorted or unsorted list. Returns: arr (integer) -- A sorted list. Example: >>> bubble_sort([5, 4, 6, 8 7 3]) [3, 4, 5, 6, 7, 8] """ for i in range(len(arr) - 1): flag = True for j in range(len(arr) - i - 1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] # Swaping here flag = False if flag: break return arr if __name__ == '__main__': # Taking input from user USER_INPUT = [float(x) for x in input().split()] # call bublesort to sort an unsorted list and print it. print(bubble_sort(USER_INPUT))
true
81a8bce1fd4ad1426104d8f4b662f0c0ca3c52c5
destinysam/Python
/more inputs in one line.py
435
4.15625
4
# CODED BY SAM@SAMEER # EMAIL: SAMS44802@GMAIL.COM # DATE: 12/09/2019 # PROGRAM: TAKING MORE THAN ONE INPUT FROM THE USER name, age, address = "sameer", "23", "tarigam" # ASSIGNING VALUES BY ORDER print("YOUR NAME,AGE AND ADDRESS IS " + name + " " + age + " " + address) x = y = z = 2 print(x+y+z) name, age, address = input("ENTER YOUR NAME AND AGE ").split() # USING OF SPLIT FUNCTION TO TAKE MORE INPUTS print(name) print(age) print(address)
true
0eaf2afa9cc1c3f161504fc2c9254b92fb3f4262
venkatadri123/Python_Programs
/100_Basic_Programs/program_43.py
280
4.53125
5
# 43. Write a program which accepts a string as input to print "Yes" # if the string is "yes" or "YES" or "Yes", otherwise print "No". def strlogical(): s=input() if s =="Yes" or s=="yes" or s=="YES": return "Yes" else: return "No" print(strlogical())
true
01158919c0c3b66a38f8094fe99d22d9d3f53bed
venkatadri123/Python_Programs
/100_Basic_Programs/program_35.py
322
4.15625
4
# 35. Define a function which can generate a dictionary where the keys are numbers between 1 and 20 # (both included) and the values are square of keys. The function should just print the keys only. def sqrkeys(): d=dict() for i in range(1,21): d[i]=i**2 for k in d: print(k) sqrkeys()
true
b1adffe626fa1a1585012689ec2b1c01925c181c
venkatadri123/Python_Programs
/core_python_programs/prog78.py
334
4.15625
4
# Write a python program to accept values from keyboard and display its transpose. from numpy import* r,c=[int(i) for i in input('enter rows,columns:').split()] arr=zeros((r,c),dtype=int) print('enter the matrix:') for i in range(r): arr[i]=[int(x) for x in input().split()] m=matrix(arr) print('transpose:') print(m.transpose())
true
3625b577e1d82afc31436473149cc7ff1e3ce96c
venkatadri123/Python_Programs
/100_Basic_Programs/program_39.py
318
4.1875
4
# 39. Define a function which can generate a list where the values are square of numbers # between 1 and 20 (both included). Then the function needs to print all values # except the first 5 elements in the list. def sqrlis(): l=[] for i in range(1,20): l.append(i**2) return l[5:] print(sqrlis())
true
fa7b092a720e7ce46b2007341f4e70de60f8e6ca
venkatadri123/Python_Programs
/100_Basic_Programs/program_69.py
375
4.15625
4
# 69. Please write assert statements to verify that every number in the list [2,4,6,8] is even. l=[2,4,6,8] for i in l: assert i%2==0 # Assertions are simply boolean expressions that checks if the conditions return true or not. # If it is true, the program does nothing and move to the next line of code. # However, if it's false, the program stops and throws an error.
true