blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
47beaf6f6933aa28e953b71285a0a7e7993c74b8
habibbueteee/Algorithm-data-structure
/Queue.py
820
4.40625
4
#FIFO first item we insert is the first item one we take out class Queue: def __init__(self): self.queue = [] # 0(1) def is_emty(self): return self.queue == [] #0(1) def enqueue(self, data): self.queue.append(data) #0(N) liner running time complexity def dequeue(self): if self.queue_size() < 1: return data = self.queue[0] del self.queue[0] return data #0(n) def peek(self): data = self.queue[0] return data #0(1) def queue_size(self): return len(self.queue) queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) print('Size: ' + str(queue.queue_size())) print("Dequeue item: "+ str(queue.dequeue())) print("Size: " + str(queue.queue_size())) print("Peek item: "+ str(queue.peek())) print("Size: " + str(queue.queue_size()))
false
666fcf93353f032029e9b974eb4d60c791ee55c5
hravnaas/python_lessons
/cointosses.py
600
4.1875
4
# You're going to create a program that simulates tossing a coin 5,000 times. # Your program should display how many times the head/tail appears. import random def flipCoin(): if round(random.random()) == 1: return "head" return "tail" msg = "Attempt #{}: Throwing a coin... It's a {}! ... Got {} head(s) so far and {} tail(s) so far " numHeads = 0; numCoinFlips = 5000; print "Starting the program..." for i in range(0, numCoinFlips): coin = flipCoin() if coin == "head": numHeads += 1 print msg.format(i + 1, coin, numHeads, i + 1 - numHeads) print "Ending the program, thank you!"
true
e0ca55619920753a3e2d3fa359dbf81b29fd2cab
hravnaas/python_lessons
/multiply.py
401
4.125
4
# Create a function called 'multiply' that reads each value in the list (e.g. a = [2, 4, 10, 16]) # and returns a list where each value has been multiplied by 5. # The function should multiply each value in the list by the second argument. def multiply(arr, multiplier): for i in range(0, len(arr)): arr[i] *= multiplier return arr myArr = [2, 4, 10, 16] result = multiply(myArr, 5) print result
true
bfa5e2c029fdb2f0789ad05f1983b6c5932a6fe5
julianevan/Sandbox
/temperature.py
1,220
4.375
4
""" CP1404/CP5632 - Practical Pseudocode for temperature conversion """ def calculate_celsius(): celsius = float(input("Celsius: ")) # float so as to allow decimal input fahrenheit = celsius * 9.0 / 5 + 32 # formula for celsius to fahrenheit conversion print("Result: {:.2f} F".format(fahrenheit)) # displays fahrenheit, rounded to two decimal places. def calculate_fahrenheit(): fahrenheit = float(input("Fahrenheit: ")) # float so as to allow decimal input celsius = (5 / 9) * (fahrenheit - 32) # formula for fahrenheit to celsius conversion print("Result: {:.2f} F".format(celsius)) # displays celsius, rounded to two decimal places MENU = """C - Convert Celsius to Fahrenheit F - Convert Fahrenheit to Celsius Q - Quit""" print(MENU) choice = input(">>> ").upper() #to make the inputted text in upper case while choice != "Q": #the program will loop until the user enters q if choice == "C": #if user enters c calculate_celsius() elif choice == "F": #if choice is F calculate_fahrenheit() else: #if choice is not C,F or Q. print("Invalid option") print(MENU) choice = input(">>> ").upper() print("Thank you.") #if user inputs Q
true
4ae398e77682cfce44ac1e92861ca89646f5e1bc
DhanaMani1983/Python
/InnerClass.py
622
4.125
4
''' inner class: class within another class is called inner class ''' class Student: def __init__(self, name, rollno): self.name = name self.rollno = rollno self.lap = self.Laptop() def show(self): print(self.name, self.rollno) self.lap.show() class Laptop: def __init__(self): self.brand = 'Dell' self.processor = 'i5' def show(self): print("brand %s, processor %s" %(self.brand,self.processor)) s1 = Student('Deepak Noveen',11) s2 = Student('Dhanasekaran',12) s1.show() s2.show()
false
7df715ae08107b1efdb6633a0010c466ccacaf73
niloo9876/marow
/example/example_functions.py
1,119
4.4375
4
def mapper(chunk): """ The mapper function: process the raw text and returns the pairs name-value. Args: - chunk(str): the raw text from data file Return(list of tuples): a list of 2D tuples with the pairs name-value. """ Pairs = [] for line in chunk.split('\n'): data = line.strip().split(",") if len(data) == 6: zip_code, latitude, longitude, city, state, country = data Pairs.append((str(country), 1)) return Pairs def reducer(Pairs): """ The reducer function: reduces the Pairs. Args: - Pairs(list of tuples): a sorted list of 2D tuples with the pairs name-value. Return(list of tuples): a list of 2D tuples with the pairs name-value. """ Results = [] actualName = None resultsIndex = -1 for name, value in Pairs: if actualName != str(name): actualName = str(name) Results.append([str(name),int(value)]) resultsIndex = resultsIndex + 1 else: Results[resultsIndex][1] = int(Results[resultsIndex][1]) + int(value) return Results
true
ead64a142884de56aae8173d60b2a157c8870e37
dettore/learn-python-exercises
/_beginners python 3 source files/strings.py
520
4.40625
4
name = "stefan mischook" result = name.endswith('ook') print(result) # This is just a quick way (using the . operator,) # to apply a method to an object. That's why you can't do this: # name.upper() # print(name) # ... It will NOT be uppercase. # nameCap = name.upper() print("Did I capitalize: " + nameCap) # strings are objects in python #strings are immutable in python print(id(name)) print(type(name)) print("\n New string created ...") name = name + "Jimmys fish" print(id(name)) print(type(name))
true
957b84ecf88087f8528e9400b93aac5cc614e4ca
tmoertel/practice
/programming_praxis/dutch_national_flag.py
1,989
4.125
4
#!/usr/bin/python # # Tom Moertel <tom@moertel.com> # 2013-03-05 """Solve Dijkstra's "Dutch National Flag" problem. http://programmingpraxis.com/2013/03/05/dutch-national-flag/ """ # Our stategy is to partition A into red, mid, and blue segments, # where the red segment A[:red] contains exclusively 'r' values, and # the blue segment A[blue:] contains exclusively 'b' values. The mid # segment A[red:blue] contains everything else, partitioned by i: # A[blue:i] are values known to be 'w', and A[i:red} are unexamined # values. Initially, then, the unexamined mid segment owns the entire # array, but as we examine elements we swap them into the red and blue # segments, which grow correspondingly. When we've examined all of # the elements, there will be no unexamined elements in the mid # segment, which must therefore be all 'w' values; hence the array # will be sorted by color (into the 'r', 'w', 'b' order of the Dutch # National Flag). def dnf_sort(A): """Sort (in-place) a 3-colored array.""" def swap(i, j): A[i], A[j] = A[j], A[i] red = i = 0 blue = len(A) while i < blue: # invariant: all elems in A[blue:i] are 'w' # invariant: all elems in A[i:red] are unexamined if A[i] == 'r': swap(i, red) red += 1 i += 1 elif A[i] == 'b': blue -= 1 swap(i, blue) # don't advance i: after swap A[i] is now unexamined else: i += 1 # Test code COLORS = 'rwb' VALUES = [0, 1, 2] cval = dict(zip(COLORS, VALUES)).get cvals = lambda cs: map(cval, cs) def test_dnf_sort(): for l in xrange(8): for cs in combinations([COLORS] * l): assert_sorted(cs) def combinations(xss): if xss == []: return [[]] return [list(x) + ys for ys in combinations(xss[1:]) for x in xss[0]] def assert_sorted(cs): expected = sorted(cvals(cs)) dnf_sort(cs) assert cvals(cs) == expected
true
3dcec98ad917bb35c6344402d7921ca1878e5bb0
gmckerrell/python-examples
/puzzles/collatz_template.py
1,480
4.40625
4
""" A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer: if n is even, the next number in the sequence is n / 2 if n is odd, the next number in the sequence is 3n + 1 It is conjectured that every such sequence eventually reaches the number 1. Test this conjecture. Bonus: What input n <= 1000000 gives the longest sequence? """ def collatz(value): """ This function returns a collatz sequence for a given number value - the number to evaluate """ return [] def getLargest(maxValue): """ This function will return the largest sequence less than the given maximum. maxValue - the maximum value to test """ return [] if __name__ == '__main__': import unittest class TestCollatzMethods(unittest.TestCase): def test_collatz_10(self): self.assertEqual( collatz(10), [10,5,16,8,4,2,1] ) def test_collatz_78(self): self.assertEqual( collatz(78), [78,39,118,59,178,89,268,134,67,202,101,304,152,76, 38,19,58,29,88,44,22,11,34,17,52,26,13,40,20,10, 5,16,8,4,2,1] ) def test_getLargest_100(self): largest = getLargest(100) self.assertEqual( len(largest), 119 ) print(f"Largest ({len(largest)} values): {largest}") unittest.main()
true
7d7f99ca0270914fb450d096e51e65abd688bdb8
WLBailey0/Think-Python-2e
/ex9/ex9.9.py
1,125
4.15625
4
#!/usr/bin/env python3 """ Exercise 9.9. Here’s another Car Talk Puzzler you can solve with a search (http://www.cartalk.com/content/puzzlers): “Recently I had a visit with my mom and we realized that the two digits that make up my age when reversed resulted in her age. For example, if she’s 73, I’m 37. We wondered how often this has happened over the years but we got sidetracked with other topics and we never came up with an answer." “When I got home I figured out that the digits of our ages have been reversible six times so far. I also figured out that if we’re lucky it would happen again in a few years, and if we’re really lucky it would happen one more time after that. In other words, it would have happened 8 times over all. So the question is, how old am I now?” Write a Python program that searches for solutions to this Puzzler. Hint: you might find the string method zfill useful. Solution: http://thinkpython2.com/code/cartalk3.py """ def num_pal(): for i in range(0, 999999): if str(i).zfill(6) == str(i).zfill(6)[::-1]: print(str(i).zfill(6)) num_pal()
true
e21eb2049f4282ea2d6500b241c6ad3a182961b9
phaneendra-bangari/python-scripts
/Python Learning Scripts/PythonLoops/string_index.py
417
4.53125
5
#This script takes a string as input and locates its index values using loops. INPUT_STRING=input("Enter a string to point their index values: ") TEMP=0 for INDEX_VALUE in INPUT_STRING: print(f"{INDEX_VALUE}->{TEMP}") TEMP=TEMP+1 ''' INPUT_STRING=list(input("Enter a string to point their index values: ")) for INDEX_VALUE in INPUT_STRING: print(f"{INDEX_VALUE}->{INPUT_STRING.index(INDEX_VALUE)}") '''
true
638b0ebd25b6004693ade97c067de0a63dfbe675
ramr24/IntroToProg-Python
/num.py
474
4.28125
4
#Assignment_02 ''' Create a new program that asks the user to input 2 numbers then prints out the sum, difference, product, and quotient. ''' #Input 2 numbers num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) #Functions add = num1 + num2 sub = num1 - num2 mul = num1 * num2 div = num1 / num2 #Print statements print("Sum:", add) print("Difference:", sub) print("Product:", mul) print("Quotient:", div)
true
beabeb6d06433f52df73f8375b952f8cca389bf8
Khaloudinho/python-lesson-distributed-apps
/TP1/HelloWorld.py
441
4.125
4
#!/usr/bin/env python # -*-coding:utf-8-*- def get_odd_numbers_between_two_numbers(nb1, nb2): # Input : 42 51 # Output : 43 45 47 49 51 output = [] if nb1 % 2 == 0: nb1 += 1 while nb1 <= nb2: output.append(nb1) nb1 += 2 return output print(get_odd_numbers_between_two_numbers(4, 13)) print(get_odd_numbers_between_two_numbers(42, 51)) print(get_odd_numbers_between_two_numbers(-1, 5))
false
054179746facd0e8a44f1e5482431db85e8ff073
premrajah/python3_101
/03_timedelta.py
1,386
4.28125
4
# # Comments go here # from datetime import date from datetime import time from datetime import datetime from datetime import timedelta def main(): # construct a basic timedelta and print it print(timedelta(days=365, hours=5, minutes=1)) # print todays date now = datetime.now() print("Today is: ", str(now)) # todays date 1 year from now print("1 year from now: ", str(now + timedelta(days=365))) # create a timedelta that uses more than one argument print("In 2 days and three weeks it will be: ", str(now + timedelta(days=2, weeks=3))) # calculate the date 1 week ago, formatted as a string t = datetime.now() - timedelta(weeks=1) s = t.strftime("%A %B %d %Y") print("1 week ago it was: ", s) print("-----") # How anys days until next aprils fool day today = date.today() afd = date(today.year, 4, 1) # use date comparison to see if april fool's has already gone for this year # if it has, use the replace() function to get the date next year if(afd < today): print("Aprils fools day already went by %d days ago" % ((today-afd).days)) afd = afd.replace(year = today.year+1) # now calculate the amount of time until Aprils fools's day time_to_afd = afd - today print("It's just", time_to_afd, " days unitl April fool's day") if __name__ == "__main__": main()
true
cddbec89a0763c63b940d3769eee5995a436667d
GeorgePapageorgakis/Hackerrank
/Python/Numpy/Min Max.py
1,456
4.25
4
''' min The tool min returns the minimum value along a given axis. import numpy my_array = numpy.array([[2, 5], [3, 7], [1, 3], [4, 0]]) print numpy.min(my_array, axis = 0) #Output : [1 0] print numpy.min(my_array, axis = 1) #Output : [2 3 1 0] print numpy.min(my_array, axis = None) #Output : 0 print numpy.min(my_array) #Output : 0 By default, the axis value is None. Therefore, it finds the minimum over all the dimensions of the input array. max The tool max returns the maximum value along a given axis. import numpy my_array = numpy.array([[2, 5], [3, 7], [1, 3], [4, 0]]) print numpy.max(my_array, axis = 0) #Output : [4 7] print numpy.max(my_array, axis = 1) #Output : [5 7 3 4] print numpy.max(my_array, axis = None) #Output : 7 print numpy.max(my_array) #Output : 7 By default, the axis value is None. Therefore, it finds the maximum over all the dimensions of the input array. Given a 2-D array with dimensions N x M perform the min function over axis 1 and then find the max of that. ''' #!/bin/python3 import numpy import sys #n, m = [int(n) for n in input().split()] n, m = map(int, input().split()) #arr = numpy.array([input() for _ in range(n)], dtype=int) arr = numpy.array([input().split() for _ in range(n)], dtype=int) print(numpy.max(numpy.min(arr, axis = 1), axis = 0)) #optional axis=0
true
5903846a864054d376f8eccb53f8439914e646ac
GeorgePapageorgakis/Hackerrank
/Python/Numpy/Concatenate.py
1,060
4.3125
4
''' Concatenate Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined: import numpy array_1 = numpy.array([1,2,3]) array_2 = numpy.array([4,5,6]) array_3 = numpy.array([7,8,9]) print numpy.concatenate((array_1, array_2, array_3)) #Output [1 2 3 4 5 6 7 8 9] If an array has more than one dimension, it is possible to specify the axis along which multiple arrays are concatenated. By default, it is along the first dimension. import numpy array_1 = numpy.array([[1,2,3],[0,0,0]]) array_2 = numpy.array([[0,0,0],[7,8,9]]) print numpy.concatenate((array_1, array_2), axis = 1) #Output [[1 2 3 0 0 0] [0 0 0 7 8 9]] Given two integer arrays of size NxP and MxP (N & M are rows, and P is the column) concatenate the arrays along axis 0. ''' import numpy from sys import stdin N, M, P = map(int, input().split()) NP = numpy.array([input().split() for _ in range(N)], int) MP = numpy.array([input().split() for _ in range(M)], int) print(numpy.concatenate((NP, MP), axis = 0))
true
99922215e95feaeffa02710f863102a1b53399a0
Northie17/Hugo-Python-Prep
/Meal tip program.py
377
4.15625
4
Name = input ("Please enter your name:") Meal = float (input ("Please enter cost of meal:" )) PercentTip = float (input ("Please enter percentage of tip :" )) Tip = Meal/PercentTip TotalCost = Meal + Tip print ("The total cost for your meal is £{0:.2f} as the tip is £{1:.2f}".format(TotalCost,Tip)) print ("Thank you {0} for using this Meal Tip Calculator".format(Name))
true
75b93f827f4e32a3a35268ad0c864b9109967c87
ryanlei309/String-Practice-Game
/similarity.py
2,342
4.3125
4
""" File: similarity.py Name: Ryan Lei ---------------------------- This program compares short dna sequence, s2, with sub sequences of a long dna sequence, s1 The way of approaching this task is the same as what people are doing in the bio industry. """ def main(): """ After the user input a DNA sequence and another DNA sequence that the user would like to match, this function will find the best match of the first inputted DNA sequence. """ # Let user input the long DNA sequence. long_sequence = input('Please give me a DNA sequence to search: ') # Let user input the DNA sequence that user would like to match. short_sequence = input('What DNA sequence would you like to match? ') # Case-insensitve for the dna that user inputted. long_sequence = long_sequence.upper() short_sequence = short_sequence.upper() print('The best match is '+str(dna_matching(long_sequence, short_sequence))) def dna_matching(long_sequence, short_sequence): """ :param long_sequence: str, long dna sequence that user inputted. :param short_sequence: str, short dna sequence that user wants to match. :return: str, show the best dna in long dna sequence. """ # Catch the len of the short dna sequence. short_dna_len = len(short_sequence) # Catch the len of the long dna sequence. long_dna_len = len(long_sequence) # Storage the ans string. ans = '' # Count the highest score in long dna sequence. maximum = 0 # Compare sub dna and short dna sequence. # Discuss with TA Wilson on 2020/1/11. for i in range(long_dna_len-short_dna_len+1): # Catch long dna string. sub_dna = long_sequence[i:i+len(short_sequence)] # Count for the correction of similarity. count = 0 # Compare each character in sub dna and short sequence dna. for j in range(short_dna_len): a = sub_dna[j] b = short_sequence[j] # When the same dna appears, sub dna score one point. if a == b: count += 1 # When the score of dna in long dna sequence, replace the lower score. if count > maximum: maximum = count ans = sub_dna return ans ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == '__main__': main()
true
8c5a3b93bf20e527875e3404d5f294512b812b3a
oscarTinkerer37/My-tinkering
/listOfSquaresPalindromes.py
1,301
4.125
4
#list of squared numbers for finding palindromes #Created on windows pc import time, pprint #A list of numbers with lengths of two or more digits (10-899 default) along with their squared values will be printed out. #The program will alert the user when a non-palindromic base produces a palindromic square. print() time.sleep(0.2) bplusSquare = [] onlySquare = [] onlyBase = [] for b in range(10, 900): #List of numbers cuadr = b**2 base = list(str(b)) base2 = base.copy() base.reverse() sq = list(str(cuadr)) cuadr2 = sq.copy() sq.reverse() print(b, cuadr) time.sleep(0.1) if base2 == base and sq == cuadr2: print('Base %s and squared %s are palindromes' %(b, cuadr)) bplusSquare.append(base) bplusSquare.append(sq) time.sleep(0.1) if base2 != base and sq == cuadr2: print('Base %s non-palindrome... Square %s is a palindrome' %(b, cuadr)) onlySquare.append(base2) onlySquare.append(sq) time.sleep(0.1) if base2 == base and sq != cuadr2: print('Base %s is a palindrome... square %s non-palindrome.' %(b, cuadr)) onlyBase.append(base2) onlyBase.append(cuadr2) time.sleep(0.05)
true
4b65e823d7a08ee18ce55f9506f8713e4cc32b85
nangia-vaibhavv/Python-Learning
/CHAPTER 6/03_quiz.py
225
4.28125
4
# write a program to print yes if age entered by userr is greater than or equal to 18 # as it is in string hence typecast it properly age=int(input("enter your age: ")) if(age>=18): print("yes") else: print("no")
true
a5ef3b05d17178110989c01946070b79b44a461a
VitaliyDuma/Python
/Task3.6.py
329
4.21875
4
place=int(input("Enter the number of your seat on the train: ")) if (place<=0) or (place>53): print("Incorect date") else: if place%2==0: print("place on top") else: print("place bottom") if place>35: print("place in side") else: print("place in conpartment ")
true
c50044c0a3c3322c91c86c7b76f2c6fe7c3a8fc4
Niira/Python_04.04.19
/100 раз подряд в квадрате.py
591
4.15625
4
# Курс основы программирования на Python # Задание по программированию: 100 раз подряд в квадрате # 08.04.2019 # # Заданное число N записали 100 раз подряд и затем возвели в # квадрат. Что получилось? # # Формат ввода # # Вводится целое неотрицательное число N не превышающее 1000. # # Формат вывода # # Выведите ответ на задачу. a = input() print(int(a * 100)**2)
false
1de0b04856cf322ee10b1ed8f67e7375224a0895
cugis2019dc/cugis2019dc-s-navya
/day3.py
2,456
4.40625
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 31 10:33:39 2019 @author: STEM """ # example 1; listing numbers of chocolate Darkchocolate = 5 Milk = 6 White = 8 print(White) #example 2: creating variables for the number of chcolates only def cadburyBox(cadbury1,cadbury2,cadbury3): print ("There are",cadbury1,"milk chocolates",cadbury2,"dark chocolates, and",cadbury3,"white chocolates") cadburyBox (6,5,8) #example 3; longest way creating variables for amount of chocolate and name of chocolate cadbury1 = "Milk Chocolate" cadbury2 = "Dark Chocolate" #here we are making variables for the chocolate types cadbury3 = "White Chocolate" def cadburyBox(m,d,w): # now we are making a function to allow people to adjust the number of choclates print ("There are",m,cadbury1,d,cadbury2,",and",w,cadbury3) #we print the amt and type and substitue in both types of variables cadburyBox (6,5,8) #now we plug in the amt of each type of chocolate #using DICT to make code concise choc1 = {"cadburymilk":6} choc2 = {"cadburydark":5} choc3 = {"cadburywhite":8} print(choc1,choc2,choc3) #eveneven more concise chocolatebox = {"dark":5,"milk":6,"white":8} #one line code practice; a list within a list studentlist = [["steve",32,"M"], ["lia",28,"F"], ["vin", 45, "M"], ["katie",38,"f"]] #run the code below to get the list above to appear as a list in the console import pandas dir(pandas) studentdf = pandas.DataFrame(studentlist, columns =("name","age","gender")) studentdf #chocolates in list form chocolatelist = [["milk",6], ["dark",5], ["white",8]] chocodf = pandas.DataFrame(chocolatelist, columns =("type","quantity")) print(chocodf) #students in list form and graphing studentlist = [["steve",32,"M"], ["lia",28,"F"], ["vin", 45, "M"], ["katie",38,"f"]] studentlist studentdf = pandas.DataFrame(studentlist, columns =("name","age","gender")) studentdf studentdf2 = pandas.DataFrame(studentlist, columns =("name","age","gender"), index = ["1","2","3","4"]) studentdf2 import plotly dir(plotly) from plotly.offline import plot import plotly.graph_objs as go studentbar = go.Bar(x=studentdf["name"],y=studentdf["age"]) plot([studentbar]) #graphing chocolate bar titles = go.Layout (title = "number of chocolates by type") chocolatebar = go.Bar(x=chocodf["type"],y=chocodf["quantity"]) fig = go.Figure(data= [chocolatebar], layout=titles) plot(fig)
true
990cc755fc4673d100f3e96e6db5bf57c30d2b2b
mick-io/codesignal
/arcade/python/7_simple_sort.py
1,642
4.21875
4
"""Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. To understand how efficient the built-in Python sorting function is, you decided to implement your own simple sorting algorithm and compare its speed to the speed of the Python sorting. Write a function that, given an array of integers arr, sorts its elements in ascending order. Hint: with Python it's possible to swap several elements in a single line. To solve the task, use this knowledge to fill in both of the blanks (...). Example For arr = [2, 4, 1, 5], the output should be simpleSort(arr) = [1, 2, 4, 5]. Input/Output [execution time limit] 4 seconds (py3) [input] array.integer arr Guaranteed constraints: 1 ≤ arr.length ≤ 500, -105 ≤ arr[i] ≤ 105. [output] array.integer The given array with elements sorted in ascending order. """ def simpleSort(arr): n = len(arr) for i in range(n): j = 0 stop = n - i while j < stop - 1: if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] j += 1 return arr if __name__ == "__main__": assertions = [ # [(arr, expect)...] ([2, 4, 1, 5], [1, 2, 4, 5]), ([3, 6, 1, 5, 3, 6], [1, 3, 3, 5, 6, 6]), ([100], [100]), ([-1, -2, 0], [-2, -1, 0]), ([100, 100, 100], [100, 100, 100]), ([1], [1]) ] for arr, expect in assertions: out = simpleSort(arr) if out != expect: e = f"[FAIL] simpleSort({arr}) == {out} expect {expect}" raise assertions(e) print("[PASSED]")
true
10239da9ba6ffe499af26b4e47ef0215644b72de
balbinfurio/higher_level_programming
/0x04-python-more_data_structures/7-update_dictionary.py
311
4.125
4
#!/usr/bin/python3 def update_dictionary(a_dictionary, key, value): x = {key: value} a_dictionary.update(x) return (a_dictionary) def print_sorted_dictionary(new_dict): # imprimir dicts por elemento de forma "sort" for i in sorted(new_dict): print("{}: {}".format(i, new_dict[i]))
true
2f6723e0d24aeaae6045f24d9a9f9af64d0bae91
3rrorBaralasch/SmallStuff
/Calculator.py
1,385
4.1875
4
def helpFunc(): print (""" Welcome to my Program, here you can do Text Mathematical Calculations. ...................................................................... (!) Help -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Functions: For Division--------------[D] For Multiplication--------[M] For Addition--------------[A] For Subtraction-----------[S] For Help------------------[H] To exit programm----------[E] """) def userInput(): num1 = input("Input your first number: ") num2 = input("Input your second number: ") return num1,num2 def main(): CalcType = input("Please choose which calculation do you want to use: ") if CalcType == "D": num1,num2 = userInput() sum = float(num1)/float(num2) print(sum) elif CalcType == "M": num1,num2 = userInput() sum = float(num1)*float(num2) print(sum) elif CalcType == "A": num1,num2 = userInput() sum = float(num1)+float(num2) print(sum) elif CalcType == "S": num1,num2 = userInput() sum = float(num1)-float(num2) print(sum) elif CalcType == "H": helpFunc() elif CalcType == "E": exit() else: print("\nPlease type correct function name ;)\n") main() #Calling Functions helpFunc() main()
true
8d89099b3a3b058636737bb05bb5a5c5cb5617e6
gateway17/holbertonschool-higher_level_programming
/0x08-python-more_classes/1-rectangle.py
2,422
4.15625
4
#!/usr/bin/python3 """ Write a class Rectangle that defines a rectangle by: (based on 0-rectangle.py) Private instance attribute: width: property def width(self): to retrieve it property setter def width(self, value): to set it: width must be an integer, otherwise raise a TypeError exception with the message width must be an integer if width is less than 0, raise a ValueError exception with the message width must be >= 0 Private instance attribute: height: property def height(self): to retrieve it property setter def height(self, value): to set it: height must be an integer, otherwise raise a TypeError exception with the message height must be an integer if height is less than 0, raise a ValueError exception with the message height must be >= 0 Instantiation with optional width and height: def __init__(self, width=0, height=0): You are not allowed to import any module """ class Rectangle: """Set a rectangle, Arg size of rectangle""" def __init__(self, width=0, height=0): """Initialize values for width and height""" if not isinstance(width, int): raise TypeError('width must be an integer') elif width < 0: raise ValueError('width must be >= 0') elif not isinstance(height, int): raise TypeError('height must be an integer') elif height < 0: raise ValueError('height must be >= 0') else: self.__width = width self.__height = height @property def width(self): """getter for width. """ return self.__width @width.setter def width(self, value): """ Setter for width.""" if not isinstance(value, int): raise TypeError('width must be an integer') elif value < 0: raise ValueError('width must be >= 0') else: self.__width = value @property def height(self): """ getter for width.""" return self.__height @height.setter def height(self, value): """Setter for height""" if not isinstance(value, int): raise TypeError('height must be an integer') elif value < 0: raise ValueError('height must be >= 0') else: self.__height = value
true
d05f9b602f79c417b8a2a5213b3fe96ab59b8912
gateway17/holbertonschool-higher_level_programming
/0x03-python-data_structures/3-print_reversed_list_integer.py
568
4.5625
5
#!/usr/bin/python3 # Write a function that prints all integers of a list, in reverse order. # # Prototype: def print_reversed_list_integer(my_list=[]): # Format: one integer per line. See example # You are not allowed to import any module # You can assume that the list only contains integers # You are not allowed to cast integers into strings # You have to use str.format() to print integers def print_reversed_list_integer(my_list=[]): var = len(my_list) while var > 0: print("{:d}".format(my_list[var - 1])) var -= 1
true
aabe501115b14636054ce1ae6693886aa33d8a3a
gateway17/holbertonschool-higher_level_programming
/0x05-python-exceptions/2-safe_print_list_integers.py
1,154
4.25
4
#!/usr/bin/python3 """ Write a function that prints the first x elements of a list and only integers. Prototype: def safe_print_list_integers(my_list=[], x=0): my_list can contain any type (integer, string, etc.) All integers have to be printed on the same line followed by a new line - other type of value in the list must be skipped (in silence). x represents the number of elements to access in my_list x can be bigger than the length of my_list - if it’s the case, an exception is expected to occur Returns the real number of integers printed You have to use try: / except: You have to use "{:d}".format() to print an integer You are not allowed to import any module You are not allowed to use len() """ def safe_print_list_integers(my_list=[], x=0): ctr = 0 for i in range(x): try: print("{:d}".format(my_list[i]), end="") ctr += 1 except (TypeError, ValueError): continue except IndexError: break print() return ctr
true
074e6a6ff06ab012bd1069e8d9c88314ac97dd3b
gateway17/holbertonschool-higher_level_programming
/0x03-python-data_structures/6-print_matrix_integer.py
745
4.21875
4
#!/usr/bin/python3 # Write a function that prints a matrix of integers. # Prototype: def print_matrix_integer(matrix=[[]]): # Format: see example # You are not allowed to import any module # You can assume that the list only contains integers # You are not allowed to cast integers into strings # You have to use str.format() to print integers def print_matrix_integer(matrix=[[]]): ctr1 = 0 ctr2 = 0 while ctr1 < len(matrix): while ctr2 < len(matrix[ctr1]): if ctr2 == (len(matrix[ctr1]) - 1): print("{:d}".format(matrix[ctr1][ctr2])) else: print("{:d} ".format(matrix[ctr1][ctr2]), end="") ctr2 += 1 ctr2 = 0 ctr1 += 1
true
c8795dd672e363f5aae4fe1df78326b7101edc48
gateway17/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.py
540
4.25
4
#!/usr/bin/python3 """ Write a function that appends a string at the end of a text file (UTF8) and returns the number of characters added: Prototype: def append_write(filename="", text=""): If the file doesn’t exist, it should be created You must use the with statement You don’t need to manage file permission or file doesn't exist exceptions. You are not allowed to import any module """ def read_file(filename=""): """Reads a file. """ with open(filename, 'r') as buffer: print(buffer.read())
true
c260ce089ef6a3c86373c93f4cfeca7e5272c313
gioung/practice01
/prob08.py
313
4.21875
4
# 문자열을 입력 받아, 해당 문자열을 문자 순서를 뒤집어서 반환하는 함수 reverse(s)을 작성하세요 string = input('입력> ') def reverses(string): size = len(string) for i in range(size, 0, -1): print(string[i-1], end='') len(string) != 0 and reverses(string)
false
6be7ca21623214baf5c5c28b8fd6d47a0d80d0db
mgarmos/LearningPython
/RegularExpression/Pr01.py
1,612
4.34375
4
# Search for lines that contain 'From' import re hand = open('mbox-short.txt') for line in hand: line = line.rstrip() if re.search('From:', line): #equivalent line.find() print(line) hand.close() print('----------') # Search for lines that start with 'From' hand = open('mbox-short.txt') for line in hand: line = line.rstrip() #equivalent line.startswith() if re.search('^From:', line): print(line) hand.close() print('----------') """ . Character matching in regular expressions ^ Start of line """ #The most commonly used special character is the period or full stop, which matches any character hand = open('mbox-short.txt') for line in hand: line = line.rstrip() #equivalent line.startswith() if re.search('F..m', line): print(line) hand.close() print('----------') """ EXTRACTING DATA USING REGULAR EXPRESSIONS * zero-or-more characters + one-or-more of the characters """ # Search for lines that start with From and have an at sign hand = open('mbox-short.txt') for line in hand: line = line.rstrip() if re.search('^From:.+@', line): print(line) hand.close() print('----------') # Search for lines that start with From and have an at sign hand = open('mbox-short.txt') for line in hand: line = line.rstrip() if re.search('\S+@.*\.org', line): print(line) hand.close() print('----------') #If we want to extract data from a string in Python we can use the findall() #method to extract all of the substrings which match a regular expression s = 'A message from csev@umich.edu to cwen@iupui.edu about meeting @2PM' lst = re.findall('\S+@\S+', s) print(lst)
true
13bc1600746b012efe03e865914e02d835822f59
mgarmos/LearningPython
/AutomateBoringStuff/FindingPatternsTextwithRegularExpressions.py
905
4.21875
4
# Finding Patterns of Text with Regular Expressions import re # Creating Regex Objects phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') miText = 'My number is 415-555-4242. My number is 245-535-4742.' matchingObject = phoneNumRegex.search(miText) print(matchingObject.group(0)) # 415-555-4242 # Se definen dos grupos mediante parentesis phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') matchingObject = phoneNumRegex.search(miText) print(matchingObject.group(0)) # 415-555-4242 print(matchingObject.group(1)) print(matchingObject.group(2)) # Se definen dos grupos mediante parentesis phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') matchingObject = phoneNumRegex.findall((miText)) print(matchingObject) # Se definen dos grupos mediante parentesis phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') matchingObject = phoneNumRegex.findall((miText)) print(matchingObject)
false
ca561a8b613e7e24a1733c3aee62e3587b25d909
aryan-upa/learn-python39
/lab-python/panagram_string.py
675
4.125
4
""" Determine if a sentence is a pangram. A pangram is a sentence using every letter of the alphabet at least once. The best known English pangram is: “The quick brown fox jumps over the lazy dog”. The alphabet used consists of ASCII letters A to Z, inclusive, and is case insensitive. Input will not contain non-ASCII symbols. """ st = input().lower() for i in map(chr, range(97, 123)): if i not in st: print('Not a Panagram String ') break else: print('Panagram String ') # using set st = set(input()) alpha_set = set(map(chr, range(97, 123))) if not len(alpha_set - st): print('Panagram ') else: print('Not Panagram ')
true
e28acb120d1e1a3b73933105aba5a26b931f9a4c
maybe-william/holbertonschool-higher_level_programming
/0x08-python-more_classes/7-rectangle.py
2,188
4.21875
4
#!/usr/bin/python3 """ This module defines a rectangle. """ class Rectangle: """ A rectangle """ number_of_instances = 0 """ the number of rectangle instances in existence """ print_symbol = '#' """ the print symbol""" def __verify_int(self, value, tp): """ Verify an int """ if type(value) is not int: raise TypeError(tp + ' must be an integer') if value < 0: raise ValueError(tp + ' must be >= 0') def __str__(self): """ Return a string representation """ rect = (((str(self.print_symbol) * self.width) + '\n') * self.height) if rect == '' or rect == '\n' * self.height: return '' return rect[:-1] def __repr__(self): """ Return an evalable rectangle representation """ ret = 'Rectangle({:d}, {:d})'.format(self.width, self.height) return ret def __del__(self): """ Detect object deletion """ print('Bye rectangle...') Rectangle.number_of_instances = Rectangle.number_of_instances - 1 def __init__(self, width=0, height=0): """ Create a rectangle """ self.__verify_int(width, 'width') self.__width = width self.__verify_int(height, 'height') self.__height = height Rectangle.number_of_instances = Rectangle.number_of_instances + 1 @property def width(self): """ Get width """ return self.__width @width.setter def width(self, value): """ Set width """ self.__verify_int(value, 'width') self.__width = value @property def height(self): """ Get height """ return self.__height @height.setter def height(self, value): """ Set height """ self.__verify_int(value, 'height') self.__height = value def area(self): """ Return the area """ if self.width == 0 or self.height == 0: return 0 return self.width * self.height def perimeter(self): """ Return the perimeter """ if self.width == 0 or self.height == 0: return 0 return 2 * self.width + 2 * self.height
true
ba3d7018e5a13bb4f94c74ba571c394a4f94422b
ElielMendes/Exercicios-da-Faculdade-e-projeto-de-Numerologia-Karmica
/.vscode/aula4.py/ex9.py
529
4.125
4
print("Linha de Crédito para Estatuários") salario = float(input("Digite o valor do seu salário bruto: ")) emprestimo = float(input("Digite o valor de empréstimo desejado: ")) numero_prest = float(input("Deseja parcelar em quantas prestações? ")) prestacao = emprestimo/numero_prest print("Salário Bruto: " , (salario)) print("Valor da prestação: R$ " , (prestacao)) if prestacao <= salario*30/100: print("empréstimo concedido") else: print("empréstimo não pode ser concedido") print("processo encerrado")
false
884695b6c9a49aa335cc0df94c32e3b9cbd01268
alenasf/advanced_topics_in_python
/json_example.py
2,398
4.1875
4
import json """Example_1: Using JSON with Python json.loads(convert JSON string into Python dict) json.load(convert JSON file into Python dict) json.dumps(convert Python dict into JSON string) json.dump(convert Python dict into JSON file) """ # open the file example.json. Convert JSON file to dict f = open("example.json") # load and print the data from example.json file print(json.load(f)) # save data as var 'json_data'. json_data = json.load(f) print(type(json_data)) """Example_2:""" # GET List of the countries.Convert JSON file to dict f = open("example.json") json_data = json.load(f) countries = json_data['countries'] # print(countries) # loop for all countries for country in countries: print(country) # print individual country for country in countries: print(country['name'], country['capital']) """Example_3""" # Convert JSON string to dict json_string = ''' { "countries" : [ { "name": "usa", "capital": "Washington", "west": true }, { "name": "canada", "capital": "Ottava", "west": true }, { "name": "japan", "capital": "Tokyo", "west": false } ] } ''' json_data = json.loads(json_string) countries = json_data['countries'] for country in countries: print(country['name'],country['capital']) """Example_4""" # Convert Python dict to JSON string json_string = ''' { "countries" : [ { "name": "usa", "capital": "Washington", "west": true }, { "name": "canada", "capital": "Ottava", "west": true }, { "name": "japan", "capital": "Tokyo", "west": false } ] } ''' json_data = json.loads(json_string) json_string_from_dict = json.dumps(json_data, indent=4, sort_keys=True) print(json_string_from_dict) """Example_5""" # Convert Python dict to JSON file dump.json json_string = ''' { "countries" : [ { "name": "usa", "capital": "Washington", "west": true }, { "name": "canada", "capital": "Ottava", "west": true }, { "name": "japan", "capital": "Tokyo", "west": false } ] } ''' json_data = json.loads(json_string) f = open("dump.json", "w") json.dump(json_data, f, indent=4, sort_keys=True)
true
06b0d5d6985c1e54a0834d42bf7101a3faefa6bf
projectinnovatenewark/csx
/Students/Semester2/lessons/students/3_classes_and_beyond/19_try_except_finally/19_try_except_finally.py
2,389
4.4375
4
""" try/except/finally with error handling """ # here, we will try to open a test.txt file. Since there is no test.txt file, # we will raise an exception using "except". Since our try creates an error then the # exception will be raised, and the finally code block executes thereafter. try: f = open("test.txt", 'r') data = f.read() print("Trying") except: print("Fiddlesticks! Failed") finally: print("Finally!") print("All Done") # This is the same code as above, except that the "else" block will ONLY happen if there is no error. # Finally will happen whether there is an error or not. Else will only happen if there is no error. try: f = open("test.txt", 'r') data = f.read() print("Trying") except: print("Fiddlesticks! Failed") else: print("Finally!") print("All Done") # when using explicit error handling, its important to handle errors efficiently. # With try/except/finally's, an IOError is the most common type to be served. # So, let's try it this way try: f = open("test.txt", "r") try: data = f.read() print(data) except IOError as e: print("IO Error", e) except: print("unknown error") finally: f.close() except: print("Fiddlesticks! Failed") finally: print("All Done") # this is a cleaner way to do the same thing as above. # When we use the "with-as" tags, it automatically executes the # open and subsequent "close" tag. Now the above function looks # a lot cleaner and can be done in less lines of code try: with open("test.txt", "r") as f: data = f.read() print(data) except IOError as e: print(e) except: print("Fiddlesticks! Failed") finally: print("Finally! We iz done!") print("All Done") # this function does something similar to a try/except # In the code above, you can see we created a class called BadNumbrersError. # Then in our function, we added a check. If x==3, then raise a BadNumbersError # exception and pass in the text “We don’t like the number 3”. # This is a simple way to raise a custom exception using a python class. # 'pass' is used for no particular reason. It is there purely for syntax reasons. class BadNumbersError(Exception): pass def addnumbers(x, y): if x == 3: raise BadNumbersError("We don't like the number 3") return x+y print(addnumbers(3, 2))
true
487d16afcb27a53d2ec35917185d927da14de8f1
projectinnovatenewark/csx
/Students/Semester2/lessons/archive/20_advanced_functions/20_advanced_functions_and_args.py
2,318
4.96875
5
""" Learning more advanced functions and navigating loops through dictionaries """ # *args being set in a function's parameters allows additional arguments to be passed. They will # turn into a tuple named after what you put following the asterisk. **kwargs being set in a function's # parameters allows additional arguments to be passed as a key/value pair in a dictionary. The dict # will be named after what you put following the two asterisks. Remember- the difference between # *args and **kwargs parameters depends on the number of asterisks you place before the name. # The "bread" and "meat" parameters are considered positional. They are considered positional # because the order in which you pass the arguments matters. The first argument passed would assume # the alias of "bread" and the second would assume the alias of "meat". def set_sandwich(bread, meat): print(f"{bread} bread and {meat} meat") # These two are considered positional arguments, since their position matters when calling the function. set_sandwich("Wheat", "Turkey") # The "ingredients" *args would take all non-positional arguments and create a tuple of them. Recall- # a tuple is an immutable list (immutable = can't be changed). def make_sandwhich(bread, *ingredients): print(f"The bread is {bread}") print(ingredients) make_sandwhich("Rye", "Turkey", "Swiss", "Lettuce", "Mayo") make_sandwhich("Burnt", "Cheese") # When you add **kwargs as a parameter in a function, the name of your kwargs becomes a dictionary # within that function. def build_profile(f_name, l_name, **user_info): # Here we are adding key/value pairs to our "user_info" dictionary print(f"user info dict before adding first and last name as key value pairs: {user_info}") user_info["first_name"] = f_name user_info["last_name"] = l_name # This is the way you'll want to iterate through a dictionary moving forward. # The way we showed prior was to give a background understanding of dictionaries. for key, val in user_info.items(): print(f"The key is: {key}, and the value is: {val}.") # User info is now a dictionary with all relevant values. Let's return that! return user_info user_profile = build_profile("Marky", "Mark", sport = "basketball", residence = "South Orange") print(user_profile)
true
af342b751513b419b0e7c8e875eb956996189c8a
projectinnovatenewark/csx
/Students/Semester1/lessons/2_python/13_classes/13_classestodo.py
1,380
4.5
4
""" Creating classes for your classmates """ # TODO: Section 1 # Define a class of "Dog". Ensure that all of the class instantiations of "Dog" have a # property of "animal_type" set to "mammal". This dog should have some attributes set # in it's init function including name, breed, and age. # TODO: # Instantiate an instance of the "Dog" class named "Fido". Fido is a 3 year old Bulldog. You can # store the instantiated class in a variable "fido". Then print the following statement using f # shorthand: "Fido is a 3 year old Bulldog." #################################################################################################### # TODO: Section 2 # Define a method, "country_info", for the below class of "Country". When called, the method should # print the the following statement using f shorthand: "{country} is {age} years old with a # population of {population} people." # HINT: Does the method need any parameters besides "self"? # Instantiate the class defined below with the correct data types for each attribute. Make sure to # assign the right type of data to the class instantiation based on it's name. Then call the method # "country_info". class Country: def __init__(self, name, age, population, colors): # HINT: What data type should colors be? self.name = name self.age = age self.population = population self.colors = colors
true
1dfad88b9ee12061af4d188b603464df6f1afd4b
danieldizzy/CodeCademy
/NumberGuess_new.py
1,595
4.625
5
""" We'll build a program that rolls a pair of dice and asks the user to guess a number. Based on the user's guess, the program should determine a winner. If the user's guess is greater than the total value of the dice roll, they win! Otherwise, the computer wins. The program should do the following: Randomly roll a pair of dice Add the values of the roll Ask the user to guess a number Compare the user's guess to the total value Decide a winner (the user or the program) Inform the user who the winner is """ from random import randint from time import sleep def get_user_guess(): user_guess = int(input('Guess a number :')) return user_guess def roll_dice(number_of_sides): first_roll = randint(1, number_of_sides) second_roll = randint(1, number_of_sides) max_val = int(number_of_sides * 2) print('The Maximum Value is : %s ' % max_val) sleep(1) user_guess = get_user_guess() if user_guess > max_val: print('Wrong value ') return else: print('Rolling...') sleep(2) print(' The First roll is %d ' % first_roll) sleep(1) print(' The Second roll is: %d ' % second_roll) sleep(1) total_roll = first_roll + second_roll print(' The total roll is: %d' % total_roll) sleep(1) print('Result...') sleep(1) if user_guess > total_roll: print('You Won!') return else: print('Sorry You Lost...Try Again') return roll_dice(6) """ """
true
41c7d53e3408dc93aeb4917bf542efa2e1b3a1a1
danieldizzy/CodeCademy
/RockScissorsPaper.py
2,298
4.5
4
"""In this project, we'll build Rock-Paper-Scissors! The program should do the following: Prompt the user to select either Rock, Paper, or Scissors Instruct the computer to randomly select either Rock, Paper, or Scissors Compare the user's choice and the computer's choice Determine a winner (the user or the computer) Inform the user who the winner is """ from time import sleep from random import randint # Creating a list 'R', 'S', 'P' and storing it as string options = ['R', 'S', 'P'] # Set the win or Loose messages LOOSE_MESSAGE = 'You Lost!!' WIN_MESSAGE = 'You Won !!' # the function to decide the winner between parameters from the computer_choice and user_choice, and print some functions def decide_winner(user_choice, computer_choice): print('You selected : %s ' % user_choice) print('Computer Selecting....') sleep(1) print('The Computer selected : %s' % computer_choice) print('Computer Selecting....') sleep(1) user_choice_index = options.index(user_choice) computer_choice_index = options.index(computer_choice) if user_choice_index == computer_choice_index: print('It\'s a tie') elif user_choice_index == 0 and computer_choice_index == 2: print('You Win!!') elif user_choice_index == 1 and computer_choice_index == 0: print('You Win!!') elif user_choice_index == 2 and computer_choice_index == 1: print('You Win !!') elif user_choice_index > 2: print('Wrong Choice, Try again !!') return else: print('You Lost') def play_rps(): print('Welcome to the Rock Scissors Paper Game !!') user_choice = input('Select R for Rock, P for Paper, or S for Scissors: ') user_choice = user_choice.upper() # computer_choice = options[randint(0, 2)] computer_choice = options[randint(0, len(options) - 1)] decide_winner(user_choice, computer_choice) play_rps() # n = [3, 5, 7] # # # def total(numbers): # result = 0 # for i in numbers: # result = result + i # return result # print total(n) # # def total1(numbers): # result = 0 # for i in range (0,len(numbers)): # result += numbers[i] # return result # print total1 (n)
true
7856ca6e19ec8120307027f641d2bbd5c476406e
jtpunt/python
/palindrome.py
1,404
4.21875
4
# Author: Jonathan Perry # Date: 9/6/2018 import re import math # Iterates through n/2 characters of the string str, where the first half of the characters are checked # against the 2nd half of characters (where the 2nd half is in reversed order) match the first half of characters. # For example, assume we split the string in 2 seperate arrays, i and j. By using the ceil function, we can safely assume # both halves will have the same # of elements, regardless of whether or not our string has an even or odd # of characters. # i = [0, 1, 2, ... ceil(n / 2)] (first half - forward order) # j = [n, n-1, n-2, ... ceil(n / 2)] (second half - reverse order) # If our our string is a palindrome, then arrays i and j will contain the same elements in the same exact order and the # function will return true. If it does not contain the same elements, the function will return false. def isPalidrome(str): length=len(str) - 1 for _ in (i for i in range(0, math.ceil(length / 2)) if str[i] != str[length-i]): return False return True # first re call removes spaces, second re call removes non-alphabetical characters def cleanStr(uncleanStr): return re.sub(r'[^a-zA-Z]', '', re.sub(r'\s+', '', uncleanStr.lower())) def main(): sentence="A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!" sentence=cleanStr(sentence) print(isPalidrome(sentence)) if __name__ == "__main__": main()
true
12af2f2479387d120c84c3890549e28fcd968c4d
lemire/talks
/2022/evil/week2/parabolic.py
315
4.1875
4
import math v = float(input("What was the velocity of the throw? ")) angle = float(input("What was the angle of the throw? ")) g = 9.81 h = float(input("What was your intial height? ")) maxHeight = h + v*v * (math.sin(math.radians(angle)) * math.sin(math.radians(angle))) / (2 * g) print("maxheight = ", maxHeight)
true
b61e74e9dca19dd771ee679ad84a4da175dc8137
abhinav-m/python-playground
/tutorials/basics/data-structures/lists/lists_methods.py
988
4.21875
4
# index method which returns index of given value numbers = [1, 2, 3, 2, 5, 6] print(numbers.index(2)) # prints the first 2 found (index 1) # optional arguments -> start, stop # starts looking for given argument from index 1. print(numbers.index(2, 1)) # prints 1 # prints 3 print(numbers.index(2, 2)) names = ["Abhinav", "Athar", "Abhinav", "Abhinav", "Raju", "Athar", "Raju"] # start is inclusive , end is not -> will throw error on 3,4 print(names.index("Raju", 3, 5)) # prints count of a value in a list. cnt = names.count("Raju") print(cnt) # If value is not present, returns 0 , unlike index which throws error. print(names.count("akash")) # Logs 0 nums = [1, 2, 3, 4, 5] # Reverses list in place nums.reverse() print(nums) # sorts list in place nums = [5, 2, 1, 3, 6] nums.sort() print(nums) # join method -> string method which takes iterable argument # and joins them using the given delimiter. words = ["I", "am", "learning", "python"] print("#".join(words))
true
8fa4ea627354a68fb3c9c18c9d9c0df9fd39a266
abhinav-m/python-playground
/tutorials/basics/datatypes.py
1,037
4.1875
4
# Some common datatypes. # bool -> true/false test = True # Assigning true to test, notice capital T test_2 = False # Uppercase F for false. some_string = "A string" test_array = [1, 2, 3, 4] # List datatypes. print(type(test_array)) print(type(some_string)) print(test) # Python has dynamic data types. # Variable accomodates all sorts of data according to type. dynamic_var = 1 print(dynamic_var) dynamic_var = True print(dynamic_var) dynamic_var = "test" print(dynamic_var) dynamic_var = None # Special type for None values print(type(dynamic_var)) # Only one instance None of this class. # None -> Pythons version of null. new_var = None print(new_var) str_one = "hello" str_two = " world" print(str_one + str_two) # str_test = 8 + "test" this is not allowed in python. Strings cant be added to integers. # print(str_test) # conversion of data types. decimal = 12.3242 decimal_toint = int(decimal) # Notice it doesn't round, but 'chops' off the decimal part. print(decimal_toint) print(int(99.99)) print(str(22))
true
577370e276189e577e049eb70ad55bb68d457d0b
abhinav-m/python-playground
/tutorials/basics/math_example.py
319
4.71875
5
# Exponentiation operator -> ** print(2**3) # should print 8 # Can also be used for roots. print(81**0.5) # Note result is a float. print(27**0.33) # Cube root example. # Regular division returns floats. print(3/2) # This will result a float. # Integer division operator -> // print(3//2) # Returns an integer.
true
d88fbf65dc524e154212937ed5a19d97cb79a17e
abhinav-m/python-playground
/tutorials/basics/data-structures/dictionaries/dictionaries.py
1,068
4.25
4
# Dictionaries are a data structure consisting of key -value pairs (same as objects / maps in javascript or java) cat = {"name": "blue", "age": 3.5, "isCute": True} print(cat) # Another way to create a dictionary dictionary_2 = dict(name="Abhinav", age="25", works="b4s") print(dictionary_2) age_str = "age" # Accessing dictionary values. print(dictionary_2["name"]) print(dictionary_2["age"]) print(dictionary_2[age_str]) print("Values in dictionaries") # Accessing all dictionary values for value in cat.values(): print(value) print("Keys in dictionaries") # Accessing all dicionary keys for key in cat.keys(): print(key) # Accessing both inside loop for k, v in cat.items(): print(f"key is {k} value is{v} ") dictionary_abhinav = { "name": "Abhinav", "age": "25", "job": "Developer" } # Testing if a key is in a dictionary. print("name" in dictionary_abhinav) print("age" in dictionary_abhinav.keys()) print("sex" in dictionary_abhinav) # Testing if a value is in a dictionary. print("Abhinav" in dictionary_abhinav.values())
true
6951551ee31c550139a58adadd82ce1cf7a3d41d
vikendu/hackerrank-solutions
/check_prime.py
483
4.25
4
#Check if prime or not using preemptive methods Python def isprime(n): if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True in1 = int(input()) if in1 == 1: print("no") elif isprime(in1) == True: print("yes") else: print("no")
false
abb82c878df8cf3c6e393845a1cff6b17f0ca926
zssasa/Bioinformatics
/Bioinformatics6/week1/Trie.py
1,478
4.15625
4
# -*- coding: utf-8 -*- __author__ = 'zhangsheng' from pprint import pprint _end = '$' def make_trie(words): """ CODE CHALLENGE: Solve the Trie Construction Problem. Input: A collection of strings Patterns. Output: The adjacency list corresponding to Trie(Patterns), in the following format. If Trie(Patterns) has n nodes, first label the root with 0 and then label the remaining nodes with the integers 1 through n - 1 in any order you like. Each edge of the adjacency list of Trie(Patterns) will be encoded by a triple: the first two members of the triple must be the integers labeling the initial and terminal nodes of the edge, respectively; the third member of the triple must be the symbol labeling the edge. """ root = dict() for word in words: # print(word) # print(type(word)) current_dict = root for letter in word: # print(letter) current_dict = current_dict.setdefault(letter, {}) current_dict = current_dict.setdefault(_end, _end) return root def trie_tostr(root): s = [] def dump_leaf(curr,parent_id): current_id = parent_id + 1 for key, value in curr.items(): if (value == _end): continue s.append(str(parent_id)+'->'+str(current_id)+':'+key) current_id = dump_leaf(value,current_id) return current_id dump_leaf(root,0) return "\n".join(s) if __name__ == '__main__': with open('./data/trie_train.txt') as f: words = f.read().splitlines() t = make_trie(words) s = trie_tostr(t) pprint(t) print(s)
true
8cf209473b573803489634ce2f18be49c51e5094
baldure/first_git_project
/max_int.py
320
4.25
4
num_int = int(input("Input a number: ")) # Do not change this line num_2_int=num_int max_int=0 while num_2_int > 0: if num_2_int > max_int: max_int = num_2_int num_2_int = int(input("Input a number: ")) # Fill in the missing code print("The maximum is", max_int) # Do not change this line
true
bf1d93a5c0be8b746256fe975b7c8048a000982f
holland11/boat_datasatore_csc462_project
/trimmed_to_duplicated.py
1,524
4.21875
4
''' Program that takes a csv as input and returns a csv as output. The output csv will have duplicated rows from the input csv, but at least one column will be slightly modified for each duplicate so they aren't identical. ''' import csv import random num_duplicates = 200 # 200 = 2,500 rows -> 500,000 rows def main(): with open('trimmed.csv') as csv_in: csv_read = csv.reader(csv_in, delimiter=",") with open('duplicated.csv', 'w') as csv_out: csv_reader = csv.reader(csv_in, delimiter=",") csv_writer = csv.writer(csv_out, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: csv_writer.writerow(row) line_count += 1 j = 0 for col_header in row: print('{}: {}'.format(j, col_header)) j += 1 continue csv_writer.writerow(row) # write original for i in range(num_duplicates): multiplier = (random.random() * 0.2) + 0.85 # random number between 0.85 -> 1.15 new_row = row.copy() new_row[3] = new_row[3] + ' ({})'.format(i) # 4: Features (name of item) csv_writer.writerow(new_row) line_count += 1 if __name__ == "__main__": main()
true
a13ae691072772ea8c5f018129c4014116f50192
sdp43/BIOSC1640Project1
/pseudocode/calculateSphere.py
1,882
4.46875
4
def ritters_bounding_sphere(pointlist): """This definition uses Ritter’s algorithm to calculate a non-minimal bounding sphere for a set of points. The sphere calculated is likely to be 5-20% larger than the optimal sphere. :param pointlist: list of points for which sphere is to be calculated :type pointlist: list of 3d tuples :returns: radius of sphere :rtype: float :returns: center of sphere :rtype: 3d tuple""" #pick a random point x #find the point y in the set that has the largest distance from x #find the point z that has the largest distance from x #create a sphere with the center at the midpoint of y and z, and radius as half the distance from y to z #while there is a point outside the sphere: #create a new sphere including the outside point and the sphere #the new sphere has the same center and the new radius is the distance from the center to the outside point #return the radius and center of the sphere def distance(point1, point2): """This definition calculates the euclidean distance between two points :param point1: point from which distance is to be calculated :type point1: 3d tuple with x, y, z coordinates :param point2: point to which distance is to be calculated :type point2: 3d tuple with x, y, z coordinates :returns: distance between the two points :rtype: float""" return sqrt((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2) def point_in_sphere(point, center, radius): """This definition checks if a particular point is enclosed within the given sphere :param point: point to be checked :type point: 3d tuple :param center: center of the sphere :type center: 3d tuple :param radius: radius of the sphere :type radius: float :returns: whether the point is in the sphere or not :rtype: boolean""" #check if the distance of the point from the center is less than the radius #if yes, return true, else return false
true
537396c441a80fa859e210be3b7fc6c8cf56e6a8
sunnyvineethreddy/Python
/ICPS/ICP2/PythonICP2/gameboard1.py
345
4.125
4
heightinp= int(input("Enter the height of the board: ")) widthinp= int(input("Enter the width of the board: ")) def board_draw(heightinp,widthinp): for temp in range(heightinp): print(" --- " * widthinp) print("| " * widthinp, end="") print("|") print(" --- " * widthinp) board_draw(heightinp,widthinp)
true
eeb7395e824375ce65f34330f67f0e5a63c4b094
kuanglian1000/PythonBasic
/Inheritance.py
2,313
4.46875
4
# Create a Parent Class class Person: def __init__(self , fname , lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname , self.lastname) print(self.firstname + self.lastname) kl = Person("KL","CHENG") kl.printname() # Create a Child Class class Student(Person): pass k2 = Student("K2","PP") k2.printname() # Add the __init__() Function in the Child Class # 子類別加入 __init__()後會覆寫,就不再繼承父類別的__init()__ class Programmer(Person): def __init__(self , name , age): self.name = name self.age = age def printname(self): print(self.name) print(self.age) k4 = Programmer("Jassica",35) k4.printname() # 保有父類別的__init__(),在子類別的__init__()內呼叫父類別的__init__() class Programmer(Person): def __init__(self , fname , lname , age , skill): Person.__init__(self,fname,lname) self.age = age self.skill = skill def printSkill(self): print(self.skill , "is what I use.") k3 = Programmer("Kevin","Inn",28,"Python") k3.printSkill() k3.printname() # Use the super() Function # 讓子類別繼承所有方法及屬性 from its parent class Student(Person): def __init__(self,fname , lname): super().__init__(fname , lname) #寫法2:Notice:少1個self # Person.__init__(self,fname,lname) #寫法1 # Add Properties class Student(Person): def __init__(self,fname,lname): super().__init__(fname,lname) self.graduationyear = 2019 s = Student("Y","KK") print(s.graduationyear) class Student(Person): def __init__(self,fname,lname,year): super().__init__(fname,lname) self.graduationyear = year b = Student("A","BB",2016) b.printname() #Parent's printname()方法 print(b.graduationyear) # Add Methods # 如果子類別新增的方法與父類別方法同名,則父類別方法會被覆寫 # If you add a method in the child class with the same name as a function in the parent class # , the inheritance of the parent method will be overridden. class Student(Person): def __init__(self,fname,lname,year): super().__init__(fname,lname) self.graduationyear = year def welcome(self): print("Welcome", self.firstname , self.lastname, "to the class of" , self.graduationyear) c = Student("A","B",25) c.welcome()
false
772f2b75781eaaf260d2f7d706492d16cc96cf4b
dinhtq/coding_practice
/arrays/reverse_polish.py
1,779
4.40625
4
""" Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it. The expression is given as a list of numbers and operands. For example: [5, 3, '+'] should return 5 + 3 = 8. For example, [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] should return 5, since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5. You can assume the given expression is always valid. """ PLUS = '+' MINUS = '-' TIMES = '*' DIVIDE = '/' OPERANDS = [PLUS, MINUS, TIMES, DIVIDE] def rpn(expr): return False def assertEqual(a, b, desc): if (a == b): print('{} ... PASS'.format(desc)) else: print('{desc} ... FAIL: {a} != {b}'.format(desc=desc, a=a, b=b)) # tests desc = 'short list' expr = [5, 3, '+'] assertEqual(rpn(expr), 8, desc) desc = 'long list' expr = [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] assertEqual(rpn(expr), 5, desc) """ The way to implement Reverse Polish Notation is to use a stack. When we encounter a value, then we add it to the stack, and if we encounter an operator such as '+', '-', '*', or '/', then we pop the last two things off the stack, use them as terms on the operator, and then pop the resulting value back on the stack. At the end of the function there should only be one thing remaining on the stack, so we just return that. def rpn(expr): stack = [] for val in expr: if val in OPERANDS: term1, term2 = stack.pop(), stack.pop() if val == PLUS: stack.append(term1 + term2) elif val == MINUS: stack.append(term1 - term2) elif val == TIMES: stack.append(term1 * term2) elif val == DIVIDE: stack.append(term1 / term2) else: stack.append(val) return stack[0] """
true
c6127c192bb9ca8e951b91f6bb051ccfc25b9288
pusparajvelmurugan/ral
/pop.py
299
4.125
4
nterms = 10 n1 = 0 n2 = 1 count = 0 if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence upto",nterms,":") while count < nterms: print(n1,end=' , ') nth = n1 + n2 n1 = n2 n2 = nth count += 1
false
37607a20cdbfd82ec43867a00aa8f04a10b622ed
SiddhantAshtekar/python-algorithem-for-begginers
/chap_5/into_list.py
423
4.53125
5
# Data stucture # List ---->this chapter # ordered collection of items # you can store anything in lists int , float ,string numbers=[1,2,3,4] print(numbers) print(numbers[1]) words=['word1','word2','word3'] print(words) print(words[:2]) mixed =[1,2,3,4,"five","six",2.3,None] print(mixed[1:3]) mixed[1]='two' print(mixed) mixed[1:]="two" print(mixed) mixed[1:]=["three","four"] print(mixed)
true
357f4572713233319541705ddbdeb3447a32fad4
RJSPEED/DAY_ONE
/palindromes.py
246
4.125
4
def is_palindrome(input_string): """Eval lower case input_string value to same reversed value""" if input_string.casefold() == input_string.casefold()[::-1]: print("True") else: print("False") is_palindrome("tacocat")
false
ee028f9656663d29867e76989785dd802e98ec2a
jefflike/leetcode
/009. Palindrome Number/Palindrome Number.py
2,992
4.3125
4
''' __title__ = 'Palindrome Number.py' __author__ = 'Jeffd' __time__ = '4/23/18 10:57 PM' ''' ''' tips: Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up: Coud you solve it without converting the integer to a string? ''' # class Solution: # def isPalindrome(self, x): # """ # :type x: int # :rtype: bool # """ # if x >= 0: # if x // 10 == 0: # return True # else: # my_list = [] # i = 0 # while x // 10 > 0: # v = x % 10 # x = x // 10 # my_list.append(v) # i += 1 # my_list.append(x) # for count in range(i): # if my_list[count] != my_list[-(count+1)]: # return False # return True # # else: # return False # class Solution: # def isPalindrome(self, x): # """ # :type x: int # :rtype: bool # 340ms # """ # if x >= 0: # my_list = [] # i = 0 # while x // 10 > 0: # v = x % 10 # x = x // 10 # my_list.append(v) # i += 1 # my_list.append(x) # for count in range(i): # if my_list[count] != my_list[-(count+1)]: # return False # return True # # else: # return False # class Solution(object): # def isPalindrome(self, x): # """ # :type x: int # :rtype: bool # 312ms # 通过比较反转整数和原整数是否相等来判断回文。 # """ # if x < 0: # return False # # tmp = x # y = 0 # while tmp: # y = y*10 + tmp%10 # tmp = tmp//10 # return y == x class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool 若不想生成反转数字,可考虑将原整数的各个数字分离,逐个比较最前最后的数字是否相等。 332ms """ if x < 0: return False digits = 1 while x/digits >= 10: digits *= 10 while digits > 1: right = x%10 left = x//digits if left != right: return False x = (x%digits) // 10 digits //= 100 return True s = Solution() print(s.isPalindrome(12321))
true
212a7167d1d5bfb7205f02c0a9ebba4e41c09eb8
chapman-cpsc-230/hw4-agust105
/count_pairs.py
478
4.1875
4
""" File: count_pairs.py Copyright (c) 2016 Francis Agustin License: MIT Wrote a program that returns the number of occurrences of a pair of bases in a DNA strand. """ ['A', 'T', 'G', 'C'] def count_v2(dna,pair): i = 0 for AT in dna: if AT == pair: i += 1 return dna.count(pair) dna = 'ACTGGCTATCCATT' pair = "AT" n = count_v2(dna,pair) print '%s appears %d times in %s' % (pair,n, dna) # dna = 'ATGCGGACCTAT' print count_v2("ATGCGGACCTAT", "AT")
true
2e253d9af0bcd8f37ef35ada20ed7cde761c9ea6
kmalakhova/grokking_algorithms
/01_introduction_to_algorithms/01_binary_search.py
668
4.1875
4
def binary_search(sorted_list,value): ''' Returns the amount of steps needed to guess the given value. If value exists in sorted_list, return its sequence number. if not, return None. Assume the list is sorted from smallest to largest. ''' low = 0 high = len(sorted_list) - 1 while low <= high: mid = (low + high) / 2 # as integar guess = sorted_list[mid] if guess == value: return mid elif value > guess: low = mid + 1 elif value < guess: high = mid -1 return None list1 = [1,3,5,6,8,90,] print binary_search(list1,6) print binary_search(list1,10)
true
bfb03dee83fa21c107bcd73db1890eb91fd7850b
yosoydead/exercises
/encrypt this/file.py
1,725
4.375
4
#string = "Hello world this is a sample text" #string = "A wise old owl lived in an oak" string = "The more he saw the less he spoke" def x(string): result = "" #if the string is empty, return an empty string if string == "": return "" else: #split the string into an array containing each word as a separate value for item in string.split(): wordsFirstLetter = ord(item[0]) #if the word has only 2 letters, concat the first letter with the #second one and then append the word to result if len(item) == 2: currentWord = str(wordsFirstLetter) + item[1] print(currentWord) result += (currentWord + " ") #if the word is a single letter, append that letter to the result elif len(item) == 1: print(wordsFirstLetter) result += (wordsFirstLetter + " ") #if it has more than 2 letters, it means i have to store the second letter, #store the last one and the substring from the third letter up to the last letter #this makes it easy to create a word with the second and last letters swapped #and inbetween them to add the rest of the substring else: secondLetter = item[1] lastLetter = item[len(item)-1] theRest = item[2:len(item)-1] bla = str(wordsFirstLetter) + lastLetter + theRest + secondLetter print(bla) result += (bla+ " ") #i use the strip method to remove any leading or trailing whitespaces return result.strip() # print(item) print(x(string))
true
c54a93bc172879dfeaa10cf4abd8261d1bf3c796
yosoydead/exercises
/playing with digits/file.py
1,187
4.125
4
#the main function def bla(number, start): #this is the inner function #it made it easier for me to execute the calculations #this way i don't modify either parameter given def inner(): #for ease of use, i converted the number param into a string to iterate #over it one character at a time backUp = str(number) result = 0 #this is a way for me to increase the step parameter #starting at the value of start and increase its value by 1 every time #the loop executes step = start for item in backUp: #print(pow(int(item), step)) #calculate the result of the current digit to the power of the current step result += pow(int(item), step) #increase the step variable at each loop execution step += 1 #print(item) #just returning the total of each digit of the number param raised to the step added together return result #save the result returned by the inner function item = inner() if item % number == 0: return item // number else: return -1 #returns 51 print(bla(46288, 3))
true
f44605e7763eb0fd7c96a34ce345bb6f029d3cf8
ComteAgustin/learning-py
/conditionals.py
672
4.625
5
# Conditionals # Comparisons operators 3 > 2 # Greater-than 3 < 2 # less-than 3 == 3 # same-than 3 != 2 # not same-than 3 <= 2 # less and same-than 3 >= 5 # greater and same-than # Logical operators 3>2 and 2>2 # if both conditions are true, return true 3>2 or 2>2 # need one of the conditions true, for return true not(3>2) # the condition must be false, for return true # if, do an action if the conditions is true if 3 == 3: print('is the same number') elif 3 < 2 : # elif is an other condition print('not is the same, but yes is less') else: # else is an action that be executed if the other conditions non be true print('not is the same number')
true
e92ed493e4300ed2c9f052cf9f3929333070cbd7
suetarazi/Buchalkas-python
/guessinggame.py
1,094
4.125
4
answer = 5 print("Please guess a number between 1-10: ") guess = int(input()) if guess == answer: print("yup, you got it!") else: if guess < answer: print("please guess higher") else: print("Please guess lower") guess = int(input()) if guess == answer: print("Yup!") else: print("Sorry, try again!") # if guess != answer: # if guess < answer: # print("please guess higher") # else: # print("Please guess lower") # guess = int(input()) # if guess == answer: # print("yup, you got it!") # else: # print("Sorry, try again!") # if guess < answer: # print("Please guess higher") # guess = int(input()) # if guess == answer: # print("You guessed it!") # else: # print("Sorry you have not guessed correctly") # elif guess > answer: # print("Please guess lower") # guess = int(input()) # if guess == answer: # print("Yup, you're right!") # else: # print("you have not guessed correctly") # else: # print("You got it!")
false
4a8a868b6f5ec259da9feeec52bb13c7a7c1403d
mcgeorgiev/Python-and-Pi_Workshop
/examples/1_hello.py
653
4.28125
4
# this is a comment. use to annotate your programmes # programmes are generally read top to bottom # this is a print function. it will display text on screen print('Hello, world.') print('Today is Tuesday the 16th of February') # this is a variable. it is a placeholder for some information animal = 'cat' # you can print variables print(animal) # # these are variables, but the information is inputted by the user # using an input function my_name = input('What is your name: ') my_age = input('What is your age: ') # you can combine strings(text) and variables in a print function print('Your name is ' + my_name) print('Your age is ' + my_age)
true
5080a821ba140287f90c8fc55600ee754a50edf7
Tanuka-Mondal/Python
/diff and double.py
423
4.25
4
#Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference. def difference(n): if n <= 17: return 17 - n else: return (n - 17) * 2 num = int(input("Enter a number: ")) dif = difference(num) print("The ans is: "+ str(dif)) #OUTPUT Enter a number: 23 The ans is: 12 Enter a number: 12 The ans is: 5
true
8ae569baaeccecb572fc396056034e156bb0de69
afcarl/machine-learning-python-examples
/supervised-learning/02-find-best-k-by-looping.py
1,643
4.3125
4
# This example uses the digits dataset to illustrate how to find the best k # value using for loop # Outcome: A plot of k vs prediction accuracy # Import necessary modules from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt # Load the digits dataset digits = datasets.load_digits() # Create feature and target arrays X = digits.data y = digits.target # Split into training and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y) # Setup arrays to store train and test accuracies neighbors = np.arange(1, 9) train_accuracy = np.empty(len(neighbors)) test_accuracy = np.empty(len(neighbors)) # Loop over different values of k for i, k in enumerate(neighbors): # Setup a k-NN Classifier with k neighbors: knn knn = KNeighborsClassifier(n_neighbors=k) # Fit the classifier to the training data knn.fit(X_train, y_train) # Compute accuracy on the training set train_accuracy[i] = knn.score(X_train, y_train) # Compute accuracy on the testing set test_accuracy[i] = knn.score(X_test, y_test) # Generate plot plt.title('k-NN: Varying Number of Neighbors') plt.plot(neighbors, test_accuracy, label='Testing Accuracy') plt.plot(neighbors, train_accuracy, label='Training Accuracy') plt.legend() plt.xlabel('Number of Neighbors') plt.ylabel('Accuracy') plt.show()
true
3b5bdc032b47fca6316662bb2078a7e417bde3d8
ambercyang/mcit582hw1
/caesar.py
983
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[6]: def encrypt(key,plaintext): ciphertext="" #YOUR CODE HERE # transverse the plain text for i in range(len(plaintext)): char = plaintext[i] # Encrypt uppercase characters in plain text ciphertext += chr((ord(char) + key-65) % 26 + 65) return ciphertext # In[9]: def decrypt(key,ciphertext): plaintext="" #YOUR CODE HERE # transverse the cipher text for i in range(len(ciphertext)): char = ciphertext[i] # Decrypt uppercase characters in cipher text plaintext += chr((ord(char) - key-65) % 26 + 65) return plaintext # In[18]: plaintext = "CEASER" key = 27 print("Plain Text : " + plaintext) print("Shift pattern : " + str(key)) print("Cipher: " + encrypt(key,plaintext)) # In[19]: ciphertext = "DFBTFS" key = 27 print("cipher Text : " + ciphertext) print("Shift pattern : " + str(key)) print("Cipher: " + decrypt(key,ciphertext)) # In[ ]:
true
c0dc26bec1486217a4578a1fa4b6ca9c43d142ae
JarettSisk/python-data-structures-practice
/17_mode/mode.py
617
4.125
4
def mode(nums): """Return most-common number in list. For this function, there will always be a single-most-common value; you do not need to worry about handling cases where more than one item occurs the same number of times. >>> mode([1, 2, 1]) 1 >>> mode([2, 2, 3, 3, 2]) 2 """ num_dict = {} for num in nums: if num in num_dict: num_dict[num] += 1 else: num_dict[num] = 1 current_num = 0 for key in num_dict: if num_dict[key] > current_num: current_num = key return current_num
true
d137c58f90c26ee84ea3182b18c73168c91e6c0c
ANDRESOTELO/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-write_file.py
335
4.40625
4
#!/usr/bin/python3 """Function that writes a string""" def write_file(filename="", text=""): """ Function that writes a string to a text file (UTF8) and returns the number of characters written """ with open(filename, 'w') as input_text: num_chars = input_text.write(text) return (num_chars)
true
03c4b4678b29ec1002653eda86ed9ea742fcbf8d
Ishant-Dhall/Python-Programs
/Prime No.py
441
4.28125
4
#Prime or not print 'THE FOLLOWING PROGRAM CHECKS WHETHER A GIVEN NO IS A PRIME NO OR NOT' x=input('Input the number: ') count=0 if x<0: print 'This is a negative number' elif x==1: print '1 is neither a prime nor a composite number' else: for n in range (1,(x/2)+1): if x%n==0: count=count+1 if (count==1): print 'This is a prime number' elif (count>1): print 'This is a not a prime number'
true
d48f2a992fbdc928e899be4caae85d3f42c6c623
Ishant-Dhall/Python-Programs
/List-Find & Remove.py
558
4.34375
4
#Finding Element in a list print "THE FOLLOWING PROGRAM SEARCHES FOR AN ELEMENT IN A LIST" list=['January','February','March', 'April','May','June', 'July','August','September', 'October','November','December'] str=raw_input("Enter the element you want to find and remove: ") for i in range (0,len(list)): if list[i]==str: print "Element found and removed" list.remove(str) break else: print '''Element is not present in the list The list remains unchanged''' print "The updated list is: ",list
true
cda5f99040ef54b3fad1c9c282a41319d793029b
Ishant-Dhall/Python-Programs
/Palindrom.py
235
4.15625
4
#String Palindrom ch=raw_input("Enter String:") l=len(ch) a=0 flag=0 while a<l: if (ch[a])==(ch[l-a-1]): flag=1 a=a+1 if flag==1: print "String is Palindrome" else: print "String is not Palindrome"
false
a59e902f2257a2384226dbf5b80696237ce827d0
jinbooooom/coding-for-algorithms
/dataStructure/stack/stack.py
828
4.21875
4
# -*- coding:utf-8 -*- class Stack: """先进后出""" def __init__(self): self.items = [] def push(self, item): # 压入 self.items.append(item) def pop(self): # 弹出 return self.items.pop() def isEmpty(self): # 判断栈是否为空 return self.items == [] def size(self): return len(self.items) def peek(self): # 返回 stack 顶部元素,但不会修改 stack return self.items[-1] def clear(self): # 设置为空栈 del self.items[:] if __name__ == "__main__": s = Stack() s.push(8) s.push(5) s.push(9) print(s.items) print(s.size()) print(s.pop()) print(s.items) print(s.isEmpty()) print(s.peek()) print(s.items) s.clear() print(s.items) print(s.isEmpty())
false
c80ce7b3268f04e952eb8a3f54e35427e50f2864
kevinmaiden7/Python_Code
/Testing_Code/test1.py
974
4.28125
4
def funcionBasica(): # Declaracion de funcion print("Print desde la funcion") def potenciaDos(exponente): print(2**exponente) def funcionPiso(numerador, denominador): return(numerador // denominador) def aumentarValor(numero): numero += 1 print("Print desde aumentarValor()") print(numero) print("---------------------------") saludo = "Saludos desde Python!" print(saludo) numero1 = 20 numero2 = 6 print(numero1) print(numero2) if numero1 > numero2: print("El numero 1 es mayor que el numero 2") else: print("El numero 2 es mayor que el numero 1") print("End") funcionBasica() print("----------------------") funcionBasica() print("Se va a invocar la funcion potenciaDos:") potenciaDos(5) potenciaDos(6) potenciaDos(10) print("Se va a invocar funcionPiso:") print(funcionPiso(32,7)) resultado = funcionPiso(64,10) print(resultado) print("Se va a invocar aumentarValor:") numero = 20 aumentarValor(numero) print("Print afuera de aumentarValor()") print(numero)
false
25ff41793f602f89911d66c25fd89832e9b1848f
sakuya13/Study
/python/py/exercises/cal_sum_of_digits_integer.py
244
4.1875
4
integer = int(input("Enter a positive integer: ")) def sumDigit(integer): s = 0 while integer > 0: s = s + integer % 10 integer = integer // 10 return s print("The sum of the digits is %.0d." % sumDigit(integer))
false
23b5ff82682b3650e7d69aa705cd0b78a232fca3
sakuya13/Study
/python/lectures/week07&08/example3_nestedfor_whilesimple_prime.py
635
4.25
4
## to calculate if a number is prime or not """ for num in range(1,20): #to iterate between 1 to 20 for i in range(2,num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor print(num, 'is not prime') break else: print (num, 'is prime') print ("Good bye!") """ num = 1 while(num < 20): i = 2 while(i <= (num/i)): if not(num % i): print(num, 'is not prime') break i = i + 1 if (i > num/i) : print (num, " is prime") num = num + 1 print ("Good bye!")
true
47de2a2c5bb1f754ff157892f28c21f0c654b9c5
sakuya13/Study
/python/lectures/week05/lecture5_example_calc_sum_user(1).py
628
4.34375
4
#this program calculates the sum of the five numbers entered by the user # these examples illustrate the range count and what they do- take a look sum = 0.0 print('This program will calculate the sum of five numbers') print('that you will enter') ''' for counter in range(5): number = int(input('enter a number:')) sum = sum + number print('the total is:', sum) ''' ''' for counter in range(1,5): number = int(input('enter a number:')) sum = sum + number print('the total is:', sum) ''' for counter in range(0,5): number = int(input('enter a number:')) sum = sum + number print('the total is:', sum)
true
021175d50dca2bcb124c293a2e1b9b000eb6ce20
sakuya13/Study
/python/lectures/week07&08/example_remove_list.py
288
4.375
4
# example to illustrate the remove(). food = ['pizza', 'burger', 'chips'] print(food) item = input('which item would you like to remove:') if item not in food: print('the item is not in the list') else: food.remove(item) print('here is the new list:') print(food)
true
0291bdb02a81dcc5d6a5243a7f89231ae9a2383f
sakuya13/Study
/python/lectures/week03/example2_lect3_input_instead_print.py
311
4.375
4
""" This example code illustrates using the input statement to gather values from the user Note: what happens to this piece of code? Is there a problem! """ width = int(input ("please enter the width = ")) height = int(input ("please enter the height = ")) area = width * height print ("the area is = ", area)
true
1a9bf864aecf7253dacdd59a24f3e65814365ac8
sakuya13/Study
/python/lectures/week06/example_format-style_empty.py
248
4.15625
4
count = 10 total = 100 print("The number contains {} digits".format(count)) print("The digits sum to {}".format(total)) #example - check the string success = 'Congratulations, you have scored "{}" out of "{}"' print(success.format(count, total))
true
1ff84c91dafdf2fcff288ecd4fdb95fe594a45ad
RayWLMo/Eng_89_Python_OOP
/Python_Functions.py
1,438
4.65625
5
# Let's create a function # Syntax -> def is used to declare followed by name of the function(): # First iteration def function(): print("This is a function") # pass # pass is the keyword that allows the interpreter to skip this without any errors function() # To call the function # If the function is not called the code would execute with no errors but no output # DRY - Don't Repeat Yourself by declaring functions and re-using code # Second iteration using return statement def function(): print("This is the print function") return "This is from the return statement" print(function()) # Third iteration with with username as a string as an argument/args def greeting(name): return "Hello " + name + "!" print(greeting("Greg")) # Create a function to prompt user to enter their name and display the name back to user with greeting message Name = input("What is your name? ") def greeting(name): return "Hello " + name.capitalize() + "!" print(greeting(Name)) # Lets create a function with multiple arguments as an int def add(num1, num2): return num1 + num2 print(add(9, 3)) def multiply(num1, num2): return num1 * num2 print(" This is the required outcome of 2 numbers: ") # This line of code will not execute as the return # statement is the last line of code that the function executes print(multiply(4, 6))
true
aa77b37721682d2c39921670950a1dfad4ac7f03
Youngshark3/100-DaysOfCode-Python
/Day 5/day-5-2-highest-score.py
1,612
4.53125
5
# Highest Score # Instructions # You are going to write a program that calculates the highest score from a List of scores. # e.g. student_scores = [78, 65, 89, 86, 55, 91, 64, 89] # **Important** # You are not allowed to use the max or min functions. # The output words must match this example:`The highest score in the class is: x` # Example Input: 78 65 89 86 55 91 64 89 # In this case, student_scores would be a list that looks like: `[78, 65, 89, 86, 55, 91, 64, 89]` # Example Output: The highest score in the class is: 91 # Hint # 1. Think about the logic before writing code. How can you compare numbers against each other to see which one is larger? # Solution # Test it here: https://replit.com/@terrykirungo/day-5-2-highest-score #🚨 Don't change the code below 👇 student_scores = input("Input a list of student scores ").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(f"Here's a list of the student_scores: {student_scores}") #🚨 Don't change the code above 👆 #Write your code below this row 👇 #initialize highest_score highest_score = 0 #Combining two functions a for loop and an if for score in student_scores: #if the item(score) we land upon is higher than the value we've set for highest score for example in the first bit when the code runs it will perform 0 > 78, then it will assign highest score to 78, then run again(loop) and perform 78 > 65, this will continue until it reaches 91 if score > highest_score: highest_score = score print(f"\tThe highest score in the class is: {highest_score}")
true
8310538cc5cc92c48735057b2129198be020f175
Youngshark3/100-DaysOfCode-Python
/Day 4/day-4-2-random-person-pays-bill.py
1,512
4.46875
4
# Who's Paying # Instructions # You are going to write a program which will select a random name from a list of names. The person selected will have to pay for everybody's food bill. # **Important**: You are not allowed to use the `choice()` function. # **Line 20** splits the string `names_string` into individual names and puts them inside a **List** called `names`. For this to work, you must enter all the names as name followed by comma then space. e.g. name, name, name # Example Input: Angela, Ben, Jenny, Michael, Chloe # Note: notice that there is a space between the comma and the next name. # Example Output: Michael is going to buy the meal today! # Hint # 1. You might need the help of the `len()` function. # 2. Remember that Lists start at index 0! import random # Split string method names_string = input("Give me everybody's names, separated by a comma. ") names = names_string.split(", ") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 # How many items are in the list number_of_people = len(names) # Get's the random person by picking a random index number of a person in the list from index[0] to the last person index[-1] in the list random_person = random.randint(0, number_of_people - 1) # Pops ups the name of the randpm index picked random_person_paying = names.pop(random_person) # The above code could be simplified to be: # random_person_paying = random.choice(names) print(random_person_paying + " is going to buy the meal today!")
true
ed5649b9a496cec3db37971b0ad220a26b13bf10
Youngshark3/100-DaysOfCode-Python
/Day 4/day-4-3-treasure-map.py
2,348
4.96875
5
# Treasure Map # Instructions # You are going to write a program which will mark a spot with an X. # In the starting code, you will find a variable called `map`. # This ```map``` contains a nested list. # When ```map``` is printed this is what the nested list looks like: # ['⬜️', '⬜️', '⬜️'],['⬜️', '⬜️', '⬜️'],['⬜️', '⬜️', '⬜️'] # In the starting code, we have used new lines (```\n```) to format the three rows into a square, like this: # ['⬜️', '⬜️', '⬜️'] # ['⬜️', '⬜️', '⬜️'] # ['⬜️', '⬜️', '⬜️'] # This is to try and simulate the coordinates on a real map. # Your job is to write a program that allows you to mark a square on the map using a two-digit system. # First your program must take the user input and convert it to a usable format. # Next, you need to use it to update your nested list with an "x". # The first digit is the vertical column number and the second digit is the horizontal row number. e.g.: # Example Input 1: column 2, row 3 would be entered as: 23 # Example Output 1: # ['⬜️', '⬜️', '⬜️'] # ['⬜️', '⬜️', '⬜️'] # ['⬜️', 'X', '⬜️'] # Example Input 2: column 3, row 1 would be entered as: 31 # Example Output 2: # ['⬜️', '⬜️', 'X'] # ['⬜️', '⬜️', '⬜️'] # ['⬜️', '⬜️', '⬜️'] # # Hint # 1. Remember that Lists start at index 0! # 2. ```map``` is just a variable that contains a nested list. It's not related to the map function in Python. # 🚨 Don't change the code below 👇 # 1 2 3 COLUMNS row1 = ["⬜️","⬜️","⬜️"] # 1 R row2 = ["⬜️","⬜️","⬜️"] # 2 O row3 = ["⬜️","⬜️","⬜️"] # 3 WS map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you want to put the treasure? ") # 🚨 Don't change the code above 👆 #Write your code below this row 👇 # rows first column last/next # If the input given is 23 it will move 2 rows 3 columns x_position = int(position[0]) #2 since they are still strings we'll change them to intergers -> int() y_position = int(position[1]) #3 # On row 2 rows and column 3 put X map[x_position - 1][y_position - 1] = "X" #Write your code above this row 👆 # 🚨 Don't change the code below 👇 print(f"{row1}\n{row2}\n{row3}")
true
b38b57291b95635f0136a09ee606f0d8a02e6984
Youngshark3/100-DaysOfCode-Python
/Day 5/day-5-4-fizz-buzz.py
1,472
4.53125
5
# FizzBuzz # Instructions # You are going to write a program that automatically prints the solution to the FizzBuzz game. # `Your program should print each number from 1 to 100 in turn.` # `When the number is divisible by 3 then instead of printing the number it should print "Fizz".` # `When the number is divisible by 5, then instead of printing the number it should print "Buzz".` # `And if the number is divisible by both 3 and 5 e.g. 15 then instead of the number it should print "FizzBuzz"` # e.g. it might start off like this: # ``` 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ``` # Hint # 1. Remember your answer should start from 1 and go up to and including 100. # 2. Each number/text should be printed on a separate line. # Solution # https://replit.com/@terrykirungo/day-5-4-fizz-buzz #Write your code below this row 👇 for number in range(1,101): #prints from 1 to 100 #have it at the top so that it proceeds with the execution #checks divisibility by 3 and 5 if number % 3 == 0 and number % 5 == 0: number = "FizzBuzz" #checks divisibility by 3 elif number % 3 == 0: number = "Fizz" #checks divisibility by 3 and 5 elif number % 5 == 0: number = "Buzz" print(number) # If we have this if number % 3 == 0 and number % 5 == 0: at the bottom the program willl execute to completion before it reaches this block of code rememeber the rock paper scissor game!
true
65c1684ecaa2a70b9148781e22ac7873c81b1b70
Youngshark3/100-DaysOfCode-Python
/Day 8/day-8-1-area-calc.py
1,549
4.53125
5
# Area Calc # Instructions # You are painting a wall. The instructions on the paint can says that **1 can of paint can cover 5 square meters** of wall. # Given a random height and width of wall, calculate how many cans of paint you'll need to buy. # number of cans = (wall height ✖️ wall width) ÷ coverage per can. # e.g. Height = 2, Width = 4, Coverage = 5 # number of cans = (2 ✖️ 4) ÷ 5 # = 1.6 # But because you can't buy 0.6 of a can of paint, the **result should be rounded up** to **2** cans. # IMPORTANT: Notice the name of the function and parameters must match those on line 13 for the code to work. # Hint # **1. To round up a number**: use math.ceil() # Test Your Code # https://replit.com/@terrykirungo/day-8-1-area-calc#main.py #Write your code below this line import math #1 can of paint can cover 5 square meters def paint_calc(height, width, cover): area = height * width #Area is calculated by width times height #Math.ceil rounds up a number if it's 1.6 we round up to 2 number_of_cans = math.ceil(area / cover) #number of cans is given by the area divided by the cover(1 can of paint can cover 5 square meters) print(f"You'll need {number_of_cans} cans of paint.") #Write your code above this line # Define a function called paint_calc() so that the code below works. # 🚨 Don't change the code below test_h = int(input("Height of wall: ")) test_w = int(input("Width of wall: ")) coverage = 5 paint_calc(height=test_h, width=test_w, cover=coverage)
true
4882708ae69e7e302fb695edf175782682905660
archime/codewars
/valid-braces.py
665
4.34375
4
""" Title: Valid Braces Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid. This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for the idea! All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}. """ def validBraces(string): while "()" in string or "[]" in string or "{}" in string: for pair in ["[]", "{}", "()"]: string = string.replace(pair, "") return len(string) == 0
true
36596a865a2d6c7141b508aa8949c3780f03eb2e
UmairKhankhail/OOPs
/Class and Instance Variables.py
1,200
4.3125
4
#Instance Variables #Class/Static Variables (Class varaibles are also called static varaibles.) class Car(): #Class variables body='Metal' def __init__(self): self.Type="BMW" self.Mileage=2000 car1=Car() car2=Car() #Now If I call the variables for both the objects, this will give us same output #These variables belongs to objects because it depends upon objects, These can not be accessed through class name. #print(Car.Type) -----> It is commented because with this the code won't run. print(car1.Type,car1.Mileage) print(car2.Type,car2.Mileage) #But if I want to change the type and mileage just for car1, It will be changed while the variables will remain same for car2 car2.body="Water" car1.Type='Carolla' car1.Mileage=50000 print(car1.Type,car1.Mileage) print(car2.Type,car2.Mileage) #Now if all the objects of the class have some simillar properties or fixed properties for all objects, I will use class variables for that because that belongs to class. #These variables can be accessed through both class and objects.# # #class varaibles can also be changed print(Car.body) print(car2.body) car2.body="Water" print(Car.body) print(car2.body)
true
ae1ec1aff6d69ff18535545016c568228df288ab
rubentrevino95/python-exercises
/exercises/strings.py
745
4.125
4
a = 10 b = 3.14 c = "Hello World" d = 'tinker' print(a + a) print(d[1:4]) # Data Types print(type(a)) print(type(b)) print(type(c)) # length of string print(len(c)) # index of string print (c[1]) # slicing print (c[:3]) # sub section slicing print (c[3:6]) # beginning to end rev print (c[::-1]) # beginning to end step size in 2s print (c[::2]) # index to index step size in 2s print (c[0:6:2]) # uppercase print (c.upper()) print (c.split()) print (c.split('l')) # string formatting print ('The {2} {1} {0}'.format('fox', 'black', 'quick')) print ('The {f} {b} {q}'.format(f='fox', b='black', q='quick')) # float formatting result = 100/777 print("The result was {r:1.3f}".format(r=result)) # String format name ="Jose"
true
09026d738aa0342913106e7fc4855f39c98c3f4e
rubentrevino95/python-exercises
/exercises/elseif.py
233
4.125
4
hungry = True if hungry: print ("Its True") else: print ("Its False") loc = 'bank' if loc == 'store' or loc == 'arcade': print ("WE'RE HERE") elif loc == 'bank': print ('MONEY') else: print ("we're NOT here")
false
a80cd106d0a1e022396e6825ef297f89bfc45544
kajalgada-gmr/leetcode-python
/leetcode_617_merge_two_binary_trees/leetcode_617_merge_two_binary_trees.py
1,503
4.25
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: # If either or both trees are empty if (root1 is None) and (root2 is None): return None elif root1 is None: return root2 elif root2 is None: return root1 # Combine trees into 1st tree stack_nodes = [[root1, root2]] while stack_nodes: cur_1, cur_2 = stack_nodes.pop() cur_1.val += cur_2.val # If both trees have a left node, add it to stack if (cur_1.left is not None) and (cur_2.left is not None): stack_nodes.append([cur_1.left, cur_2.left]) # If tree 1 has a node and tree 2 doesn't, it remains unchanged. # If tree 1 doesn't have a node and tree 2 does, add tree 2 node to tree 1. elif cur_1.left is None: cur_1.left = cur_2.left if (cur_1.right is not None) and (cur_2.right is not None): stack_nodes.append([cur_1.right, cur_2.right]) elif cur_1.right is None: cur_1.right = cur_2.right return root1
true
462a9af8672830e6de07133583e5ab5b0600f8a7
lambda-projects-lafriedel/Sorting
/src/recursive_sorting/recursive_sorting.py
2,146
4.21875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): # These 2 lines are creating a new list that has the length of 'elements' and is being instantiated with 0s as placeholders elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # Need to keep track of indices! This is what I was missing. arrA_index = 0 arrB_index = 0 # Loop through merged_arr's indices and compare the values of arrA and arrB. for i in range(0, elements): # If the stored index equals the length of the arr (meaning all values have been added to the sorted list), set merged_arr[i] as the last value in the opposite arr. if arrA_index == len(arrA): merged_arr[i] = arrB[arrB_index] arrB_index += 1 elif arrB_index == len(arrB): merged_arr[i] = arrA[arrA_index] arrA_index += 1 # If index of arrA is smaller than index of arrB, set that arrA's index to merged_arr[i]. Else, set arrB's index to merged_arr[i] elif arrA[arrA_index] < arrB[arrB_index]: merged_arr[i] = arrA[arrA_index] arrA_index += 1 else: merged_arr[i] = arrB[arrB_index] arrB_index += 1 # print(merged_arr) return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO # If arr is 0 or 1 in length, return arr. if len(arr) <= 1: return arr # Split arr into two equal arrays split_index = len(arr) // 2 # Recurse through the new arrays left = merge_sort(arr[:split_index]) right = merge_sort(arr[split_index:]) # Merge the two sides merged_arr = merge(left, right) return merged_arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr
true
98ee613ea7335b360e7fcadbff1f86eb0a147abb
Ch4insawPanda/CP1404_Practical
/prac_05/emails.py
1,477
4.40625
4
def main(): email_to_name = {} user_email = input("Enter Email :") while user_email != '': user_email = get_user_name(email_to_name, user_email) for name, email in email_to_name.items(): print('{} {}'.format(name, email)) def get_user_name(email_to_name, user_email): """Check if the user email name is the same as the name and add to the dictionary""" user_name = get_email_name(user_email) is_name = input('Is {} your name? (Y/n) :'.format(user_name)).lower() while is_name != 'y' and is_name != 'n': print('Error: Invalid Input') is_name = input('Is {} your name? (Y/n) :'.format(user_name)).lower() if is_name == 'y': email_to_name[user_name] = user_email else: user_name = input('Enter Name :') email_to_name[user_name] = user_email user_email = input("Enter Email :") return user_email def get_email_name(user_email): """Get the user name from the email""" user_name = user_email.split('@') user_name = (user_name[0]).title() user_name = is_split(user_name) return user_name def is_split(user_name): """Split username into first name last name if possible.""" if '.' in user_name: name_parts = user_name.split('.') first_name = (name_parts[0]).title() last_name = (name_parts[1]).title() user_name = ('{} {}'.format(first_name, last_name)) return user_name if __name__ == '__main__': main()
true
c750a3bb24c536152394f98ee6500ffa46008ae5
jgramelb/Python-learning
/ex12_07.py
1,690
4.28125
4
#12.7 #Exercise 4 from book #Instructions: #Change the urllinks.py program to extract and count paragraph (p) tags from the #retrieved HTML document and display the count of the paragraphs as the #output of your program. Do not display the paragraph text, only count them. #Test your program on several small web pages as well as some larger web pages. import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl try: HOST = input('Enter a URL - ') #prompts user for the URL for that it can read any webpage HOST = HOST.lower() #convert the input into lowercase letters except: print('You have entered an improperly formatted or non-exisent URL - ', HOST) exit() # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE #Open up the URL file fhand = urllib.request.urlopen(HOST, context=ctx) #Parse it with BeautifulSoup, but we don't want to show it. soup = BeautifulSoup(fhand, 'html.parser') #here, we read each line in the file // BUT WE DONT NEED IT IN THIS EXAMPLE. # WE ARE NOT TRYING TO READ THE HTML!!!! #for line in fhand: #We strip it of whitespaces on the right and left of each line. #line = line.decode().strip() #just simply print out the URL file #print(line) #initialize the counts paragraphcounts = 0 # Retrieve all of the paragraph tags tags = soup('p') for tag in tags: #get the tag. call it ptag ptag = tag.get(None) #count how many <p> you see. paragraphcounts = paragraphcounts + 1 #print the counts print('There are',paragraphcounts,'<p> tags!')
true
332fb5f30bcf3faae4d1de96ac0bde81a2bd883e
jgramelb/Python-learning
/ex02_04.py
340
4.1875
4
#Exercise 4: Assume that we execute the following assignment statements: #width = 17 #height = 12.0 #For each of the following expressions, write the value of the expression and the type (of the value of the expression). width = 17 height = 12.0 print(round(width//2)) print(round(width/2.0)) print(round(height/3)) print(round(1+2*5))
true
8f6ade43f1e8baf6a6091f1ad01d426f73cf6d90
jgramelb/Python-learning
/ex08_05.py
954
4.3125
4
#ex8.5 # 8.5 Open the file mbox-short.txt and read it line by line. # When you find a line that starts with 'From ' # like the following line: # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # You will parse the From line using split() and # print out the second word in the line # (i.e. the entire address of the person who sent the message). # Then print out a count at the end. fname = input('Enter file name: ') try: fhandle = open(fname) except: print('Please enter correct file name. You entered:', fname) quit() count = 0 #read txt file line by line for line in fhandle: #print(line) #When you find a line that starts with 'From ' if not line.startswith('From '): continue #Split the line into words words = line.split() #print out the second word in the line #print(words[1]) count = count + 1 #print count print("There were",count, "lines that starts with 'From '")
true