blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
bc17e2a5436a35f6c2036c929bbe1ca4d1706839
colinbazzano/learning-python
/src/regex/main.py
604
4.28125
4
import re string = 'search inside of this text, please!' print('search' in string) # we are looking for the word 'this' in the variable string a = re.search('this', string) # will show you where it began counted via index print(a.start()) # returns what you wanted if available print(a.group()) """NoneType if you cannot find the word, it will return a NoneType error, so you can except for it you can do other methods such as pattern = re.compile('text to be searched through') a = pattern.search(string) b = patternfindall(string) c = pattern.fullmatch(string) d = pattern.match(string) """
true
01a1deaacd22b9a1bb7664748887a7abb2db59aa
colinbazzano/learning-python
/src/fileio/inputoutput.py
499
4.15625
4
# File I/O or, File Input/Output # Below, we are assigning a variable to the path of the txt file we want to read. my_file = open('src/fileio/write.txt') # here we are just using the read method and printing it print(my_file.read()) # .seek(0) is another way to move the cursor # .readline() you can continue to call this and move down the lines # .readlines() will go through and show you each line with the \n new line indicator # be a kind dev, close the file when you're done my_file.close()
true
81e58f79d8e6c77e374487444531d9e98e3c2e4c
mike006322/ProjectEuler
/Solutions/PE002_even_fibonacci_numbers/python/even_fibonacci_numbers.py
1,124
4.15625
4
#!/bin/python3 # https://www.hackerrank.com/contests/projecteuler/challenges/euler002 from functools import lru_cache @lru_cache(maxsize=None) def fib(n): """ returns the nth fibonacci number """ if n == 1: return 1 if n == 2: return 2 if n > 2: return fib(n - 1) + fib(n - 2) def even_fibonacci_numbers(n): """ returns the sum of the even valued fibonacci numbers less than or equal to n """ even_fib_less_than_n = [] i = 1 fib_i = 1 while fib_i <= n: if fib_i % 2 == 0: even_fib_less_than_n.append(fib_i) i += 1 fib_i = fib(i) return sum(even_fib_less_than_n) if __name__ == '__main__': print(even_fibonacci_numbers(4000000)) # t = int(input().strip()) # for a0 in range(t): # n = int(input().strip()) # even_fib_lessthan_n = [] # i = 1 # fib_i = 1 # while fib_i <= n: # if fib_i % 2 == 0: # even_fib_lessthan_n.append(fib_i) # i += 1 # fib_i = fib(i) # print(sum(even_fib_lessthan_n))
false
07cd1b50d39d25a2cb18c2b4f36110c80b192691
rishabhgautam/LPTHW_mynotes
/ex13-studydrills3.py
303
4.21875
4
# ex13: Parameters, Unpacking, Variables # Combine input with argv to make a script that gets more input from a user. from sys import argv script, first_name, last_name = argv middle_name = input("What's your middle name?") print("Your full name is %s %s %s." % (first_name, middle_name, last_name))
true
da50855b9c02c62100ae1870849b03c545afc8e1
rishabhgautam/LPTHW_mynotes
/ex20-studydrills.py
1,962
4.28125
4
# ex20: Functions and Files # Import argv variables from the sys module from sys import argv # Assign the first and the second arguments to the two variables script, input_file = argv # Define a function called print_call to print the whole contents of a # file, with one file object as formal parameter def print_all(f): # print the file contents print(f.read()) # Define a function called rewind to make the file reader go back to # the first byte of the file, with one file object as formal parameter def rewind(f): # make the file reader go back to the first byte of the file f.seek(0) # Define a function called print_a_line to print a line of the file, # with a integer counter and a file object as formal parameters def print_a_line(line_count, f): # Test whether two variables are carrying the same value print("line_count equal to current_line?:", (line_count == current_line)) # print the number and the contents of a line print(line_count, f.readline()) # Open a file current_file = open(input_file) # Print "First let's print the whole file:" print("First let's print the whole file:\n") # call the print_all function to print the whole file print_all(current_file) # Print "Now let's rewind, kind of like a tape." print("Now let's rewind, kind of like a tape.") # Call the rewind function to go back to the beginning of the file rewind(current_file) # Now print three lines from the top of the file # Print "Let's print three lines:" print("Let's print three lines:") # Set current line to 1 current_line = 1 # Print current line by calling print_a_line function print_a_line(current_line, current_file) # Set current line to 2 by adding 1 current_line += 1 # Print current line by calling print_a_line function print_a_line(current_line, current_file) # Set current line to 3 by adding 1 current_line += 1 # Print current line by calling print_a_line function print_a_line(current_line, current_file)
true
bd5993726157d5b616c171c1bd1c3527996b5ed7
ramanancp/python-test
/mytimedelta.py
826
4.125
4
from datetime import date from datetime import time from datetime import timedelta from datetime import datetime print(timedelta(days=365, hours=5, minutes=1)) now = datetime.now() print("Today is " + str(now)) #print today's date one year from now print("Today's date 1 year from now " + str(now + timedelta(days=365))) print("Two weeks and 2 days from now " + str(now + timedelta(days=2, weeks=2))) print("1 month 3 weeks and 2 days before " + str(now - timedelta(days=2,weeks=7))) today = date.today() afd = date(today.year,4,1) if (afd < today): print("April fool's day has already went %d days before " % ((today -afd).days)) afd = afd.replace(year = today.year+1) #calculate number of days to next April fool's day time_to_afd = afd-today print("Next april fool's day is %d days only", time_to_afd.days)
false
d8e39d1e7c7561253203f68afcc1f4dfa7d7f5e7
xiemingzhi/pythonproject
/lang/arrays.py
1,365
4.375
4
#List is a collection which is ordered and changeable. Allows duplicate members. # in python they are called lists a = [1, 2, 3, 4, 5] def printArr(arr): for x in arr: print(x) printArr(a) #Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # in python they are called dictionary d = {'jack':'apple', 'jill':'pear', 'giant':'sheep'} def printMap(map): for i, v in map.items(): print(i, v) printMap(d) #Tuple is a collection which is ordered and unchangeable. Allows duplicate members. #In Python tuples are written with round brackets. #Tuples are immutable #You can convert the tuple into a list, change the list, and convert the list back into a tuple. x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x) #Set is a collection which is unordered and unindexed. No duplicate members. #In Python sets are written with curly brackets. #you cannot change its items, but you can add new items. thisset = {"apple", "banana", "cherry"} thisset.add("orange") print(thisset) thisset.remove("banana") print(thisset) set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print('set union', set3) x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.intersection(y) print('set intersection', z)
true
477ed45fd0d6d278a87f33209ad99b30e7732c65
AbhinavUtkarsh/Cracking-The-Coding-Interview
/Solutions to Arrays and Strings/rotate matrix.py
1,787
4.34375
4
def rotate(matrix): N=len(matrix) for layer in range(N//2): first , last = layer, N - layer - 1 for i in range(first, last): top = matrix[layer][i] matrix[layer][i] = matrix[-i-1][layer] matrix[-i-1][layer] = matrix[-layer-1][-i-1] matrix[-layer-1][-i-1] = matrix[i][-layer-1] matrix[i][-layer-1] = top #printing print("Result: ") display(matrix) def transpose_reverse(matrix): """ Here we first transpose the matrix as rotating by a 90 degreee angle itself is making the rows become columns. However, the rows when noticed get reversed, hence we need to reverse thr rows of our transposed matrix. When compared to the rotated matrix, out transposed and reversed rows matrix would be the same. """ #transpose N=len(matrix) for i in range(N): for j in range(i+1,N): temp= matrix[i][j] matrix[i][j]=matrix[j][i] matrix[j][i]=temp print("The Transposed Matrix is: ") display(matrix) # now reversing the rows of the matrix for i in range(N): matrix[i]=matrix[i][::-1] print("Result from transpose and reverse: ") display(matrix) def display(matrix): #displays the matrix N=len(matrix) for i in range(N): for j in range(N): print(matrix[i][j], end=" ") print() matrix0=[[1]] matrix1=[[1,2],[3,4]] matrix2=[[1,2,3],[4,5,6],[7,8,9]] matrix3=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] transpose_reverse(matrix0) transpose_reverse(matrix1) transpose_reverse(matrix2) transpose_reverse(matrix3) print("+++++++++++++++++++++++++++++") rotate(matrix0) rotate(matrix1) rotate(matrix2) rotate(matrix3)
true
f98cdb5ef5a5a9af2a5f6304b85a81750c5a0be6
MojoZZ/Python
/pwork/11.循环.py
924
4.25
4
# 循环语句 while和for # while 条件表达式 : # 代码块 # else : # i = 0 # while i < 5 : # print('i=', i) # i += 1 # else : # # 在条件表达式为False时执行 # print('结束循环') #循环的嵌套 # i = 0 # while i < 5 : # j = 0 # while j < 5 : # print('*', end='') # j += 1 # print() # i += 1 # i = 0 # while i < 5 : # j = 0 # while j < i + 1 : # print('*', end='') # j += 1 # print() # i += 1 #break 可以用来立刻退出当前的循环(包括else) # i = 0 # while i < 5 : # if i == 3 : # break # print(i) # i += 1 # else : # print('循环结束') #continue 可以跳过当次循环 # i = 0 # while i < 5 : # i += 1 # if i == 3 : # continue # print(i) # else : # print('循环结束') #pass是用来在判断和循环语句中占位的 #当循环体或者if代码块中没有写任何代码运行会报错,可以加上pass i = 0 if i < 5 : pass
false
817b9baccfd33d2e7c06126fbd97244545fdf29d
MojoZZ/Python
/pwork/07.类型检查.py
1,132
4.21875
4
#通过类型检查,可以检查数值(变量)的类型 #type() 函数,用来检查值得类型 a = 123 b = '123' print(type(a)) #<class 'int'> print(type(b)) #<class 'str'> print(type(0.152)) #<class 'float'> print(type(True)) #<class 'bool'> print(type(None)) #<class 'NoneType'> #类型转换 将一个类型的对象转换为其他对象 #类型转换不是改变对象本身的类型,而是根据当前对象的值创建一个新对象 #int() float() str() bool() 函数 #int()规则: # 布尔值:True-1 False-0 # 浮点数:取整 # 字符串:合法的整数字符串 # None:不支持 a = True a = int(a) print('a =', a) a = '123' a = int(a) print('a =', a) a = 123.456 a = int(a) print('a =', a) a = None; #a = int(a) #print('a =', a) #float()规则基本和int()一致 b = 209 b = float(b) print('b =', b); print('b的类型', type(b)) #str() s = 123 s = str(123) #print('s =', s) #print('s的类型', type(s)) #bool() 任何对象都可以转为布尔值 #所有表示空性的对象都会转为False,其余的转为True #空性的有如:0 None '' n = '' n = bool(n) print('n=', n)
false
410d4d42ae44f344665057493173c13ad2fac4be
panchaldhruvin99/forsk2019
/Day_09/database1.py
1,193
4.15625
4
""" Code Challenge 1 Write a python code to insert records to a mongo/sqlite/MySQL database named db_University for 10 students with fields like Student_Name, Student_Age, Student_Roll_no, Student_Branch. """ import sqlite3 from pandas import DataFrame conn = sqlite3.connect("db_university.db") c=conn.cursor() c.execute ( """CREATE TABLE student( student_name TEXT, student_age INTEGER, student_roll_no INTEGER, student_branch TEXT)""" ) c.execute("DROP TABLE IF EXISTS student;") c.execute("INSERT INTO student VALUES ('Dhruvin',21,053,'CSE')") c.execute("INSERT INTO student VALUES ('honey',22,054,'CSE')") c.execute("INSERT INTO student VALUES ('Dhruv',21,055,'CSE')") c.execute("INSERT INTO student VALUES ('manas',22,056,'CSE')") c.execute("INSERT INTO student VALUES ('aayush',21,057,'CSE')") c.execute("SELECT * FROM student") print ( c.fetchall() ) c.execute("SELECT * FROM student") df = DataFrame(c.fetchall()) df.columns = [" student_name ", "student_age ", "student_roll_no ", "student_branch "] conn.commit() conn.close()
false
a365034c83e81045f609c720c145b23fcca28489
angeldeng/LearnPython
/LearnPython/data structure/using_tuple.py
2,068
4.28125
4
zoo=('python','elephant','penguin') #小括号可选 print('Number of cages in the new zoo is',len(zoo)) new_zoo=('monkey','camel',zoo) print('Number of cages in the new zoo is',len(new_zoo)) print('All animals in new zoo are', new_zoo) print('Animals brought from old zoo are', new_zoo[2]) print('Last animal brought from old zoo is', new_zoo[2][2]) print('Number of animals in the new zoo is',len(new_zoo)-1+len(new_zoo[2])) '''代码如何工作: 变量 zoo 引用一个元组。我们看到 len 函数可以得到元组的长度。这也表明元组 同样是一个序列类型。 因为老动物园歇菜了,于是我们将这些动物转移到一个新的动物园。因此元组 new_zoo 既包含已有的动物又包含从老动物园转移过来的新动物。 言归正传,注意一个包含在其它元组内的元组并不会丢失它的身份。 (注:包含元组会引用被包含元组,即在包含元组内对被包含元组的操作会反应 到被包含元组自身之上,有点绕口。。。) 像列表一样,我们可以通过一对方括号指定元素的位置访问这个元素。这叫做索 引操作符。 我们通过 new_zoo[2]访问 new_zoo 的第三个元素,通过 new_zoo[2][2]访问 new_zoo 的第三个元素的第三个元素。 一但你理解这种语言风格,这样的操作太安逸了. 虽然小括号是可选的,但我强烈建议你坚持使用小括号,这样一眼就能看出它是 个元组,尤其还能避免出现歧义。 例如,print(1, 2, 3)和 print((1, 2, 3))是不同的 – 前者打印 3 个数字而后者打印一 个元组(包含 3 个数字).''' '''拥有 0 个或 1 个元素的元组 一个空元组通过空小括号创建,例如 myempty = ()。 不过,指定一个单元素元组就不那么直观了。你必须在其仅有的一个元素后跟随 一个逗号,这样 python 才能区分出 你要的是元组而不是一个被小括号包围的对象的表达式。例如你想要一个包含值 为 2 的单元素元组,则必须写成 singleton = (2, )'''
false
ba2fe09108179858452060b08d2eba2bd3b485c6
dem27va/Dp-P026
/Homework 2020-06-23/HW06-23_Task_4.py
1,363
4.28125
4
#Пользователь вводит целое число. #Определить является ли чесло однозначным, двузначным, трехзначным или содержит больше символов inputNumber = input('Введите целое число: ') #Проверяем положительно или отрицательное введено число if inputNumber[0] == '-': digitsCount = len(inputNumber) - 1 sign = 'отрицательное' else: digitsCount = len(inputNumber) sign = 'положительное' #Записываем в строчную переменную сколькозначное число введено if digitsCount == 1: result = 'однозначное' elif digitsCount == 2: result = 'двузначное' elif digitsCount == 3: result = 'трезначное' elif digitsCount > 3: result = 'содержащее больше четырех знаков' else: result = 'какое-то другое' #Если введен нуль - пишем, что введен нуль, в противном случае пишем какое число введено if inputNumber == '0': print('Введен нуль') else: print('Введено {} {} число '.format(sign, result))
false
a64c82bd01eac0b1114b23a9a3a88d0fe593e26e
Birdboy821/python
/natural.py
399
4.1875
4
#natural.py #christopher amell 1/3/19 #find the sum and sum of the cubed of the natural #numbers up to one that is imputed by the user def sumN(n): summ = 0 while(n>0): summ=summ+n n=n-1 print(summ) def sumNCubes(n): summ = 0 while(n>0): summ=summ+n**3 n=n-1 print(summ) def main(): n = eval(input("which place do you want: ")) sumN(n) sumNCubes(n) main()
true
384061158790da10d7eb6975a80044e9bfb89a0b
Birdboy821/python
/sphere.py
325
4.25
4
#sphere.py #christopher amell 1/3/19 #a program that calculate a spheres area and volume def sphereArea(radius): a = 4 * 3.14 * radius ** 2 print(a) def sphereVolume(radius): v = 4 / 3 * 3.14 * radius ** 3 print(v) def main(): r = eval(input('what is your radius: ')) sphereArea(r) sphereVolume(r) main()
false
337b757021637c1ea01c47410999d9f0d4ff125c
Shiv2157k/leet_code
/math_and_srings/square_root_x.py
1,738
4.125
4
class SquareRoot: def get_square_root_(self, val: int) -> int: """ Approach: Pocket Calculator input: val, output: res Formulae: left-------------right res^2 <= val < (res + 1) :param val: :return: """ from math import e, log left = int(e ** (0.5 * log(val))) right = left + 1 return left if right * right > val else right def get_square_root__(self, val: int) -> int: """ Approach: Binary Search input: val, output: res Formulae: 0 < x < x // 2 :param val: :return: """ # base case if val <= 2: return val left, right = 2, val // 2 while left <= right: pivot = left + (right - left) // 2 res = pivot * pivot if res < val: left = pivot + 1 elif res > val: right = pivot - 1 else: return pivot return right def get_square_root(self, val: int) -> int: """ Approach: Newton's Method Formulae: val(k + 1) = 1/2[val(k) + val/val(k)] :param val: :return: """ if val < 2: return val val0 = val val1 = (val0 + val / val0) / 2 while abs(val0 - val1) >= 1: val0 = val1 val1 = (val0 + val / val0) / 2 return int(val1) if __name__ == "__main__": sq = SquareRoot() print(sq.get_square_root(36)) print(sq.get_square_root_(36)) print(sq.get_square_root__(36)) print(sq.get_square_root(10)) print(sq.get_square_root_(10)) print(sq.get_square_root__(10))
false
b7aaa56c625d4c68ce805e97b891a600313e56c3
Shiv2157k/leet_code
/revisited__2021/arrays/container_with_most_water.py
759
4.125
4
from typing import List class WaterContainer: def with_most_water(self, height: List[int]) -> int: """ Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param height: :return: """ left, right = 0, len(height) - 1 area = 0 while left < right: area = max(area, min(height[left], height[right]) * (right - left)) if height[left] > height[right]: right -= 1 else: left += 1 return area if __name__ == "__main__": container = WaterContainer() print(container.with_most_water([1, 8, 6, 2, 5, 4, 8, 3, 7])) print(container.with_most_water([1, 1, 1, 1, 1, 1, 1, 1, 1]))
true
1d77a643e819600c1b626c78b53d8bc489f0ffa6
Shiv2157k/leet_code
/revisited/math_and_strings/math/plaindrome_number.py
759
4.1875
4
class Number: def is_palindrome(self, num: int) -> bool: """ Approach: Revert the half Time Complexity: O(log base 10 N) Space Complexity: O(1) :param num: :return: """ # base case if num < 0 or (num % 10 == 0 and num != 0): return False half = 0 while num > half: half = half * 10 + num % 10 num //= 10 return num == half or num == half // 10 if __name__ == "__main__": number = Number() print(number.is_palindrome(121)) print(number.is_palindrome(11)) print(number.is_palindrome(-121)) print(number.is_palindrome(11211)) print(number.is_palindrome(2442)) print(number.is_palindrome(2157))
false
46780f22b185fa8b881a63bb12a4c78e9e993e7b
Shiv2157k/leet_code
/revisited/trees/same_tree.py
1,537
4.125
4
from collections import deque class TreeNode: def __init__(self, val: int, left: int=None, right: int=None): self.val = val self.left = left self.right = right class BinaryTree: def is_same_tree_(self, t1: "TreeNode", t2: "TreeNode") -> bool: """ Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param t1: :param t2: :return: """ if not t1 and not t2: return True if not t1 or not t2: return False if t1.val != t2.val: return False return self.is_same_tree_(t1.left, t2.left) and self.is_same_tree_(t1.right, t2.right) def is_same_tree_(self, t1: "TreeNode", t2: "TreeNode") -> bool: """ Approach: Iteration Time Complexity: O(N) Space Complexity: O(N) :param t1: :param t2: :return: """ def check(tree_1: "TreeNode", tree_2: "TreeNode") -> bool: if not tree_1 and not tree_2: return True if not tree_1 or not tree_2: return False if tree_1.val != tree_2.val: return False return True queue = deque([(t1, t2)]) while queue: p, q = queue.popleft() if not check(p, q): return False if p: queue.append((p.left, q.left)) queue.append((p.right, q.right)) return True
false
5882a8db15e46c6cfcb1e523e8f111e698b16789
Shiv2157k/leet_code
/revisited__2021/linked_list/swap_nodes_in_pairs.py
1,811
4.21875
4
class ListNode: def __init__(self, val: int, next: int = None): self.val = val self.next = next class LinkedList: def swap_nodes_in_pairs_(self, head: "ListNode"): """ Approach: Iterative Time Complexity: O(N) Space Complexity: O(1) :param head: :return: """ new_head = ListNode(-1) new_head.next = head prev = new_head while head and head.next: # nodes to be swapped first = head second = head.next # swapping prev.next = second first.next = second.next second.next = first prev = first head = first.next return new_head.next def swap_nodes_in_pairs(self, head: "ListNode"): """ Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param head: :return: """ if not head or not head.next: return head # nodes to be swapped first = head second = head.next # swap first.next = self.swap_nodes_in_pairs(second.next) second.next = first return second if __name__ == "__main__": l1 = ListNode(1) l1.next = ListNode(2) l1.next.next = ListNode(3) l1.next.next.next = ListNode(4) linked_list = LinkedList() l2 = linked_list.swap_nodes_in_pairs(l1) while l2: print(l2.val) l2 = l2.next print("---------------------------------") ll = ListNode(1) ll.next = ListNode(2) ll.next.next = ListNode(3) ll.next.next.next = ListNode(4) linked_list1 = LinkedList() l3 = linked_list1.swap_nodes_in_pairs_(ll) while l3: print(l3.val) l3 = l3.next
true
79d35a93969f21c3087a68c0a5326d6f7055b346
Shiv2157k/leet_code
/goldman_sachs/implement_trie_prefix_tree.py
1,549
4.21875
4
class TrieNode: def __init__(self): self.child_nodes = {} self.end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word: str): """ Time Complexity: O(M) Space Complexity: O(M) :param word: :return: """ curr_node = self.root for ch in word: node = curr_node.child_nodes.get(ch, TrieNode()) curr_node.child_nodes[ch] = node curr_node = node curr_node.end = True def search_word(self, word: str) -> bool: """ Time Complexity: O(M) Space Complexity: O(1) :param word: :return: """ curr_node = self.root for ch in word: node = curr_node.child_nodes.get(ch, None) if not node: return False curr_node = node return curr_node.end def search_prefix(self, word: str) -> bool: """ Time Complexity: O(M) Space Complexity: O(1) :param word: :return: """ curr_node = self.root for ch in word: node = curr_node.child_nodes.get(ch) if not node: return False curr_node = node return True if __name__ == "__main__": trie = Trie() trie.insert("apple") print(trie.search_word("apple")) print(trie.search_word("app")) print(trie.search_prefix("app")) trie.insert("app") print(trie.search_word("app"))
false
df117ff3f1c3411a5f9a6bc55d364c40727fb8cc
Shiv2157k/leet_code
/expedia/merge_two_sorted_list.py
764
4.125
4
class ListNode: def __init__(self, val: int, next: int = None): self.val = val self.next = next class LinkedList: def merge_two_sorted_list(self, l1: "ListNode", l2: "ListNode") -> "ListNode": """ Approach: Iterative Time Complexity: O(M + N) Space Complexity: O(1) :param l1: :param l2: :return: """ pre_head = ListNode(None) prev = pre_head while l1 and l2: if l1.val <= l2.val: prev.next = l1 l1 = l1.next elif l2.val <= l1.val: prev.next = l2 l2 = l2.next prev = prev.next prev.next = l1 if l1 else l2 return pre_head.next
false
442f234a5a5e4a0fedf9bb5a8c89fcafcefab587
Shiv2157k/leet_code
/amazon/greedy_or_two_pointers/queue_reconstruction_by_height.py
656
4.25
4
from typing import List class People: def queue_reconstruction_by_height(self, people: List[List[int]]) -> List[int]: """ Approach: Greedy Time Complexity: O(N^2) - O(N log N) Sorting O(K) for inserting Space Complexity: O(N) :param people: :return: """ people.sort(key=lambda x: (-x[0], x[1])) queue = [] for person in people: queue.insert(person[1], person) return queue if __name__ == "__main__": p = People() print(p.queue_reconstruction_by_height( [ [7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2] ] ))
false
074c11ad90d77eb8641b6251f4065bc2c87c2855
Shiv2157k/leet_code
/goldman_sachs/shortest_word_distance.py
994
4.125
4
from typing import List class Words: def shortest_word_distance(self, words: List[str], word1: str, word2: str) -> int: """ Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return: """ p1 = p2 = -1 min_distance = len(words) for pointer, word in enumerate(words): if word == word1: p1 = pointer elif word == word2: p2 = pointer if p1 != -1 and p2 != -1: min_distance = min(min_distance, abs(p2 - p1)) return min_distance if __name__ == "__main__": w = Words() print(w.shortest_word_distance( ["practice", "makes", "perfect", "coding", "makes"], word1="coding", word2="practice" )) print(w.shortest_word_distance( ["practice", "makes", "perfect", "coding", "makes"], word1="makes", word2="coding" ))
true
1ed7487081e736f8b4732b114799d1b37bf59dee
obedansah/Smart_Game
/Smart_Game.py
1,315
4.1875
4
#Welcoming the Users name = input("Enter your name") print("Hello " +name,"Let's Play SmartGame") print("So what's your first guess") #Guess word word = "Entertainment" #creates an variable with an empty value guesses = " " #determine the number of runs runs = 15 while runs>0: # Create a while loop and check if the number of turns are greater than zero failed = 0 # make a counter that starts with zero for Char in word: # for every character in secret_word if Char in guesses: # Print if the character is in the players / users guess print(Char) # if not found, print a dash else: print("*") failed += 1 #if failed == 0 print you won if failed == 0: print("You won") break print() # ask the user to guess a character guess = input("Guess a Character:") guesses += guess # if guess is not found in the secret word if guess not in word: #number of runs is reduced by 1 runs -= 1 # print("Wrong guess") # The number of runs left print("You have", +runs, "more guesses") #if the number of runs is 0 print hurray you won if runs == 0: print("Hurray!!!! you lose")
true
cba91cabb82130749a4ca5026a76a949e0cd63b9
mastansberry/LeftOvers
/lotteryAK.py
1,573
4.125
4
''' matches(ticket, winners) reports how well a lottery ticket did test_matches(matches) reports whether a matches() function works as assigned. ''' def matches(ticket, winner): ''' returns the number of numbers that are in both ticket and winner ticket and winner are each a list of five unique ints returns an int from 0 to 5 inclusive. ''' # Could be done more effectively using the Python "set" type, # but that is not standard across programming languages # and is not introduced in the course. Could be: # return len(set(ticket) & set(winners)) score = 0 for number in ticket: if number in winner: score += 1 return score def test_matches(match_function): '''match_function is a function that takes two parameters, each a list of five unique ints. returns True if function works as expected; prints error and returns False otherwise. ''' def test(ticket, winner, expected): if match_function(ticket, winner) == expected: return True else: print(match_function+' returned '+expected+' when ') print(' ticket = '+str(ticket) +' and ') print(' winner = '+str(winner)) return False result = True result = result and test([1,2,3,4,5],[6,7,8,9,10],0) result = result and test([1,2,3,4,5],[1,6,7,8,9],1) result = result and test([1,2,3,4,5],[1,2,3,4,5],5) return result
true
07a9daea73195e3c57c8f793a15fe10a80eb561c
Setubal18/Introducao-as-AGs
/funcao1.py
547
4.15625
4
def converteBinarioReal(string): if(len(string)==8): return float(f'{int(string[:2], 2)}.{int(string[3::], 2)}') else: raise Exception('Número menor ou maior que o permitido') #recebe uma string com oito valores 'zero' ou 'um' sendo os dois primeiros #equivalentes à parte inteira e os seis restantes equivalente à parte #fracionária de um número binário. #A função deverá retornar este número convertido para um número real (float) #print(converteBinarioReal('11001100')) # saida na tela: 3.12
false
c239d4aedead6d00d326929403ba5ef36b5edbab
Varshitha019/Daily-Online-Coding
/25-06-2020/Program1.py
207
4.125
4
1. Write a python program for cube sum of first n natural numbers. def sumOfSeries(n): sum = 0 for i in range(1, n+1): sum +=i*i*i return sum n = int(input("Enter number:")) print(sumOfSeries(n))
true
b4685f71740233957125bbcf285279612d6e7669
Varshitha019/Daily-Online-Coding
/28-5-2020/Program2.py
611
4.28125
4
2. .Write a python program to find digital root of a number. Description: A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. digit_root(0)= 0 digital_root(16) => 1 + 6 => 7 digital_root(132189) => 1 + 3 + 2 + 1 + 8 + 9 => 24 ... => 2 + 4 def DigitalRoot(number): addper = 0 while number >=10: number = sum(int(digit)for digit in str(number)) addper +=1 print(number) DigitalRoot(2516)
true
e77acb53bf3bc9c86e18dc2b72ac6c86187b0ed0
gislig/hr2018algorithmAssignment1
/project2.py
1,166
4.28125
4
# 1. Checks if the first three numbers are entered # 2. If the numbers are above 3 then start sequencing # 3. Sums up the first, second and third number into a variable next_num # 4. Each step sets the last number to the next bellow # 5. Finally it prints out the next_num n = int(input("Enter the length of the sequence: ")) # Do not change this line first_num = 1 second_num = 2 third_num = 3 next_num = 0 # 1 + 2 + 3 = 6 # 2 + 3 + 6 = 11 # 3 + 6 + 11 = 20 # 6 + 11 + 20 = 37 # This is the formula # Checks if the n is more or less than one if n >= 1: print(first_num) # Checks if the n is more or less than two if n >= 2: print(second_num) # Checks if the n is more or less than three if n >= 3: print(third_num) # If n is more than three then enter the if loop if n > 3: # Sequence the numbers but remove the first three numbers because we have already gone through it for seq in range(n-3): # Sums up the first, second and third number into next number next_num = first_num + second_num + third_num first_num = second_num second_num = third_num third_num = next_num print(next_num)
true
c99cf490702d49b88dfd18cdb8592546a46d17d0
Nate-Rod/PythonLearning
/Problem_003.py
1,319
4.4375
4
''' Problem text: Time for some fake graphics! Let’s say we want to draw game boards that look like this: --- --- --- | | | | --- --- --- | | | | --- --- --- | | | | --- --- --- This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more). Ask the user what size game board they want to draw, and draw it for them. ''' class GameBoard: hLine = "---" vLine = "|" space = " " def __init__(self, length=3, width=3): self.length = length self.width = width def printBoard(self): for i in range (0, self.width): self.printHorizontal() self.printVertical() self.printHorizontal() return def printHorizontal(self): for i in range (0, self.length): print(" " + self.hLine, end="") print(" ") return def printVertical(self): for i in range (0, self.width): print(self.vLine + self.space, end="") print(self.vLine) return def main(): boardSize = int(input("What size board would you like?\n")) userBoard = GameBoard(boardSize, boardSize) userBoard.printBoard() return if __name__ == "__main__": main()
true
a18192ce83389931a90328b9b2b7fa21c282fe27
BravoCiao/PY103_Bravo
/ex11.py
1,921
4.375
4
print "How old are you?", age = raw_input("24") # i've tried to delete the comma and run the programme, # then the age shows,on the second line, the comma # is a prompt for data to show on the same line. # based on official handbook, raw_input() is written to standard output # without a trailing newline. The function then reads a line from input, # converts it to a string (stripping a trailing newline), and returns that. print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight) # in %r, r is for representation, but will use the raw_input # the contents between perentheses show the variable # is in that order # the first line end with an open perenthesis # because of 80 characters limitation # i try to put the answer in the perentheses of raw_input() without "", # the answer shows in the first three prints, python didn't tell me # to type in the answer, but the answer didn't show in the last two # Then, i put the answer with "", and it works, python tells me to type in the # answer and the answer shows in the last two prints # conclusion is, if you didn't put anything inside the perentheses of # raw_input(), the answer is typed in by yourself print # to add a new line print ("So, you're %r years old, %r cms tall, \n" "and %r kgs heavy.") % (age, height, weight) # this is the video i see on Youtube about lpthw # in that video, the uploader shows another way to # write the code if we want to add more text into # and that will excess the 80 character limitation # put the sentence in the perentheses, # this is called the adjacent string, the adjacent string # will merge into one single string # \n is to start a new line # i checked the python handbook about the definition of raw_input # but couldn't understand entirely
true
db546942befa0cb9745931a986ff2f75ee008c53
linusqzdeng/python-snippets
/exercises/string_lists.py
867
4.34375
4
'''Thsi program asks the user for a string and print out whether this string is a palindrome or not (a palindrome is a string that reads the same forwards and backwards) ''' # ask for a word something = input('Give me a word: ') # convert the given word into a list original_list = list(something) print(original_list) # check if the word is a palindrome or not check_list = original_list[::-1] if check_list == original_list: print('This word is a palindrome') else: print('This word is not a palindrome') # loop solution print('-'*40) def reverse(word): x = '' for i in range(len(word)): x += word[len(word)-i-1] return x word = input('Give me another word: ') x = reverse(word) print(x) if x == word: print('This word is a palindrome') else: print('This word is NOT a palindrome')
true
8d085b8f331fad09583bc0e31e40e961ea03e833
linusqzdeng/python-snippets
/exercises/guessing_game1.py
1,102
4.3125
4
''' This program generates a random number between 1 to 9 (including 1 and 9) and asks the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. ''' from random import randint num = randint(1, 9) attempt = 1 while True: guess = int(input('Guess what number I have got from 1 to 9?\n')) if guess not in list(range(1, 10)): print('Invalid input. You must select a number between 1 to 9.') attempt += 1 continue if guess > num: print('Too high! Try again!') attempt += 1 continue elif guess < num: print('Too low! Try again!') attempt += 1 continue elif guess == num: print('Bingo!') if input('Do you want to start again? Type \'exit\' to quit\n') == 'exit': print('Game over! You have tried', attempt, 'times to win.') break else: attempt = 1 continue else: print('Please choose a number between 1 to 9.') attempt += 1 continue
true
4501b4ba1f9e9b31875c063f1c21e36ac58475e2
zerynth/core-zerynth-stdlib
/examples/Interrupts/main.py
1,442
4.40625
4
################################################################################ # Interrupt Basics # # Created by Zerynth Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import streams # create a serial port stream with default parameters streams.serial() # define where the button and the LED are connected # in this case BTN0 will be automatically configured according to the selected board button # change this definition to connect external buttons on any other digital pin buttonPin=BTN0 ledPin=LED0 # LED0 will be configured to the selected board led # configure the pin behaviour to drive the LED and to read from the button pinMode(buttonPin,INPUT_PULLUP) pinMode(ledPin,OUTPUT) # define the function to be called when the button is pressed def pressed(): print("touched!") digitalWrite(ledPin,HIGH) # just blink the LED for 100 millisec when the button is pressed sleep(100) digitalWrite(ledPin,LOW) # attach an interrupt on the button pin and call the pressed function when it falls # being BTN0 configured as pullup, when the button is pressed the signal goes to from HIGH to LOW. # opposite behaviour can be obtained with the equivalent "rise" interrupt function: onPinRise(pin,fun) # hint: onPinFall and onPinRise can be used together on the same pin, even with different functions onPinFall(buttonPin,pressed)
true
981052ef2e22904af49c578dc06edab1df4834ea
SiddharthSampath/LeetCodeMayChallenge
/problem16.py
1,707
4.25
4
''' Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Example 1: Input: 1->2->3->4->5->NULL Output: 1->3->5->2->4->NULL Example 2: Input: 2->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL Note: The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on ... ''' ''' Approach: A mistake I was making was thinking of a LL in terms of an array and trying a bunch of swaps to get the odd nodes all together. The best solution here is, start with the odd at the head, even at head.next. The next odd node is at even.next. The next even node is at the next odd.next. By manipulating the next pointers to point to the next even and odd numbers, we get the required linked list. Code is pretty straightforward. Time Complexity : O(nodes) Space : O(1) ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if head is None: return None odd = head even = head.next evenHead = even while even is not None and even.next is not None: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = evenHead return head
true
20f31fa81f7e3ac014987d042e32ac4f0d9e2cc9
tonycmooz/Pythonic
/nested_function.py
277
4.15625
4
# An example of a nested function def outer(): x = 1 def inner(): print x # Python looks for a local variable in the inner inner() # then looks in the enclosing, outer outer() # Python looks in the scope of outer first # and finds a local variable named inner
true
94086d952013023c802590a289e042bcdaedc44f
iffishells/Regular-Expression-python
/Split-with-regular-expressions.py
908
4.71875
5
####################################### #### Split with regular expressions ### ###################################### import re # Let's see how we can split with the re syntax. This should look similar to how # you used the split() method with strings. split_term="@" phrase = "what is the domain name of someone domain with the email:iffishells@gmail.com" #return list at the spliting point..! print(re.split(split_term,phrase)) # Note how re.split() returns a list with the term to spit on removed and the # terms in the list are a split up version of the string. Create a couple of # more examples for yourself to make sure you understand! ############################################ ### Finding all instances of a pattern ##### ############################################ # You can use re.findall() to find all the instances of a pattern in a string. # For example: print(re.findall("domain",phrase))
true
743956f40ff4a5139d5fb2a6ce64688642238d39
ai230/Python
/draw_shape.py
504
4.125
4
import turtle def draw_square(): # Create window window = turtle.Screen() window.bgcolor("red") #Create object fig = turtle.Turtle() fig.shape("circle") fig.color("white") fig.speed(5) fig.forward(200) fig.right(90) fig.forward(200) fig.right(90) fig.forward(200) fig.right(90) fig.forward(200) fig2 = turtle.Turtle() fig2.shape("arrow") fig2.circle(100) #Close the window by click window.exitonclick() draw_square()
true
6263594794ac44dd19a4a81f202f5cc1fb63049b
1devops/fun
/project 1.py
318
4.40625
4
"""If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.""" def proj1(num): j = 0 for i in range(0, num): if i % 3 == 0 or i % 5 == 0: j = i + j print "final", j proj1(1000)
true
376ff13289b1b622db69e6591494d2d59a3256a8
bensoho/Python
/Basic_Python/Chapter03/01_data_structure.py
2,679
4.15625
4
#Python 数据结构 # 列表 # Python中列表是可变的,这是它区别于字符串和元组的最重要的特点,一句话概括即:列表可以修改,而字符串和元组不能。 # 以下是 Python 中列表的方法: # 方法 描述 # list.append(x) 把一个元素添加到列表的结尾,相当于 a[len(a):] = [x]。 # list.extend(L) 通过添加指定列表的所有元素来扩充列表,相当于 a[len(a):] = L。 # list.insert(i, x) 在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引,例如 a.insert(0, x) 会插入到整个列表之前,而 a.insert(len(a), x) 相当于 a.append(x) 。 # list.remove(x) 删除列表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误。 # list.pop([i]) 从列表的指定位置删除元素,并将其返回。如果没有指定索引,a.pop()返回最后一个元素。元素随即从列表中被删除。(方法中 i 两边的方括号表示这个参数是可选的,而不是要求你输入一对方括号,你会经常在 Python 库参考手册中遇到这样的标记。) # list.clear() 移除列表中的所有项,等于del a[:]。 # list.index(x) 返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。 # list.count(x) 返回 x 在列表中出现的次数。 # list.sort() 对列表中的元素进行排序。 # list.reverse() 倒排列表中的元素。 # list.copy() 返回列表的浅复制,等于a[:]。 # 将列表当做堆栈使用 # 列表方法使得列表可以很方便的作为一个堆栈来使用,堆栈作为特定的数据结构,最先进入的元素最后一个被释放(后进先出)。用 append() 方法可以把一个元素添加到堆栈顶。用不指定索引的 pop() 方法可以把一个元素从堆栈顶释放出来。 # 将列表当作队列使用 # 也可以把列表当做队列用,只是在队列里第一加入的元素,第一个取出来;但是拿列表用作这样的目的效率不高。在列表的最后添加或者弹出元素速度快,然而在列表里插入或者从头部弹出速度却不快(因为所有其他的元素都得一个一个地移动)。 # from collections import deque # queue = deque(["Eric", "John", "Michael"]) # queue.append('Terry') # queue.append('Gramham') # queue.popleft() # queue.popleft() # print(queue) vec = [2, 4, 6] # s = [(x,3*x)for x in vec] # print(s) # freshfruit = [' banana', ' loganberry ', 'passion fruit '] # s = [ x.strip() for x in freshfruit] # print(s) # s = [x*3 for x in vec if x > 3] # print(s) print(vec.index(4))
false
d7197fb18c63b4718cd3f24687925d0cf8e44029
rishav-ish/MyCertificates
/reverseStack_recu.py
398
4.125
4
#Reverse Stack using recursion def insert(stack,temp): if not stack: stack.append(temp) return temp2 = stack.pop() insert(stack,temp) stack.append(temp2) def reverse(stack): if not stack: return temp = stack.pop() reverse(stack) insert(stack,temp) arr = [1,2,3,45,6,7,1] reverse(arr) print(arr)
true
5480ea016f829075ef8d69d2905ff2ba8966189d
kostpasha/Homework-SP
/lab1/Zadanie_6.py
421
4.15625
4
import math R1=float(input('Ввести значение R1: ')) R2=float(input('Ввести значение R2: ')) R3=float(input('Ввести значение R3: ')) v1=(4/3)*math.pi*R1**3 v2=(4/3)*math.pi*R2**3 v3=(4/3)*math.pi*R3**3 Z=(v1+v2+v3)/3 print('Значение v1: ', v1) print('Значение v2: ', v2) print('Значение v3: ', v3) print() print('Значение Z: ', Z)
false
cc8605be2016f8acf8c4a29029ed2d4b5bf80e2b
thirihsumyataung/Python_Tutorials
/Fizz_Buzz_Python.py
748
4.125
4
#Fizz Buzz #if a number is divisilbe by 3 and 5 --> FIZZ BUZZ #elif a number is divisible by 3 --> FIZZ #elif a number is divisible by 5 --> BUZZ #else just a number ( user input ) myFizzBuzzList = [] aString = '' number = int(input('How many numbers user want to type ? ')) for i in range(number): userInput = int(input( )) #print(myFizzBuzzList) if (userInput%3 == 0) and (userInput%5 == 0): aString = 'FIZZ BUZZ' #print("Fizz BUZZ") elif (userInput%3) == 0: aString = 'FIZZ' #print(" FIZZ ") elif (userInput%5) ==0: aString = 'BUZZ' #print('BUZZ') else: aString = str(userInput) #print(userInput) myFizzBuzzList.append(aString) print(myFizzBuzzList)
false
6676dffc286556c70577090f37d2a7f94d1eb652
thirihsumyataung/Python_Tutorials
/function_CentigradeToFahrenheit_Converter_Python.py
801
4.3125
4
#Temperture converting from Centigrade to Fahrenheit is : # F = 9/5 * C + 32 #Question : F = Fahrenheit temperature # C = the centigrade temperature #Write a function named fahrenheit that accepts a centigrade temperature as an argument # function should return the temperature the temperature , converted to Fahrenheit #Demonstrate the function by calling it in a loop that displays a table of the Centigrade temperature 0 through 20 # and their Fahrenheit equivalents def fahrenheit(centigrade): F = round((1.8*int(centigrade)) + 32, 2) print(f'\t{centigrade}\t\t\t\t\t{F}') print('------------------------------------') print('Centigrade\t\t\tFahrenheit') print('------------------------------------') for i in range(20): fahrenheit(i) print('------------------------------------')
true
c2778ff17feadc65e78715ec67b201d09d9adbfe
thirihsumyataung/Python_Tutorials
/function_kineticEnergyCalculation_Python.py
779
4.375
4
#Write a function named kineticEnergy that accepts an object’s mass (in kilograms) and velocity (in meters per second) as arguments. # The function should return the amount of kinetic energy that the object has. # Demonstrate the function by calling it in a program that asks the user to enter values for mass and velocity. #Formula: KE = ½ mv2 where KE is the kinetic energy , m is the object's mass in kilograms , V is the object's velocity(in meters per second) def kineticEnergy(mass, velocity): KE = round((0.5 * mass * pow(velocity,2)), 2) print("Kinetic Energy : KE = " + str(KE)) return KE mass = float(input("An object's mass in kilograms: ")) velocity = float(input("The object;s velocity in meters per second: ")) KE = kineticEnergy(mass, velocity)
true
25761d97611f8acc56c87bbae58d07600d5054a5
sppess/Homeworks
/homework-13/hw-13-task-1.py
676
4.3125
4
from functools import wraps # Write a decorator that prints a function with arguments passed to it. # NOTE! It should print the function, not the result of its execution! # For example: # "add called with 4, 5" def logger(func): def wripper(*args, **kwargs): arguments = '' for arg in args: arguments += f"{arg}, " return f"{func.__name__} called with {arguments[0:-2]}" # new_str = ', '.join([arg for arg in args]) # return f"{func.__name__} called with {new_str}" return wripper @logger def add(x, y): return x + y @logger def square_all(*args): return [arg ** 2 for arg in args] print(add(3, 6))
true
abc589ba9207eac5da8ebad5db193fe0e7909b2f
hzhao22/ryanpython
/venv/hailstone.py
533
4.375
4
print ("Hail Stone") #Starting with any positive whole number $n$ form a sequence in the following way: #If $n$ is even, divide it by $2$ to give $n^\prime = n/2$. #If $n$ is odd, multiply it by $3$ and add $1$ to give $n^\prime = 3n + 1.$ def hailStone(n): numbers = [] while ( 1 not in numbers): if n % 2 == 0: n = n/2 else: n = 3 * n + 1 numbers.append(int(n)) return numbers for i in range(1, 31): mylist = hailStone(i) print(i, len(mylist), max(mylist))
true
97c9933472f1f2fab1c37d13c22fc91fa943dace
gstoel/adventofcode2016
/day3_DK.py
1,106
4.1875
4
# http://adventofcode.com/2016/day/3 from itertools import combinations from pandas import read_fwf # all combinations of 2 sides of a triangle tri = [list(n) for n in combinations(range(3), 2)] for n in range(3): tri[n].append(list(reversed(range(3)))[n]) def check_tri(sides): """checks whether the sum of any two sides must be larger than the remaining side""" while True: for n in tri: if not(sides[n[0]] + sides[n[1]] > sides[n[2]]): return False else: # loop fell through without finding violation, so sides is a triangle return True data = read_fwf('day3_input_DK.txt', header=None, widths=[5,5,5]) possible_triangles = 0 for row in data.iterrows(): if check_tri(row[1]): possible_triangles += 1 print('Number of possible triangles: {}'.format(possible_triangles)) # triangles defined vertically pos_tri = 0 for col in data.columns: for t in range(0, len(data), 3): if check_tri(list(data[col][t:t+3])): pos_tri += 1 print('Number of possible triangles: {}'.format(pos_tri))
true
4def4f4e7119ff665c9279a80916c60a64ce1af9
awsk1994/DailyCodingProblems
/Problems/day23.py
2,273
4.1875
4
''' This problem was asked by Google. You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on. Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board. For example, given the following board: [[f, f, f, f], [t, t, f, t], [f, f, f, f], [f, f, f, f]] and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of steps required to reach the end is 7, since we would need to go through (1, 2) because there is a wall everywhere else on the second row. ''' from collections import deque def is_end(elem, end): return elem[0] == end[0] and elem[1] == end[1] def is_not_wall(tile, matrix): return matrix[tile[0]][tile[1]] == False def is_valid_tile(seen, matrix, tile): t0_within_bounds = (tile[0] < len(matrix) and tile[0] >= 0) t1_within_bounds = (tile[1] < len(matrix[0]) and tile[1] >= 0) return (t0_within_bounds and t1_within_bounds) and (is_not_wall(tile, matrix) and tile not in seen) # in range, not tree and not already seen. def get_neighbors(seen, matrix, elem): return [n for n in [ (elem[0], elem[1]+1), # top (elem[0] - 1, elem[1]), # left (elem[0], elem[1]-1), # bot (elem[0] + 1, elem[1]) # right ] if is_valid_tile(seen, matrix, n)] def bfs(matrix, s, e): seen = set() q = deque() q.append((s, 0)) while q: elem, cost = q.popleft() neighbors = get_neighbors(seen, matrix, elem) seen.add(elem) for n in neighbors: q.append((n, cost + 1)) if is_end(n, e): return cost + 1 return None def main(): matrix = [[False, False, False],[False, True, False],[False, False, False]] start = (0,0) end = (2,2) print(bfs(matrix, start, end)) matrix = [[False, False, False],[False, True, False],[False, True, False]] start = (2,0) end = (2,2) print(bfs(matrix, start, end)) if __name__ == "__main__": main()
true
bbe885cb3e51c0c7b083a7a42d634dfc143e3d6a
Kapral26/solutions_from_checkio.org
/elem_list.py
249
4.125
4
''' returns a tuple with 3 elements - first, third and second to the last ''' def easy_unpack2(elements: tuple) -> tuple: return(elements[0],elements[2], elements[-2]) print(easy_unpack2((1, 2, 3, 4, 5, 6, 7, 9))) print(easy_unpack2((6, 3, 7)))
true
dc19208a3b7aa093a1588f3abb635f7c67c427b2
bnitin92/coding_practice
/Interview1_1/9_30.py
1,436
4.125
4
# finding the depth of a binary tree """ input : root Binary tree : not balanced ouput: the height of the tree 5 / \ 4 7 / \ \ 12 15 15 \ 19 use Breadth first search """ class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None def height(root): # BFS use queues #res = [] if root == None: return None queue = [] queue.append(root) count = -1 while queue: level_length = len(queue) levelelement = [] count += 1 for _ in range(level_length): current = queue.pop(0) levelelement.append(current.val) if current.left: queue.append(current.left) if current.right: queue.append(current.right) #res.append(levelelement) return count #len(res) - 1 def main(): root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.right.left = TreeNode(4) root.right.left.left = TreeNode(5) # root = TreeNode(5) # root.left = TreeNode(4) # root.right = TreeNode(7) # root.left.left = TreeNode(12) # root.left.right = TreeNode(15) #root = TreeNode(5) #root = None print("height:", str(height(root))) main()
true
6432a0c3992552346b7bff30f72c4980422c513e
bnitin92/coding_practice
/Recursion_DP/8.1 Triple Step.py
491
4.3125
4
""" A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. """ def tripleStep(n): if n < 0: return 0 if n == 0: return 1 else: return tripleStep(n-3) + tripleStep(n-2) + tripleStep(n-1) # We multiply the values when it's "we do this then this:' We add them when it's "we do this or this:' print(tripleStep(3))
true
8c6d32b839e851b019b2a8936e8809b97e28a361
MarineKing5248/MLPython
/chapter4/gradient_descent.py
1,000
4.21875
4
# 1) An Empty Network weight = 0.1 alpha = 0.01 def neural_network(input, weight): prediction = input * weight return prediction # 2) PREDICT: Making A Prediction And Evaluating Error number_of_toes = [8.5] win_or_lose_binary = [1] # (won!!!) input = number_of_toes[0] goal_pred = win_or_lose_binary[0] pred = neural_network(input,weight) error = (pred - goal_pred) ** 2 # 3) COMPARE: Calculating "Node Delta" and Putting it on the Output Node delta = pred - goal_pred # 4) LEARN: Calculating "Weight Delta" and Putting it on the Weight weight_delta = input * delta # 5) LEARN: Updating the Weight alpha = 0.01 # fixed before training weight -= weight_delta * alpha #### reducing error weight, goal_pred, input = (0.0, 0.8, 0.5) for iteration in range(8): pred = input * weight error = (pred - goal_pred) ** 2 delta = pred - goal_pred weight_delta = delta * input weight = weight - weight_delta print("Error:" + str(error) + " Prediction:" + str(pred))
true
b08fc4ba6f9053b9ffbae0c391bdaa10f7df906d
giacomocallegari/spatial-databases-project
/src/main.py
1,394
4.125
4
from src.geometry import Point, Segment from src.structures import Subdivision def main(): """Main function. After providing a sample subdivision, its trapezoidal map and search structure are built. Then, points can be queried to find which faces contain them. """ example = 2 # Number of the example # Create a sample subdivision. print("\n\n*** INITIALIZATION ***") segments = set() if example == 1: p1 = Point(2, 4) q1 = Point(9, 6) p2 = Point(6, 3) q2 = Point(12, 2) s1 = Segment(p1, q1) s2 = Segment(p2, q2) segments = {s1, s2} elif example == 2: p1 = Point(10, 8) p2 = Point(2, 4) p3 = Point(6, 2) p4 = Point(20, 4) p5 = Point(12, 10) p6 = Point(16, 6) s1 = Segment(p1, p2) s2 = Segment(p2, p3) s3 = Segment(p3, p4) s4 = Segment(p4, p5) s5 = Segment(p2, p6) segments = {s1, s2, s3, s4, s5} S = Subdivision(segments) # Build the trapezoidal map and the search structure. print("\n\n*** CONSTRUCTION ***") S.trapezoidal_map() # Query a sample point. print("\n\n*** QUERY ***") query_point = Point(4, 2) face = S.T.D.query(query_point) print("\nPoint " + str(query_point) + " is located here:\n" + str(face)) if __name__ == "__main__": main()
true
83e1cae23a573214248dadb3d9ed670330319555
ruppdj/Curriculum
/Beginner_Level/Unit1/Practice_what_you_learned/variables.py
308
4.15625
4
"""Variables""" # To set the value 3 to the variable distance we code distance = 3 # 1. Set the variable speed to the value 5. speed = # 2. Set the variable fast_speed to the value True. # 3. Change the value in the variable below to 1.23 # What will be printed now? a_variable = 3.4 print(a_variable)
true
cfd13f7dd2db899ebba36c992cefc0580c04a2dd
sdg000/git
/lowerANDupperlimit_code.py
1,849
4.46875
4
#Write a script to take in a lower limit and an upper limit. #And based on the users selection, provide all the even or odd #numbers within that range. #enter a new range: then display odd or even values following that. #if not , then exit. ''' VARIABLES TO DECLARE LowerL UpperL odd_range even_range ''' LowerL=input('enter a lower limit: ') UpperL=input('enter upper limit: ') RangeOption=raw_input('do you prefer your range odd or even ? ODD/EVEN ') if LowerL%2!=0 and RangeOption=='ODD': print range(LowerL,UpperL,2) elif LowerL%2==0 and RangeOption=='ODD': print range(LowerL+1,UpperL,2) elif LowerL%2==0 and RangeOption=='EVEN': print range(LowerL,UpperL,2) elif LowerL%2!=0 and RangeOption=='EVEN': print range(LowerL+1,UpperL,2) else: print('your ranges are stupid') RESTART =raw_input('wanna go again ? YES/NO ') if RESTART=='YES': print('I would have to call something to make the whole process start again') if RESTART=='NO': print('Thank you for making my job easier...off to play') exit() ''' choice=raw_input('do you want odd or even range btn ur limits ? ' ) if choice=='odd': print(odd_range()) elif choice=='even': print(even_range()) # 1 if start is odd (n%2!=0), then step by 2 regardless of END VALUE. to get ODD range # 3 if start is even (n%2=0), then step by 2 regardless of END VALUE. to get EVEN range # 4 if start is odd, increase by one and step by 2 to get EVEN RANGES # 2 if start is even, increase by one and step by 2 to get ODD RANGES #even number display for i in lower_limit: print(lower_limit,+1) #if lower_limit%2==0: """ llimit ulimit oddrange evenrange newrange newllmit newulimit noodrange nevenrange def even_range(): return range(LowerL,UpperL,2) def odd_range(): return range(LowerL,UpperL,3) '''
true
18a85925742b90cc3618d42435ba3684caaf7614
fr0z3n2/Python-Crash-Course-Examples
/ch2_variables_and_strings/print_message.py
494
4.53125
5
''' This is how to print a message in python 3 ''' # Storing the message in a variable. message = "This is a message ;)" print(message) message = 'Holy crap "Look at these quotes"' print(message) message = "holy cRaP 'look again'" print(message) # The title method puts the characters in upper case. print(message.title()) print(message.upper()) print(message.lower()) print("Hey\n\tnew\n\tline\n\t") python = ' python ' print(python.rstrip()) print(python.lstrip()) print(python.strip())
true
c4dfc75f401eeddfd21b968c9ba149e204640089
Niaksis/Example
/python/колво четных и нечетных.py
923
4.34375
4
'''Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).''' print("Эта программа посчитает из вашего числа количество четных и нечетных цифр") even = 0 odd = 0 list_even = [] list_odd = [] list_num = [] number = int(input("Введите целое число: ")) while number > 10: x = number % 10 number = number // 10 list_num.append(x) for l in list_num: if l % 2 == 0: list_even.append(l) even +=1 else: list_odd.append(l) odd += 1 print(f'В вашем числе {odd} четных и {even} нечетных цифр.\nЧетные = {list_even}.\nНечетные = {list_odd}')
false
62a5324ffbf462e7c2003314afe70526edead42c
MalithaDilshan/Data-Structures-and-Algorithms
/Sorting/Selection Sort/selectionsort.py
1,301
4.34375
4
''' This is the code for the selection sort algorithm This code will handle the execution time using the time.time() method in python and here use the random arrays (using the random()) as the input to the algorithm to sorting to ascending order ''' import time import random random.seed() #test cases enable what you want # This will generate the 10000 length of numbers that are in range 1-1000000 mylist=[random.randint(1,1000000) for i in range (10000)] #mylist=sorted(mylist, key=int, reverse=True) # input a descending order list #mylist=sorted(mylist) # input the ascending order list #mylist=[] #print(mylist) start=time.time() # start the tim# print(mylist) print the list def selection_sort(mylist): length = len(mylist) for i in range (length-1,0,-1): # reverse for loop elementposition=0 for j in range(1,i+1): # to find the max element in each step if mylist[elementposition]<mylist[j]: elementposition=j # use the tmperory veriable to swaping tem=mylist[i] mylist[i]=mylist[elementposition] mylist[elementposition]=tem selection_sort(mylist) end =time.time() print("sorted") print(mylist) print() elapsedtime=end-start print("time(ms) : %0.5f"% (1000*elapsedtime))
true
0dc4cb22e911d581c47016f3214c5e1e0846d823
Sam-Power/Trials
/Exercises/Statistics/Assignment-3.py
1,547
4.28125
4
"""EXERCISE 1. The following data represent responses from 20 students who were asked “How many hours are you studying in a week?” 16 15 12 15 10 16 16 15 15 15 12 18 12 14 10 18 15 14 15 15 What is the value of the mode? The median? The mean? EXERCISE 2. Use the data below to calculate the mean, variance, and standard deviation. 10 9 7 9 8 9 5 4 EXERCISE 3. The list named as salary represents the yearly income for some data scientists in USA. salary = [120, 80, 85, 85, 80, 83, 100, 105, 105, 85, 75, 125, 120, 105, 85, 80, 95, 90, 95, 85, 80, 85, 120, 100, 105, 90] Calculate the mean, median, mode, range, interquartile range, variance, and standard deviation in Python. What can you conclude from these measures?""" #EXERCISE 1. import numpy as np import scipy.stats as stats print("#EXERCISE 1") data = [16,15, 12, 15, 10, 16, 16, 15, 15, 15, 12, 18 ,12 ,14 ,10 ,18 ,15 ,14,15,15] print(f"mode: {stats.mode(data)}") print(f"median : {np.median(data)}") print(f"mean : {np.mean(data)}") #EXERCISE 2 print("#EXERCISE 2") data = [10 ,9, 7, 9 ,8 ,9 ,5 ,4] print(f"mean : {np.mean(data)}") print(f"var : {np.var(data)}") print(f"std : {np.std(data)}") #EXERCISE 3 print("#EXERCISE 3") salary = [120, 80, 85, 85, 80, 83, 100, 105, 105, 85, 75, 125, 120, 105, 85, 80, 95, 90, 95, 85, 80, 85, 120, 100, 105, 90] print(f"mean : {np.mean(salary)}") print(f"median : {np.median(salary)}") print(f"mode : {stats.mode(salary)}") print(f"range : {max(salary) - min(salary)}") print(f"iqr : {stats.iqr(salary)}") print(f"std : {np.std(salary)}")
true
4044b4aa2dd63741b06f7632f462d1df05c26669
nickvarner/automate-the-boring-stuff
/04-first-complete-program/numberGuessing.py
610
4.125
4
#This is a guess the number game. import random print('Hello! What is your name?') userName = input() print('Well ' + userName + ", I'm thinking of a number between 1-20.") secretNum = random.randint(1,20) for guessesTaken in range(1, 7): print('Take a guess!') guess = int(input()) if guess < secretNum: print("You're guess is too low.") elif guess > secretNum: print("You're guess is too high.") elif guess == secretNum: print("You got it! The number was " + str(secretNum) + "! Nice Job.") break print('You took ' + str(guessesTaken) + ' guesses.')
true
7a5d9234b3d407ed4e1adc22f8bd5e4e845fec8d
ShijieLiu-PR/Python_Learning
/month01/python base/day04/code03.py
611
4.1875
4
""" 字符串操作 """ # 1.数学运算 str01 = "wukong" str02 = "bajie" #创建新对象 str03 = str01 + str02 print(str03) #容器可以与数字相乘 str04 = str01 * 3 print(str04) print(str01 > str02) for item in str01: print(ord(item)) # 2.成员运算 str03 = "猥琐发育,别浪!" print("猥琐" in str03) # 3.索引 str04 = "abcdef" print(str04[0]) print(str04[len(str04) - 1]) print(str04[-1]) # 4.切片slice str05 = str04[0:3:2] print(str05) print(str04[::]) print(str04[::-1]) print(str04[1:19]) #切片即使越界,也不会报错 print("----------------") print(str04[3:1:-1])
false
e61039ada9393964301b2363ca6f090faeb2757f
ShijieLiu-PR/Python_Learning
/month01/python base/day05/code02.py
414
4.125
4
""" 列表推导式 """ list01 = [3,5,6,7,9] # 需求:创建新列表,每个元素是list01中的元素的平方 list02 = [] for item in list01: list02.append(item **2) print(list02) list03 = [item ** 2 for item in list01] print(list03) # 需求:创建新列表,如果元素是偶数,则将该元素的平方存入新列表 list04 = [item ** 2 for item in list01 if item % 2 != 0] print(list04)
false
a414e7ab54f84b7bc6157155f73d914c5fca7a27
ShijieLiu-PR/Python_Learning
/month01/python base/day16/code02.py
438
4.3125
4
""" 生成器表达式 """ list01 = [2,3,4,6] result = [ x**2 for x in list01] print(result) result = (x**2 for x in list01) for item in result: print(item) list02 = [2,3,4,6] # 练习:使用列表推导式与生成器表达式,获取列表list02中大于3的数据。 result01 = [item for item in list02 if item > 3] print(result01) result02 = (item for item in list02 if item > 3) for item in result02: print(item)
false
c857cc2eb199b41ab3e029618ac73dd7894120c5
ShijieLiu-PR/Python_Learning
/month01/python base/day04/exercise01.py
231
4.3125
4
# 练习1:在控制台中获取一个字符串,打印每个字符的编码值。 str_input = input("Please input string:") for item in str_input: print(ord(item)) else: print("Complete!") print(ord("a")) print(bin(11))
false
e9a42970ce63c9f9e0c7ea825c3fa03a0a9fdc09
ShijieLiu-PR/Python_Learning
/month01/python base/day02/review.py
775
4.59375
5
""" day01复习 1. python定义:免费的,开源的,跨平台的,动态的,面向对象的编程语言 2. 执行方式:交互式和文件式 3. 执行过程:源代码-编译->字节码-解释->机器码 4. 函数:功能,做功能的人--函数定义者 使用功能的人--函数调用者 print("需要显示的信息") 将括号中的内容显示到控制台中 变量=input("需要显示的信息") 从控制台中获取信息 5. 变量:存储对象低着的标识符, 见名知义 """ # 练习:在控制台中获取一个变量 # 再获取一个变量 # 输出结果 a = input("input var a:") b = input("input var b:") a, b = b, a print("a is :", a) print("b is :", b)
false
0716cd827ea6026471f6e1d28483cab1a2c33b06
Tanmay-Shinde/Python
/Arithmetic operators.py
308
4.1875
4
#Arithmetic Operators print(3+5) # Addition print(3-5) # Subtraction print(3*5) # Multiplication print(6**2) # Exponentiation print(6/2) # Division (returns Quotient as floating value) print(6//2) # Division (returns Quotient as integer value) print(6%2) # Modulo Operator - returns the remainder
true
dd0eb1fd68a35a32d4a63c16df74367a4c6a4a21
aryanmotgi/python-training
/training-day-9.py
747
4.15625
4
class MyClass: # atrribute or methods go here pass myObj = MyClass() class Person: def __init__(self, name, age): """ This methods is executed every time we created a new `person` instance `self` is the object instanve being created.""" self.name = name self.name = age self.num_arms = 2 self.nums_legs = 2 self.num_limbs = self.num_arms + self.nums_legs def print_name_and_age(self): print("Name:", self.name, "\nAge:", self.age) person1 = Person("Bob", 15) class Dog: def __init__(self,name): self.name=name def speak(message): print("*woof* "+ message+" *woof") dog1=Dog("Rocco") print(dog1.name,dog1.speak("hello"))
true
132f53ace51e422b8506cae237fbb30ba673fb22
dfrantzsmart/metis-datascience
/Pair-Programming/01-12-reverser.py
661
4.28125
4
""" ## Pair Programming 1/12/2016 ## Reverser of string ## Ozzie with Bryan Pair Problem You may be asked to write code that reads from standard input and/or writes to standard output. For example, you will be asked to do that now. Write a program that reads from standard input and writes each line reversed to standard output. For example, if your Python script is called "reverser.py", you could do this at a command line: echo -e "first line\nsecond line" | python reverser.py And the output should be: enil tsrif enil dnoces """ # magic string reverse super useful and stuff import sys n = sys.stdin.read() def rev(n): return n[::-1] print(rev(n))
true
bbb8676999f0fefc1ece885fb1929ede01415a22
antymijaljevic/google_python_course
/seconds_of_iteration.py
668
4.15625
4
#!/home/amijaljevic/anaconda3/bin/python3 print("ITERATION TIME CALCULATOR\n") numOfElements = float(input("Number of elements to iterate through loop? > ")); loopNum = float(input("How many loops you have? > ")); milisec = 1000; minAndHour = 60; numOfElements = numOfElements ** loopNum; resultInMili = numOfElements * milisec; resultInSec = numOfElements / milisec; resultInMin = resultInSec / minAndHour; resultInHours = resultInMin / minAndHour; print("\nIn miliseconds ==> " + str(int(resultInMili))); print("In seconds ==> " + str(int(resultInSec))); print("In minutes ==> " + str(int(resultInMin))); print("In hours ==> " + str(round(resultInHours, 2)));
false
ab837ad96b076533c9f146e58d7af43ad2358389
sebadp/LeetCode---Python
/sortArrayByParity.py
1,167
4.25
4
def sortArrayByParity(A): """ Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example 1: Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. """ # # FIRST APPROACH # #declarar variables una para pares y otra para impares. # pares = [] # impares = [] # # #for recorrer la lista y separarlos # for i in A: # if i % 2 == 0: # pares.append(i) # else: # impares.append(i) # # #juntar la lista y retornar el output que nos piden. # return print(pares + impares) # SECOND APPROACHGIT # ordered_list = A.copy() # for i in A: # if i%2==1: # ordered_list.append(i) # ordered_list.remove(i) # return print(ordered_list) # MORE CLEVER APROACH: Reduces memory usage and code # return print(sorted(A, key = lambda x : x % 2)) if __name__ == '__main__': # sortArrayByParity([3, 1, 2, 4])
true
dbeab0c45b25f8651e4f53bf4079be1e9da143b9
dssheldon/pands-programs-sds
/es.py
1,691
4.1875
4
# Sheldon D'Souza # G00387857 # Weekly task 7 # The objective of the task is to write a program that reads a text file and outputs the number of 'e's it contains # I amended the program slightly to take in a user input search character but the default remaining as e # As instructed the program will take the filename on the command line # Reference: Week 7 Lectures and Real Python blog post # Obtained the mobydick.txt file from ftp://ftp.cs.princeton.edu/pub/cs226/textfiles/mobydick.txt # I added on a step importing Path from the pathlib library so that the input could take a full file path rather than only a file name # I googled how to do this from pathlib import Path file_name = Path(input('Please enter the name and path of the file: ')) # ask user to input the file name search_char = input('Please enter the search character (press enter to select "e"): ') # takes a user input search character if search_char == '': # if no search character is input then search_char = 'e' # the default search character will be e with open(file_name, 'r') as search_file: # opens the file search_file_text = search_file.read() # reads the file and stores the text in a variable list_for_ss = [] # create an empty list to store the number times the search character occurs for text in search_file_text: # iterates through the text within the open file if text == search_char: # searches for each iteration of the search character in the search text list_for_ss.append(text) # appends all positive hits into the specified list print('The number of times', search_char, 'appears in', file_name.name, 'is', len(list_for_ss)) # prints the length of the list
true
35a9fc3839f5c8f0c0e81e68f1a9655bacbb2417
rohyat/EXCEL_AUTOMATION_WITH_PYTHON
/write.py
2,333
4.40625
4
def column_edit(s, row, column, wb): coln = int(input("ENTER THE COLUMN NUMBER\n")) if(coln > column): print("U HAVE ENTERED WRONG COLUMN NUMBER\n") else: f = int(input('''PRESS THE RIGHT OPTION THIS WILL DONE TO ALL CELLS OF COLUMN EXCEPT FIRST\n'1'--FOR ADD(+)\n'2'--FOR SUBTRACT(-)\n'3'--FOR MULTIPLY(*)\n''')) if(f == 1): n = int( input("ENTER THE NUMBER YOU WANT TO ADD TO CELLS OF COLUMN NUMBER\n")) for i in range(2, row+1): s.cell(i, coln).value = s.cell(i, coln).value+n wb.save("data.xlsx") elif(f == 2): n = int( input("ENTER THE NUMBER YOU WANT TO SUBTRACT TO CELLS OF COLUMN NUMBER\n")) for i in range(2, row+1): s.cell(i, coln).value = s.cell(i, coln).value-n wb.save("data.xlsx") elif(f == 3): n = int( input("ENTER THE NUMBER YOU WANT TO MULTIPLY TO CELLS OF COLUMN NUMBER\n")) for i in range(2, row+1): s.cell(i, coln).value = s.cell(i, coln).value*n wb.save("data.xlsx") else: print("U HAVE CHOSEN A INVALID CHOICE\n") def cell_edit(s, row, column, wb): rown = int(input("ENTER THE ROW NUMBER OF CELL\n")) coln = int(input("ENTER THE COLUMN NUMBER OF CELL\n")) if(rown > row or coln > column): print("U HAVE ENTERED VALUE OUT OF RANGE\n") else: value = int(input("PRESS\n1--STRING\n2--INTEGER\n")) if(value == 1): newvalue = input("ENTER THE NEW STRING\n") s.cell(rown, coln).value = newvalue elif(value == 2): newvalue = input("ENTER THE NEW NUMBER\n") s.cell(rown, coln).value = newvalue else: print("U HAVE ENTERED WRONG CHOICE\n") def add_row(s, row, column, wb): print("UR ROW WILL BE EDITED AFTER THE LAST PRESENT ROW\n") for j in range(1, column+1): value = int(input("PRESS\n1--STRING\n2--INTEGER\n")) if(value == 1): newvalue = input("ENTER THE NEW STRING\n") s.cell(row+1, j).value = newvalue elif(value == 2): newvalue = input("ENTER THE NEW NUMBER\n") s.cell(row+1, j).value = newvalue row = row+1 wb.save("data.xlsx")
false
377d4dfa97ff594717d6973bc512132c26f28e30
Dhanya-bhat/MachineLearning_Programs
/3-9-2020/HighestOf3values-p5.py
354
4.5625
5
5.Write a Python program to find the highest 3 values in a dictionary. from collections import Counter my_dict = {'elston': 30, 'winston': 40, 'alsten': 60, 'royston': 50, 'joyston': 20} k = Counter(my_dict) high = k.most_common(3) print("Dictionary with 3 highest values are :") print("Keys: Values") for i in high: print(i[0]," :",i[1]," ")
false
a3d99c04c8e39bb909ff2d0088a1b85cb00e3de5
Zhou-jinhui/Python-Crash-Course-Exercise
/Chepter4Slice.py
2,422
4.5
4
# Chepter 4 Working with part of a list # Slice players = ["charles", "martina", "michael", "florence", "eli"] print(players[0:3]) # !!! It's a colon in the square bracket, not commas. print(players[1:4]) print(players[:4]) print(players[2:]) print(players[-3:]) # Looping through a slice players = ["charles", "martina", "michael", "florence", "eli"] print("Here are the first three players on my team:") for player in players[:3]: print(player.title()) # Copying a list my_foods = ["pizza", "falafel", "carrot cake"] friend_foods = my_foods[:] my_foods.append("cannoli") friend_foods.append("ice cream") print(my_foods) print(friend_foods) # TRY IT YOURSELF # 4-10. Slices: Using one of the programs you wrote in this chapter, add several # lines to the end of the program that do the following: # • Print the message, The frst three items in the list are: Then use a slice to # print the frst three items from that program’s list # • Print the message, Three items from the middle of the list are: Use a slice # to print three items from the middle of the list # • Print the message, The last three items in the list are: Use a slice to print # the last three items in the list players = ["charles", "martina", "michael", "florence", "eli"] print("The first three items in the list are:") print(players[:3]) print("Three items from the middle of the list are:") print(players[1:4]) print("The last three items in the list are:") print(players[-3:]) # 4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1 # (page 60) Make a copy of the list of pizzas, and call it friend_pizzas # Then, do the following: # • Add a new pizza to the original list # • Add a different pizza to the list friend_pizzas # • Prove that you have two separate lists Print the message, My favorite # pizzas are:, and then use a for loop to print the frst list Print the message, # My friend’s favorite pizzas are:, and then use a for loop to print the second list Make sure each new pizza is stored in the appropriate list my_pizzas = ["apple", "banana", "tomato"] friend_pizzas = my_pizzas[:] my_pizzas.append("cheese") friend_pizzas.append("ice cream") print("My favorite pizzas are:") for i in my_pizzas: print(i+" pizza.") print("My friend's favarite pizzas are:") for i in friend_pizzas: print(i+" pizza.")
true
00069a2c8dcc8fbf17458c148b7f02be35cf7678
alsgk0221/Java_Project
/src/chap4/추상메소드구현.py
2,002
4.15625
4
import math class Shape: def __init__(self): self.name = "모양" def area(self): raise NotImplementedError("이것은 추상메소드입니다. ") def perimeter(self): raise NotImplementedError("이것은 추상메소드입니다. ") class Rectangle(Shape): def __init__(self, w, h): super().__init__() self.w = w self.h = h self.name = "사각형" def area(self): print("넓이 : %s " % self.name) return self.w*self.h def perimeter(self): print("둘레 : %s " % self.name) return 2*(self.w+self.h) class Circle(Shape): def __init__(self, r): super().__init__() self.r = r self.name = "원" def area(self): print("넓이 : %s " % self.name) return math.pi*self.r*self.r def perimeter(self): print("둘레 : %s " % self.name) return 2*math.pi*self.r class Triangle(Shape): def __init__(self, x1, y1, x2, y2, x3, y3): super().__init__() self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.x3 = x3 self.y3 = y3 self.name = "삼각형" def area(self): print("넓이 : %s " % self.name) return 0.5*math.fabs((self.x1*self.y2+self.x2*self.y3+self.x3*self.y1)-(self.x1*self.y3+self.x3*self.y2+self.x2*self.y1)) def perimeter(self): print("둘레 : %s " % self.name) return math.sqrt((self.x1-self.x2)*(self.x1-self.x2)+(self.y1-self.y2)*(self.y1-self.y2))+math.sqrt((self.x2-self.x3)*(self.x2-self.x3)+(self.y2-self.y3)*(self.y2-self.y3))+math.sqrt((self.x3-self.x1)*(self.x3-self.x1)+(self.y3-self.y1)*(self.y3-self.y1)) r1 = Rectangle(10, 20) print(r1.area()) print(r1.perimeter()) r2 = Circle(10) print(r2.area()) print(r2.perimeter()) r3 = Triangle(10, 10, 20, 20, 20, 10) print(r3.area()) print(r3.perimeter())
false
2c9d0340d2ea59cf566a7c60360b766a6f1a0209
karinnecristina/Curso_Python
/Programacao_Procedural/zip.py
433
4.34375
4
''' Considerando duas listas de inteiros ou floats (lista A e lista B) Some os valores nas listas retornando uma nova lista com os valores somados: Se uma lista for maior que a outra, a soma só vai considerar o tamanho da menor. Exemplo: lista_a = [1,2,3,4,5,6,7] lista_b = [1,2,3,4] Resultado: [2,4,6,8] ''' lista_a = [1,2,3,4,5,6,7] lista_b = [1,2,3,4] lista_soma = [x+y for x, y in zip(lista_a, lista_b)] print(lista_soma)
false
03682e34db14e13d8d458b185a7d11d2489a7506
karinnecristina/Curso_Python
/Logica_de_Programacao/Tamanho_da_string.py
543
4.15625
4
''' Faça um programa que peça o primeiro nome do usuário. Se o nome tiver 4 letras ou menos escreva "Seu nome é curto"; se tiver entre 5 e 6 letras, escreva "Seu nome é normal"; maior que 6 letras escreva "Seu nome é muito grande". ''' nome = input('Qual o seu nome?: ') tamanho = len(nome) if tamanho <= 4: print(f'Seu nome tem {tamanho} letras, e é um nome curto.') elif tamanho <= 6: print(f'Seu nome tem {tamanho} letras, e é um nome normal.') else: print(f'Seu nome tem {tamanho} letras, e é um nome muito grande.')
false
ca5af8027fc67847c56a641fb996d7a0f8c3e517
AchWheesht/python_koans
/python3/koans/triangle.py
1,064
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): max_length = a + b min_length = a - b if min_length < 0: min_length *= -1 if c >= max_length or c <= min_length: raise TriangleError("Not a legal triangle!") triangle_set = {a, b, c} for item in triangle_set: if item <= 0: raise TriangleError("Not a legal side length!") if len(triangle_set) == 1: return "equilateral" elif len(triangle_set) == 2: return "isosceles" else: return "scalene" # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
true
de61b7fcb0b2521097f41b1a8e140764dea0158e
meghavijendra/K_means_model
/elbow_method.py
1,857
4.28125
4
#!/usr/bin/env python # coding: utf-8 # ## Finding optimum value for number of clusters for k-means clustering # <p> Here we are trying to find the optimum value of k which needs to be used for the k-means algorithm in order to get the more accurate results</p> # <p> We can either use this method to get the optimum k values or randomly assign k values to the algorithm and find out which one offer the best accurary</p> # In[7]: #importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # In[8]: #importing the Iris dataset with pandas df_iris = pd.read_csv('Iris.csv') x = df_iris.iloc[:, [0, 1, 2, 3]].values # <p> Here we will implement 'The elbow method' on the Iris dataset. # The elbow method allows us to pick the optimum amount of clusters for classification.</p> # In[20]: #Finding the optimum number of clusters for k-means classification from sklearn.cluster import KMeans wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) kmeans.fit(x) wcss.append(kmeans.inertia_) #Plotting the results onto a line graph, allowing us to observe 'The elbow' plt.plot(range(1, 11), wcss) plt.title('The elbow method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') #within cluster sum of squares plt.annotate('Optimum k value', xy = (3,100), xytext = (3.6, 250), arrowprops = dict(facecolor='black', shrink = 0.1), horizontalalignment='center', verticalalignment='top') plt.show() # <p> The optimum number of clusters is where the elbow occurs. This is when the within cluster sum of squares (WCSS) doesn't decrease significantly with every iteration. We see that the <b>optimum number of clusters is 3</b> and we can now give this as an input to our kmeans algorithm </p>
true
4d73b7bfe97a3fd817181536eb6a97e8fa9a0cf1
licheeee/PythonProject
/is_odd.py
219
4.25
4
# -*- coding: UTF-8 -*- # 判断数字是否是奇数 num = int(input("Please input a number :")) if (num % 2) == 0: print("{0} is an even number".format(num)) else: print("{0} is an odd number".format(num))
false
5e6b40a9df523d901c02b7f9323e96b8cc05ea01
chinmaybhoir/project-euler
/euler4.py
707
4.25
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ import time start_t = time.time() def is_palindrome(num): num_string = str(num) if num_string == num_string[::-1]: return True return False def get_palindrome(): largest = 0 for i in range(101,1000): for j in range(101, 1000): if is_palindrome(i*j) and i*j > largest: largest = i * j return largest if __name__ == '__main__': answer = get_palindrome() print("ans:", answer, " time:", time.time() - start_t)
true
662ecea8a000da7eacebedf9381f7c06ec627e90
DipeshBuffon/python_assignment
/DT16.py
269
4.125
4
#Write a Python program to sum all the items in a list. list=[] n=int(input("Enter length of list:- ")) for i in range(n): a=int(input("Enter numeric value for list:- ")) list.append(a) sum=0 for i in range(len(list)): sum+=list[i] print(sum)
true
1ddd0ef3ae72a9de31920d1413b2795aee5b18b2
DipeshBuffon/python_assignment
/DT18.py
229
4.34375
4
#Write a Python program to largest item in a list. n=int(input("Enter length of list:- ")) list=[] for i in range(n): a=int(input("Enter numeric value for list:- ")) list.append(a) list.sort() print(list[-1])
true
eff9439139901b66bb066e932c4ff9326662c111
DipeshBuffon/python_assignment
/f6.py
280
4.15625
4
#WAP in python function to check whether the given number is in range or not. n=int(input("Enter a number:- ")) r=int(input("enter the end of range:- ")) def check(n,r): if n in range(r+1): print('found') else: print("not found") check(n,r)
true
06e581477069f64f865aa01ddf93c433761b94c3
deepakdas777/anandology
/functional_programming/tree_reverse.py
255
4.125
4
#Write a function tree_reverse to reverse elements of a nested-list recursively. def tree_reverse(lis): lis.reverse() for i in lis: if isinstance(i,list): tree_reverse(i) return lis print tree_reverse([[1, 2], [3, [4, 5]], 6])
true
162c03918391f131d1f4c8741094da50238f0e9a
anudeepthota/Python
/checkingIn.py
206
4.1875
4
parrot = "Norwegian Blue" letter = input("Enter a character:") if(letter in parrot): print("{} is present in {}".format(letter,parrot)) else: print("{} is not present in {}".format(letter,parrot))
true
75c93b591147c4f1cf0e2788a46a0e4cf700d14d
anudeepthota/Python
/instance_start.py
1,109
4.46875
4
# Python Object Oriented Programming by Joe Marini course example # Using instance methods and attributes class Book: # the "init" function is called when the instance is # created and ready to be initialized def __init__(self, title, author, pages, price): self.title = title self.author = author self.pages = pages self.price = price self.__secret = "This is a secret value" # TODO: create instance methods def getprice(self): if hasattr(self, "_discount"): return self.price - (self.price * self._discount) else: return self.price def setdiscount(self, amount): self._discount = amount # TODO: create some book instances b1 = Book("War and Peace", "Anudeep Thota", 1000, 100) b2 = Book("The Catcher in the Rye", "Suresh Thota", 799, 200) # TODO: print the price of book1 print(b1.getprice()) # TODO: try setting the discount print(b2.getprice()) b2.setdiscount(0.10) print(b2.getprice()) # TODO: properties with double underscores are hidden by the interpreter print(b2._Book__secret)
true
e1a7cde7429b806310907f77fd32b95af3b466a8
anudeepthota/Python
/holidaychallenge.py
235
4.21875
4
name = input("Please enter your name: ") age = int(input("Please enter your age: ")) if age > 18 and age < 31: print("Hi {}, Welcome to the Holiday!!".format(name)) else: print("Hi {}, Sorry you are not eligible".format(name))
true
ee1c1f40b7e3cf42cfc8a0851d834d8fd9cc1cdc
edubu2/OOP-Tutorials
/2_oop_class_variables.py
1,566
4.4375
4
# Object-Oriented Programming tutorials from Corey Schafer's OOP YouTube Series. class Employee: num_of_emps = 0 # will increment each time an employee is added raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@' + 'company.com' Employee.num_of_emps += 1 # increment num employees each time an instance is created def fullname(self): """ Prints the full name of an Employee instance. """ return "{} {}".format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amount) # What is a class variable? # Something that's the same across all instances (example: raise amount) # See apply_raise(self) function # when we reference raise_amount in this function, we could use self.raise_amount OR Employee.raise_amount # there is a difference! # self.raise_amount: Will apply the raise_amount variable from this INSTANCE (so if that employee has a different raise_amount than the class, it will be used) # Employee.raise_amount: Regardless of the instance's raise_amount, the class attribute raise_amount value will be used emp_1 = Employee('Elliot', 'Wilens', 100000) emp_2 = Employee('Megan', 'Harpell', 125000) print(emp_1.raise_amount) print(emp_1.pay) emp_1.apply_raise() print(emp_1.pay) emp_1.raise_amount = 1.10 print(emp_1.raise_amount) print(emp_2.raise_amount) print(Employee.num_of_emps)
true
e5a3e18b2c9d28d763d47f72157bbe0a7f977f1d
ciriusblb/python
/bucles.py
2,346
4.15625
4
# for i in ["pildoras", "informaticas", 3]: # print("Hola", end= " ") #para quitar el salto de linea # -----------------ejercicio------------------- # email = False # for i in "ciriusblb@gmail.com": #iterar i tantas veces caracteres tenga el string # if i == "@": # email = True # if email: # print("email corecto") # else: # print("enamil incorrrecto") # ----------for------- # for i in range(5): # print(i) # for i in range(5, 10): # de donde a donde # print(f"numero {i}") # for i in range(5, 40, 5): # de donde a donde y de cuando en cuanto # print(f"numero {i}") # ----------while------------------ # i = 1 # while i <= 10: # print("Ejecucion "+ str(i)) # i= i+1 # print("termino") # ----------------------ejercicio------------------------------ # edad = int(input("ingrese edad: ")) # while edad<5 or edad>100: # print("edad incorrecta") # edad = int(input("introduce edad de nuevo: ")) # print("bye " + str(edad)) # ----------------------ejercicio------------------------------ # import math # print("programa raiz cuadrada") # numero = int(input("ingrese numero: ")) # intentos = 1 # while numero < 0: # print("no hay raiz de numero negativo") # if intentos == 3: # print("no sabes ni que son numeros negativos, largate") # break # numero = int(input("vuelva a ingresar numero: ")) # if numero < 0: # intentos = intentos + 1 # if intentos < 3: # solucion = math.sqrt(numero) # print("la raiz de: "+ str(numero) + " es: " + str(solucion)) #--------------continue, pass, else--------------- # for i in "python": # if i == "h": # continue #pasa a la siguiente iteracion ignorando el codigo de abajo # print("letra: " +i) # ----------ejemplo------------------ # c = 0 # for i in "ciro yupanqui": # if i == " ": # continue #pasa a la siguiente iteracion ignorando el codigo de abajo # c+=1 # print("tamaño: "+ str(c)) # ------------pass--------- # class miclase: # pass #para implementar mas tarde # # el pass sirve par ignorar codigo #--------------else------------ # email = input("email: ") # for i in email: # if i == "@": # arroba = True # break # else: # else del for, en caso de que el for termine sin saltos(break) # arroba = False # print(arroba)
false
6f816aa39a46097c3bcbad42f6a262e12ab5aba7
bana513/advent-of-code-2020
/day2/part1.py
1,145
4.125
4
""" Task: Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times. In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies. How many passwords are valid according to their policies? """ def password_ok(lower, upper, char, password): count = 0 for c in password: if c == char: count += 1 return lower <= count <= upper if __name__ == "__main__": count = 0 with open("day2/input.txt", 'r') as f: while line := f.readline(): bounds, char, password = line.split(' ') char = char.strip(':') lower, upper = [int(b) for b in bounds.split('-')] count += password_ok(lower, upper, char, password) print(count)
true
c04bb30ce006e2b0f4fc816daaf6c664aa8fb147
hasrakib/Python-Practice-Projects
/Basic/days-between.py
293
4.375
4
# Write a Python program to calculate number of days between two dates. # Sample dates : (2014, 7, 2), (2014, 7, 11) # Expected output : 9 days from datetime import date first_date = date(2014, 7, 2) last_date = date(2014, 7, 11) difference = last_date - first_date print(difference.days)
true
220827b7f76f736120e24d9855bc3d1a1b66b0f5
friver6/Programming-Projects
/Python Exercises/ex16-DriveAge.py
314
4.3125
4
#Program to determine if user can drive according to his or her age. drivAge = 16 userAge = int(input("What is your age? ")) if userAge <= 0: print("Please enter a valid age.") elif userAge > 0 and userAge < drivAge: print("You are not old enough to legally drive.") else: print("You are allowed to drive.")
true
c1918e556d13f357889d5f2196abfbd9811a758c
friver6/Programming-Projects
/Python Exercises/ex28-AddingNums.py
263
4.125
4
#Prompts for five numbers and computes the total. total = 0 numInput = 0 usrInput = "" for i in range(0,5): usrInput = input("Enter a number: ") if usrInput.isdecimal(): numInput = int(usrInput) total += numInput print("The total is {}.".format(total))
true
cdea4e4f0c0489edba630b95b4467efd84ae8a1f
friver6/Programming-Projects
/Python Exercises/ex18-TempConv.py
678
4.34375
4
#Converts between Fahrenheit and Celsius and vice-versa. print("Press C to convert from Fahrenheit to Celsius.\nPress F to convert from Celsius to Fahrenheit.\n") usrChoice = input("Your choice: ") if usrChoice == "C" or usrChoice == "c": usrTemp = float(input("Please enter the temperature in Fahrenheit: ")) convTemp = (usrTemp-32) * (5/9) print("The temperature in Celsius is {:.2f}.".format(convTemp)) elif usrChoice == "F" or usrChoice == "f": usrTemp = float(input("Please enter the temperature in Celsius: ")) convTemp = (usrTemp * (9/5)) + 32 print("The temperature in Fahrenheit is {:.2f}.".format(convTemp)) else: print("Invalid input.") raise SystemExit
true
206bf39105de0fa5388ec4635523c0e1378becf4
rishavsharma47/ENC2020P1
/Session10G.py
2,477
4.21875
4
""" OOPS : Object Oriented Programming Structure How we design Software Its a Methodology 1. Object 2. Class Real World Object : Anything which exists in Reality Class : Represents how an object will look like Drawing of an Object Principle of OOPS 1. Think of an Object 2. Create its Class 3. From Class Create Real Object Computer Science Object : Multi Value Container Homo/Hetro Data in Object is stored as Dictionary where keys are known as attributes which will hold values as data Class : Represent how an object will look like What it should contain as data Provide certain functionalities to process the data as well in Object Principle of OOPS 1. Think of an Object We need to analyse detailed requirements from client regarding his/her software needs Identify all those terms which will have lot of data associated with it that term -> Object and data associated -> attributes Requirement by John: We wish to create a food delivery app. Customer should register. We will display him all the restaurants. For Every Restaurant we will display menu. Customer will select Dishes and add them to Cart. Customer will process Order by paying online/offline Think of an Object [Customer and Restaurant] Customer : name, phone, email, gender, address Restaurant : name, phone, email, address, rating, pricePerPerson, openingHours, category 2. Create its Class 3. From Class Create Real Object """ # 2. Create its Class class Customer: pass # 3. From Class Create Real Object # Object Construction Statement cRef = Customer() print(">> cRef is:", cRef) print(">> cRef HashCode is:", hex(id(cRef))) print(">> Type of cRef:", type(cRef)) # What is in Object, print it as Dictionary print(">> cRef Dictionary", cRef.__dict__) # Add Data in Object cRef.name = "John Watson" cRef.phone = "+91 99999 88888" cRef.email = "john@example.com" cRef.address = "Redwood Shores" cRef.gender = "Male" # Update Data In Object cRef.phone = "+91 98765 67890" # Delete Data In Object del cRef.address # Object Deletion # del cRef print(">> cRef Dictionary now is:", cRef.__dict__)
true
e9ac0a9133baf8a519d7a00d7ae4955a5d48ef8d
rishavsharma47/ENC2020P1
/Session20C.py
1,025
4.15625
4
# Function with Input to Reference of Function def hello(fun): print(">> Hello...") fun() def bye(): print(">> Bye...") def show(num=10): print(">> showing", num) # Passing Function as Argument hello(fun=bye) print("~~~~~~~~~") hello(fun=show) # Factory Design Pattern # Create with help of Concept called Polymorphism (Run Time) def loginWithFaceBook(): print(">> Login With FaceBook") def loginWithGoogle(): print(">> Login With Google") def loginWithGitHub(): print(">> Login With GitHub") def login(type): type() print("-----------------------") print("|1 Login With Facebook|") print("-----------------------") print("|2 Login With Google |") print("-----------------------") print("|3 Login With GitHub |") print("-----------------------") choice = int(input("Select Your Login Type")) if choice == 1: login(loginWithFaceBook) elif choice == 2: login(loginWithGoogle) elif choice == 3: login(loginWithGitHub) else: print(">> Please Select Valid Choice")
false
98a87be0f2fe544c1db9d42800763be8a086562a
BurnsCommaLucas/Sorts
/python/bubble.py
618
4.125
4
#!/usr/bin/env python """bubble.py: Sorts an array of integers using bubble sort""" __author__ = "Lucas Burns" __version__ = "2017-9-28" import process def sort(items): swapped = True while (swapped): swapped = False for i in range(0, len(items) - 1): process.comparisons += 1 if items[i] > items[i + 1]: swapped = True process.swap(i, i + 1, items) process.accesses += 3 a = process.populate() print("Original array: " + str(a)) process.initCounters() sort(a) print("Sorted array: " + str(a)) print(str(process.comparisons) + " comparisons " + str(process.accesses) + " array accesses")
true