blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
334e867ca3c975cb7356eb997151a8d27b1332cd
ugaliguy/PE-Sprint
/problem-6.py
308
3.703125
4
# Python 3 # I feel like the accepted answer is the opposite of what was asked for. n = 100 def sum_of_squares(n): result = n*(n+1)*(2*n+1)/6 return result def square_of_sum(n): result = (n*(n+1)/2)**2 return result answer = sum_of_squares(n) - square_of_sum(n) print(answer)
e928ecc213fe399652114e6e3bfe85eb16a37e11
akjalbani/Test_Python
/Misc/PythonFilling/Pdf/reading_pdf_file.py
792
3.734375
4
# PyPDF2 is the python poweful library to read and write pdf file, you have to install PyPDF2 library with pip command # pip install PyPDF2 # pip install os # author: AA Jalbani # version 1.0 # Tested on Python IDLE # ################################################################################################ import PyPDF2 import os os.chdir('C:\\Users\\xyz\\Desktop\\mypdf') # change dir ( chdir) and provide relative path to the target folder pdfFile = open('filename.pdf','rb') # read binary mode reader = PyPDF2.PdfFileReader(pdfFile) pages = reader.numPages print("No .of pages = ", pages) page = reader.getPage(2) # readeing page numbers 3 -> arg 0 represents the page 1, arg1 represents page 2 and so on text= page.extractText() print("Text from Pdf file") print("^"*30) print(text)
49d52a297ac3ed347b682a7534fce20ed0a7d79b
ansonmiu0214/algorithms
/2019-03-24_Fruit-into-Baskets/solution.py
1,158
3.8125
4
#!/bin/python3 def totalFruit(tree): ''' DP approach of finding longest subarray with 2 elements ''' n = len(tree) last = n - 1 # accumulate most optimal result prevType = tree[last] # tree type of previous countOneType = 1 # longest subarray, from prev, with 1 unique countTwoType = 1 # longest subarray, from prev, with 2 unique secondType = prevType # 2nd tree type for longest subarray with 2 unique acc = countTwoType # max accumulator of longest subarray with 2 unique for i in range(n-2, -1, -1): currType = tree[i] newCountOneType = 1 if currType != prevType else (countOneType + 1) newCountTwoType = (countOneType + 1) if (currType != prevType and currType != secondType) else (countTwoType + 1) newSecondType = prevType if currType != prevType else secondType # update accumulators prevType = currType countOneType = newCountOneType countTwoType = newCountTwoType secondType = newSecondType acc = max(acc, countTwoType) return acc if __name__ == "__main__": print("Enter space-separated trees: ", end="") tree = list(map(int, input().strip().split())) res = totalFruit(tree) print(res)
763050d8f94b9409bd29b0aa821787ab0c1e103c
lianke123321/leetcode_sol
/129_sum_root_to_leaf_numbers/sol.py
1,662
3.8125
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ result = [] if not root: return 0 stackOfNode = [root] stackOfString = [root.val] while stackOfNode: currNode = stackOfNode.pop() currString = stackOfString.pop() if currNode.left: stackOfNode.append(currNode.left) stackOfString.append(currString * 10 + currNode.left.val) if currNode.right: stackOfNode.append(currNode.right) stackOfString.append(currString * 10 + currNode.right.val) if not currNode.left and not currNode.right: result.append(currString) return sum(result) def sumNumbers_self(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 node_stack = [root] num_stack = [root.val] result = 0 while node_stack: node = node_stack.pop() num = num_stack.pop() if not node.left and not node.right: result += num if node.left: node_stack.append(node.left) num_stack.append(num * 10 + node.left.val) if node.right: node_stack.append(node.right) num_stack.append(num * 10 + node.right.val) return result
10c62ea3e833924b47a5cfb365f98fc2df96de45
jonyachen/TestingPython
/bubblesort-forfor.py
347
4.125
4
#Bubble sort with for loop then for loop myList = [5, 2, 1, 4, 3] def bubblesort(list): for i in range(0, len(list)): for j in range(0, len(list)-1): if list[j] > list[j + 1]: temp = list[j + 1] list[j + 1] = list[j] list[j] = temp return list print bubblesort(myList)
17e3d52fa8b0ba4c4e03a4fe6a9a5fbc1b421893
Fabaladibbasey/MITX_6.00.1
/ps6/sortingAlgorithms
2,231
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 18 18:01:20 2021 @author: suspect-0 """ # def bubble_sort(L): # swap = False # while not swap: # swap = True # for J in range(1, len(L)): # if L[J - 1] > L[J]: # swap = False # # do the swaping # L[J - 1], L[J] = L[J], L[J - 1] # return L # def selection_sort(L): # suffixSt = 0 # while suffixSt != len(L): # for i in range(suffixSt, len(L)): # if L[i] < L[suffixSt]: # print(L[i], L[suffixSt]) # L[suffixSt], L[i] = L[i], L[suffixSt] # print(L) # suffixSt += 1 # return L # def selSort(L): # for i in range(len(L) - 1): # minIndx = i # minVal = L[i] # j = i+1 # while j < len(L): # if minVal > L[j]: # minIndx = j # minVal = L[j] # j += 1 # if minIndx != i: # temp = L[i] # L[i] = L[minIndx] # L[minIndx] = temp # And here is a suggested alternative: # def newSort(L): # for i in range(len(L) - 1): # j=i+1 # while j < len(L): # if L[i] > L[j]: # temp = L[i] # L[i] = L[j] # L[j] = temp # j += 1 def merge_sort(L): if len(L) < 2: return L[:] else: middle = len(L)//2 left = merge_sort(L[:middle]) right = merge_sort(L[middle:]) print(left, ' ', right) m = merge(left, right) print('this is m', m) return m def merge(left, right): result = [] i,j = 0, 0 while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 while (i < len(left)): result.append(left[i]) i += 1 while (j < len(right)): result.append(right[j]) j += 1 return result l1 = [3, 7, 2, 1] l2 = [4, 8, 2, 9] l3 = l1 + l2 print(l3) # print(merge_sort(l1)) print(merge_sort(l3))
e07a002b20c9e32761582d015e6c2412fdd2672a
priyanshu3666/Iedaas-python-bootcamp
/day4/Triangle.py
555
3.953125
4
class Triangle(object): def __init__(self,angle1,angle2,angle3): self.angle1=angle1 self.angle2=angle2 self.angle3=angle3 number_of_sides=3 def check_angles(self): if self.angle1+self.angle2+self.angle3 ==180: return True else: return False class Equilateral(Triangle): angle = 60 def __init__(self): self.angle1 = self.angle2 = self.angle3 = self.angle my_triangle=Triangle(90,30,60) print(my_triangle.number_of_sides) print(my_triangle.check_angles())
f0c73caf667c851b79b7bed79bc111702529f72e
Xenomorphims/Python3-examples
/new folder/name.py
219
4.03125
4
ages = { 'Innocent' : 17, 'Chris' : 16, 'Sam' :18, 'Emmanuel' :17, } if 'Innocent' in ages: age = ages['Innocent'] else: age = 'Unknown' print ('Innocent is %s years old' % age)
71b3575757e4640d8caefe67b5e5a4df60455a33
mangel2500/Programacion
/Práctica 7 Python/Exer-4.py
592
4.40625
4
'''MIGUEL ANGEL MENA ALCALDE - PRACTICA 7 EJERCICIO 4 Escribe un programa que pida una frase, y le pase como parmetro a una funcin dicha frase. La funcin debe sustituir todos los espacios en blanco de una frase por un asterisco, y devolver el resultado para que el programa principal la imprima por pantalla. ''' def cadena(): frase=raw_input("Escribe una frase: ") valor= ' ' for i in range(len(frase)): if frase[i] == ' ': valor+='*' else: valor+=frase[i] return valor print cadena()
ee0745c533b925869fe372a80a67d19a7194b851
shankar7791/MI-10-DevOps
/Personel/Nilesh/python/Practice/3March/program2.py
227
4.34375
4
#Python program create function to check if a string is palindrome or not def palindrome(s): if s == s[::-1]: print("palindrome") else: print("not a palindrome") palindrome("aba") palindrome("cba")
bef56a57556a3b101cb6bc5b7e27ec45e68fd594
AnomDevgun/DataStructuresandAlgos
/Python/Nemo.py
274
3.71875
4
import time words_list = ['nemo']*1000 def findNemo(words_list): start = time.time() for i in range (len(words_list)): if(words_list[i]=='nemo'): print("found Nemo") end = time.time() print('Time taken is '+str(end-start)+' seconds') findNemo(words_list)
0008bb32f150aec654ae288a5cc0e1c4de77e60d
Stanleyli1984/myscratch
/lc/scrapth2.py
433
3.6875
4
class a(object): def __init__(self): a.c = 0 a.x = 1 A = a(c = 3, x = 1) exit(0) def generate_power_func(n): print "id(n): %X" % id(n) def nth_power(x): return x**n print "id(nth_power): %X" % id(nth_power) return nth_power def generate_power_func1(n): print "id(n): %X" % id(n) r4 = generate_power_func(4) r41 = generate_power_func(4) r42 = generate_power_func(5) print r4(3)
c6eaa6d90b9fa40491d04d3e413d9f2c04774d5b
ehoney12/comp110-21f-workspace
/exercises/ex05/utils_test.py
1,916
3.8125
4
"""Unit tests for list utility functions.""" # TODO: Uncomment the below line when ready to write unit tests from exercises.ex05.utils import only_evens, sub, concat __author__ = "730240245" def test_only_evens_empty() -> None: """Only_evens function edge case testing with empty list.""" x: list[int] = [] assert only_evens(x) == [] def test_only_evens_all() -> None: """Only_evens function use case testing all even numbers.""" x: list[int] = [2, 4, 6, 8, 10] assert only_evens(x) == [2, 4, 6, 8, 10] def test_only_evens_none() -> None: """Only_evens function use case testing with all odd numbers.""" x: list[int] = [1, 3, 5, 7, 9] assert only_evens(x) == [] def test_sub_empty() -> None: """Sub function edge case testing with empty list.""" p: list[int] = [] a: int = 0 b: int = 3 assert sub(p, a, b) == [] def test_sub_interior_testing() -> None: """Sub function use case testing.""" p: list[int] = [1, 7, 9, 10, 12, 14] a: int = 2 b: int = 4 assert sub(p, a, b) == [9, 10] def test_sub_a_less_than_zero() -> None: """Sub function use case testing.""" p: list[int] = [0, 3, 6, 12, 15, 19, 22] a: int = -2 b: int = 6 assert sub(p, a, b) == [0, 3, 6, 12, 15, 19] def test_concat_empty_one_list() -> None: """Concat function edge case testing with empty list.""" one: list[int] = [] two: list[int] = [1, 2] assert concat(one, two) == [1, 2] def test_concat_len_two() -> None: """Concat function use case testing longer length of list two.""" one: list[int] = [3, 5, 7] two: list[int] = [4, 5, 7, 9] assert concat(one, two) == [3, 5, 7, 4, 5, 7, 9] def test_concat_len_one() -> None: """Concant function use case testing longer length of list one.""" one: list[int] = [1, 2, 3, 4] two: list[int] = [5] assert concat(one, two) == [1, 2, 3, 4, 5]
6b29c707d1cbcdb336180b877946e713d91baf4f
wann31828/leetcode_solve
/python_solution/400.py
1,024
3.953125
4
''' 400. Nth Digit Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... Note: n is positive and will fit within the range of a 32-bit signed integer (n < 231). Input: 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. ''' #total digits : 1*9 +2*90 + 3*900 + 4*9000 .... def findNthDigit(n): digit =1 while(n > 0): n -= digit* pow(10,digit-1) * 9 digit += 1 digit -= 1 n += digit * 9*pow(10,digit-1) if digit == 1: target , location = int(n/digit), n%digit else : location = n%digit if n<= digit: target = pow(10,digit-1) else: if(location == 0): target = pow(10,digit-1) + int(n/digit) -1 else: target = pow(10,digit-1) + int(n/digit) if(location == 0): return int(str(target)[-1]) else: return int(str(target)[location-1])
3a3c0b9b574baefae606a6d76432e551695cb060
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/904.py
469
3.546875
4
def is_tidy(n): s = str(n) if len(s) == 1: return True for i in range(1, len(s)): if int(s[i]) < int(s[i-1]): return False return True T = int(input()) for c in range(T): N = int(input()) answer = "" while not is_tidy(N): S = list(str(N)) S[-1] = "9" answer = answer + S[-1] N = int("".join(S[:-1])) N -=1 answer = str(N) + answer answer = int(answer) print("Case #{}: {}".format(c+1, answer))
199d49f135b35c57f723432c406b7367cf7b0328
corriander/finances
/finances/tests/test_salary.py
2,193
4.15625
4
import unittest from finances.salary import Salary class TestSalary(unittest.TestCase): """Test the Salary class. The class possesses the following attributes: - Pretax salary - Income attributes (annual, monthly, weekly) - Income tax property - National insurance property - Student loan property All these need testing and verifying for sample salaries. I'm not about to end up above the basic tax rate so these tests should be valid for salaries up to ~41,000 GBP/yr """ def test_nontaxable_salary(self): salary = Salary(9600) self.assertEqual(salary.pretax.monthly, 800.0) self.assertEqual(salary.income_tax, 0) self.assertEqual(salary.student_loan, 0) self.assertAlmostEqual(salary.nat_ins, 197.28, 2) def test_basic_rate_no_loan(self): """Test a basic tax band salary with no student loan.""" salary = Salary(19200) self.assertEqual(salary.pretax.monthly, 1600.0) self.assertEqual(salary.income_tax, 1840.0) self.assertEqual(salary.student_loan, 0.0) self.assertAlmostEqual(salary.nat_ins, 1349.28, 2) self.assertAlmostEqual(salary.annual, 16010.72, 2) def test_basic_rate_below_sl_threshold(self): """Test a basic tax band salary with loan, under threshold.""" salary = Salary(15000, student_loan=True) # We've tested the pretax above. self.assertEqual(salary.income_tax, 1000.0) self.assertEqual(salary.student_loan, 0) self.assertAlmostEqual(salary.nat_ins, 845.28, 2) self.assertAlmostEqual(salary.annual, 13154.72, 2) def test_basic_rate_with_loan(self): salary = Salary(19200, student_loan=True) # We've tested the pretax above. self.assertEqual(salary.income_tax, 1840.0) self.assertAlmostEqual(salary.student_loan, 206.1, 1) self.assertAlmostEqual(salary.nat_ins, 1349.28, 2) self.assertAlmostEqual(salary.annual, 15804.62, 2) def test_high_basic_rate(self): salary = Salary(36000, student_loan=True) # We've tested the pretax above. self.assertEqual(salary.income_tax, 5200.0) self.assertAlmostEqual(salary.student_loan, 1718.1, 1) self.assertAlmostEqual(salary.nat_ins, 3365.28, 2) self.assertAlmostEqual(salary.annual, 25716.62, 2) if __name__ == '__main__': unittest.main()
066781a5674af6d2732782a1f5b3ca4cbc6f088d
wuyuku/liaoxuefeng
/samples/Loop.py
216
3.921875
4
''' sum = 0 # ()是tuple,不可变;[]是list,可变 for x in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10): sum = sum + x print (sum) ''' #print (list(range(101))) sum = 0 for x in range(101): sum = sum + x print (sum)
425f323a5cc49c57d251ee78d9229609ea8a3a87
debolina-ca/my-projects
/Python Codes 2/find and report (print) number of w, o and use of word code.py
279
3.734375
4
# [ ] find and report (print) number of w's, o's + use of word "code" work_tip = "Good code is commented code" w = work_tip.count("w") o = work_tip.count("o") code = work_tip.count("code") print("No. of 'w's: ", w) print("No. of 'o's: ", o) print("No. of 'code's: ", code)
5f6d6514c474a47052d294c857b7475de97fe426
jominkmathew/Programming-lab-Python-
/Course Outcomes/Course Outcome 1/2b.py
81
3.875
4
a=int(input("enter the number :")) list=[x**2 for x in range(1,a+1)] print(list)
e2876fd7789ba8b81fe1834d7544880213d6b9d2
vitorscassiano/SimpleDesignPatterns
/interface.py
284
3.703125
4
from abc import ABC, abstractmethod from typing import List class IHello(ABC): @abstractmethod def hello(self, word: str, bla: List): pass class Hello(IHello): def hello(self, word): print(f"Hello {word}!") pass # Main Hello().hello("World")
353f6daff8e97ff350a2eb47b1f9bd14ca31b41f
nkr4m/Python_uploads
/Binary_Trees/Preorder_BT.py
642
3.625
4
#Pre order BT class BTnode: def __init__(self,data): self.data = data self.left = None self.right = None def take_input(): rootData = int(input()) if(rootData == -1): return root = BTnode(rootData) root.left = take_input() root.right = take_input() return root def printBT(root): if(root) is None: return print(root.data,end=" ") if(root.left) is not None: print(root.left.data,end=" ") if(root.right) is not None: print(root.right.data,end=" ") print() printBT(root.left) printBT(root.right) root = take_input() printBT(root)
c621f3a8adc3d65ef48f29c8e126213e7d0d9e52
Auskas/Solutions-to-Project-Euler
/p086_cuboid_route.py
2,360
4.0625
4
# # Solution to Project Euler Problem 86 Cuboid route. # Copyright (c) Auskas. All rights reserved. # # https://github.com/Auskas/Solutions-to-Project-Euler # # The first step to solve the problem is to unfold the pictured cuboid. The shortest path is the hypotenuse of the right-angled triangle. # One of the sides is the length of the cuboid, the other side is the sum of the width and the heigth. # The algorithm is simple: we calculates the number of solutions for each M starting with 3. Sums up the number of solutions. # In order to find the number of solutions for each M, we check if there is the number N to form a right-angled triangle with all integer side lengths. import time def number_of_cuboids(M=2,counter=0,target=1000000): # Here is a little trick: in order to get rid of finding the square root in the Pythagorean theorem # the squares of integers are precalculated. At first, I chose the upper limit 10000. # However, as soon as I got the answer, the limit was chosen close to the answer multiplied by 2. # (We need to take into account the doubled limit because N (the width plus the height) can take values up to 2 * M) squares = set([i ** 2 for i in range(2, 4000)]) while counter < target: M += 1 for N in range(3, 2 * M + 1): if M ** 2 + N ** 2 in squares: # If the width plus the height of a cuboid is less than the length, there are N // 2 solutions. # For instance, if the length (M) equals to 8 and the width plus the height (N) equals to 6, there are 3 solutions: # (8,1,5), (8,2,6), (8,3,3). We cannot include (8,5,1), (8,2,6) because those are rotations of the cuboids. if N <= M: counter += N // 2 # If the sum of height and width (N) is bigger than the length (M), the height can take the values between # 1 and M inclusive. For instance, if M = 6, N = 8, there are 3 solutions (6,6,2), (6,5,3), (6,4,4). else: counter += 1 + (M - (N + 1) // 2) return M st_time = time.perf_counter() print("The value of M when the number of solutions first exceed one million equals to", number_of_cuboids()) print("The execution time is {0} seconds.".format(time.perf_counter() - st_time))
890d78c8d985f090429ababed465098f9377a8da
eclipse-ib/Software-University-Professional-Advanced-Module
/September 2020/02-Tuples-and-Sets/Exercises/07-Battle-of-Names.py
679
3.953125
4
n = int(input()) even_names = set() odd_names = set() for i in range(1, n+1): name = input() current_ascii_sum = 0 for char in name: current_ascii_sum += ord(char) current_ascii_sum = current_ascii_sum // i if current_ascii_sum % 2 == 0: even_names.add(current_ascii_sum) else: odd_names.add(current_ascii_sum) result = "" if sum(even_names) == sum(odd_names): result = odd_names.union(even_names) elif sum(even_names) < sum(odd_names): result = odd_names.difference(even_names) elif sum(even_names) > sum(odd_names): result = odd_names.symmetric_difference(even_names) print(", ".join(str(_) for _ in result))
1ecb6c49e950776a26071df0e27d9e265a1732be
choushruti88/Python-Programmes
/Loops.py
404
4.25
4
nums = [1,2,3,4,5,6] for num in nums: print(num) #Search a certain number is our list for num in nums: if num == 3: print('Found!') break print(num) for num in nums: if num == 3: print('Found!') continue print(num) for num in nums: for letter in 'abc': print(num, letter) #if u want to print a string put it in ''
b363ae24cf538a2cc9508b4515aa767d8affed71
mikaelbeat/Modern_Python3_Bootcamp
/Modern_Python3_Bootcamp/Lambdas/Introduction.py
300
4.25
4
# Runs lambda for each value in the iterable and returns a map object print("\n*** Basic function ***\n") def calculate(value): return value + value print(calculate(5)) print("\n*** Lambda function ***\n") calculate2 = lambda value: value + value print(calculate2(5))
75a7f26426b3d87ade543156c52bc18465ca302a
malikdipti/Python_program
/collection/list/builtinfunction.py
357
3.703125
4
l1=[6,8,23,24,64,21,14] print("total:",sum(l1)) print("maximum:",max(l1)) print("minimum:",min(l1)) print("length:",len(l1)) print("-----------------------------------------") names=["razz","kumar","lucy","john","ram mohan"] #print(sum(names)) TypeError: unsupported operand type(s) for +: 'int' and 'str' print(max(names)) print(min(names)) print(len(names))
67cd8aa0bdb149110f1ab082485ad302522345bd
skybrim/practice_leetcode_python
/everyday/973.py
1,286
4.3125
4
""" 973. 最接近原点的 K 个点 我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。 (这里,平面上两点之间的距离是欧几里德距离。) 你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。 示例 1: 输入:points = [[1,3],[-2,2]], K = 1 输出:[[-2,2]] 解释: (1, 3) 和原点之间的距离为 sqrt(10), (-2, 2) 和原点之间的距离为 sqrt(8), 由于 sqrt(8) < sqrt(10),(-2, 2) 离原点更近。 我们只需要距离原点最近的 K = 1 个点,所以答案就是 [[-2,2]]。 示例 2: 输入:points = [[3,3],[5,-1],[-2,4]], K = 2 输出:[[3,3],[-2,4]] (答案 [[-2,4],[3,3]] 也会被接受。) 提示: 1 <= K <= points.length <= 10000 -10000 < points[i][0] < 10000 -10000 < points[i][1] < 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/k-closest-points-to-origin 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ import math def k_closest(points, K): res = points[:] res.sort(key=lambda x: (x[0] ** 2 + x[1] ** 2)) return res[:K] if __name__ == "__main__": print(k_closest([[1, 3], [-2, 2]], 1))
d2d9b9cee7fe623ada34c4edbb633092996915c6
wilfredarin/geeksforgeeks
/Dynamic Programming/word-break.py
711
3.5625
4
#https://practice.geeksforgeeks.org/problems/word-break/0 def wordBreak(dic,arr,n): dp = [[0 for i in range(n)] for j in range(n)] for i in range(n): dp[i][i]= 1 if arr[i] in dic else 0 for l in range(1,n+1): for s in range(n-l): if arr[s:s+l+1] in dic: dp[s][s+l]=1 else: for brk in range(s,s+l): if dp[s][brk] and dp[brk+1][s+l]: dp[s][s+l]=1 break return dp[0][-1] test = int(input()) for i in range(test): q = int(input()) dic = list(input().split()) b = input() print(wordBreak(dic,b,len(b)))
ab1570e50cd2a34a404d1cf77255011a08dd3ff4
vbetts/exercism.io
/python/isogram/isogram.py
241
3.9375
4
def is_isogram(string): string = string.replace(' ', '').replace('-', '').lower() letterSet = set() for s in string: if s in letterSet: return False else: letterSet.add(s) return True
7b1289403d3e867bf70e76ad4d572d64a085f56b
rogerthat39/advent-of-code-2019
/Day 5.py
3,662
3.890625
4
#Day 5 - based on day 2 "Intcode" computer def getIntsList(): f = open("puzzle_input/day5.txt", "r") ints = [int(x.strip()) for x in f.readline().split(',')] f.close() return ints def intCode(ints): n = 0 i = 0 while(n != 99): n = ints[i] modes = determineModes(str(n)) #change the opcode to the last two digits if the mode was supplied if(modes != ['0','0','0']): n = int(str(n)[-2:]) #opcode 1 - add two digits and store in position given if(n == 1): a = getValue(i+1, modes[0]) b = getValue(i+2, modes[1]) ints[ints[i+3]] = a + b i += 4 #go to next instruction #opcode 2 - multiply two digits and store in position given elif(n == 2): a = getValue(i+1, modes[0]) b = getValue(i+2, modes[1]) ints[ints[i+3]] = a * b i += 4 #go to next instruction #opcode 3 - store input from user in position given elif(n == 3): ints[ints[i+1]] = int(input("Enter an input: ")) i += 2 #go to next instruction - this instruction is 2 chars long #opcode 4 - output the digit in the position given elif(n == 4): print(getValue(i+1, modes[0])) i += 2 #go to next instruction - this instruction is 2 chars long #opcode 5 - jump to given place in program if True elif(n == 5): if(getValue(i+1, modes[0]) != 0): i = getValue(i+2, modes[1]) #set pointer to second parameter else: i += 3 #go to the next instruction as normal #opcode 6 - jump to given place in program if False elif(n == 6): if(getValue(i+1, modes[0]) == 0): i = getValue(i+2, modes[1]) #set pointer to second parameter else: i += 3 #go to the next instruction as normal #opcode 7 - store '1' in position given if first param less than second elif(n == 7): if(getValue(i+1, modes[0]) < getValue(i+2, modes[1])): ints[ints[i+3]] = 1 else: ints[ints[i+3]] = 0 i += 4 #go to next instruction (this instruction is 3 chars long) #opcode 8 - store '1' in position given if first and second params match elif (n == 8): if(getValue(i+1, modes[0]) == getValue(i+2, modes[1])): ints[ints[i+3]] = 1 else: ints[ints[i+3]] = 0 i += 4 #go to next instruction (this instruction is 3 chars long) #return the diagnostic code at position 0 in list print("Halting...") return ints[0] #returns modes if they were supplied, or a list of 0's if none present def determineModes(instruction): if(len(instruction) > 2): #get all digits apart from opcode (2 right-most digits) modes = instruction[:-2] #reversed so it reads left to right (so the first mode comes first) modes = list(reversed(modes)) #pad out the list (where mode is not supplied, mode = 0) while(len(modes) < 3): modes.append('0') return modes else: return ['0','0','0'] #returns a value depending on which mode is given def getValue(location, mode): if(mode == '1'): #immediate mode - returns the value itself return ints[location] elif(mode == '0'): #position mode - returns value in that position in list return ints[ints[location]] #main routine ints = getIntsList() intCode(ints)
ba2fe89080908ed784ca8f2f9d78dcf593e2112f
1reddymallik1/ETrade-Trading
/Entries/ActiveItem.py
1,946
3.546875
4
from BusinessModels.SellDeltaType import SellDeltaType class ActiveItem: """ A class used to represent the stock item in the UI. Basically UI model for the stock item. Attributes: Symbol:str - Stock symbol. StartPrice:float - Start price. BuyStepSize:float - Buy intervals. Applied when quantity is greater than 0. SellStepSize:float - Sell profit. Applied when the SellStepType is FIXED or PERCENTAGE. SellStepType:SellDeltaType - Option to decide on the Sell price. When FIXED - SellStepSize value is used as profit amount per stock. When PERCENTAGE - SellStepSize value is used as percentage. When NEXTBUYPRICE - Sell price is the next(forward) BUY price. Quantity:int - The fixed quantity for the stock. It's convention based. When the quantity is greater than 0 - The Qualitity in the field is used. When the quantity is 0 - PriceCoordinates0 is applied. When the quantity is -1 - PriceCoordinates1 is applied and so on. MaxActiveBuy:int - Maximum number of active BUY orders for this stock. QuantityMultiplier:int - Used to multiply the quantity. Should be useful in case of Split(Reverse Split) or used to avoid creating another PriceCoordinate """ def __init__(self, symbol:str, startPrice: float, buyStepSize:float = 0, sellStepSize: float = 0, sellStepType:SellDeltaType = SellDeltaType.FIXED, quantity:int = 0, maxActiveBuy:int = 0, quantityMultiplier:int = 1): self.Symbol:str = symbol self.StartPrice:float = startPrice self.BuyStepSize:float = buyStepSize self.SellStepSize:float = sellStepSize self.SellStepType:SellDeltaType = sellStepType self.Quantity:int = quantity self.MaxActiveBuy:int = maxActiveBuy self.QuantityMultiplier:int = quantityMultiplier
150733010482a316e26ade49afd7cebfd0361a78
kamalikap/leetcode_python_solutions
/backtracking/permutationsII.py
856
3.875
4
""" 47. Permutations II: Runtime: 40 ms, faster than 92.96% Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. Example 1: Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]] Example 2: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] """ class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] nums.sort() self.dfs(nums, [], res) return res def dfs(self, nums, path, res): if len(nums) == 0: res.append(path) for i in range(len(nums)): if i > 0 and nums[i] == nums[i-1]: continue self.dfs(nums[:i] + nums[i+1:], path + [nums[i]], res)
36586c381d4ac83d16f8d0a265a8ad99e637ce20
rserafico1/MIS3640
/calc.py
1,611
4.125
4
print(42*60+42) print(10*1.61) print(2562/16.1) #exercise 1 due 9/6 by 11:59pm pi = 3.14 print((4/3)*pi*5**3) print('The volume of a sphere with a radius of 5 units is', (4/3)*pi*5**3) # 1 Final Answer print(24.95*.4) # cover price * 40% discount = discount amount print(24.95-9.98) # cover price - discount amount = price per book print(14.97*60) # price per book (rounded up) * number of copies = total costs of books alone print(3+(.74*59)) # shipping cost for first book + (shipping cost for each additional book * remaining quantity) = total shipping cost print(898.2+46.66) # total cost of books alone + total shipping costs = total wholesale cost for 60 copies print('The total wholesale cost for 60 copies is $', 898.2+46.66) # 2 Final Answer print(((8*60)+15)) # ( [8] minutes * 60 seconds) + [15] seconds = total seconds for that first mile print(((21*60)+36)) # ( [7+7+7] minutes * 60 seconds) + [12+12+12] seconds = total seconds for those next 3 miles print((495+1296+495)/60) # (first mile seconds + next 3 miles seconds + final mile seconds [same length as first mile]) / 60 seconds = total minutes from running print(60-52) # minutes in a hour - time = remaining minutes of previous hour print(38.1-8) # total running minutes - remaining minutes of previous hour print('7:30 am') # 6:52am + 8 min = 7:00am + 30.1 min = 7:30am print('You will get home at 7:30am for breakfast') # 3 Final Answer print(89-82) # new number - original number = increase amount print(7/82) # increase amount / original = percentage of the increase print('The percentage of the increase is 8.5%') # 4 Final Answer
19691c743c01407b06cf5c8619163476a19f6673
excelsky/Leet1337Code
/274_h-index.py
378
3.671875
4
# https://leetcode.com/problems/h-index # class Solution: # def hIndex(self, citations: List[int]) -> int: def hIndex(citations): citations.sort() n = len(citations) for i, c in enumerate(citations): if c >= n - i: return n - i return 0 assert(hIndex([3,0,6,1,5])) == 3 assert(hIndex([10,8,5,4,3])) == 4 assert(hIndex([25,8,5,3,3])) == 3
df3bd288aa70da59bb985d31d565951a42a6de8d
daniel-reich/ubiquitous-fiesta
/ZWEnJEy2DoJF9Ejqa_17.py
143
3.546875
4
def edabit_in_string(txt): i = 0 for c in txt: if c == 'edabit'[i]: if i == 5: return "YES" i += 1 return "NO"
70aa89c49430ac8c285bfb5cdee3c1e419c7628f
Mmsimpson/Python-exercises
/matrix_add2_functionex.py
894
3.8125
4
m1= { [2,3] [5,7] } m2= { [7,8] [6,2] } height = len(matrix1) width= len(matrix1[0]) def create_empty_matrix(width, height): result=[] # initialize the resulting matrix for i in range(0, height): result.append([]) for j in range(0, width): result[i].append(0) return result height = len(matrix1) width = len(matrix1[0]) matrix = create_empty_matrix(width, height) matrix = create_empty_matrix(3, 3) #fill in the matrix def add_matrices(m1, m2): height = len(m1) width = len(matrix1[0]) matrix = create_empty_matrix(width, height) for i in range(0, height): for j in range(0, width): cell1= m1[i][j] cell2= m2[i][j] matrix[i][j]= cell1 + cell2 return matrix m1= { [2,3] [5,7] } m2= { [7,8] [6,2] } result= add_matrices(matrix1, matrix2) print result
a5bed60b0190fc42afee5d2bf78445d9e87d6464
linux-downey/bloc_test
/leetcode/two_sum/two_sum.py
495
3.5625
4
def twoSum(nums, target): data=[] print len(nums) for i in range(len(nums)): print len(data) for j in range(len(data)): if(nums[i] != data[j]): print 12 else: return [j,i] data.append(target-nums[i]) return None def main(): nums = [22222,22222] target =44444 result=twoSum(nums,target) print result if __name__ == '__main__': main()
f0e8e88ab9648f07f148a940fccd38e63dd3f87b
SmileAK-47/pystuday
/JiChu/ChuangJia-List.py
337
4.0625
4
'''for value in range(1,5): print(value) numbers = list(range(1,6)) print(numbers) even_number = list(range(2,11,2)) print(even_number) ''' squares =[] for value in range(1,11): square = value**2 #平方 squares.append(square) print(squares) digits =[1,2,3,4,7,8,9] print(min(digits)) print(max(digits)) print(sum(digits))
6e06d7fd784749401036a31c32c39623c2533fc8
lidianxiang/leetcode_in_python
/数组/26-删除排序数组中的重复项.py
2,101
3.53125
4
""" 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。 你不需要考虑数组中超出新长度后面的元素。 """ class Solution: """ 看了一些大佬的解题思路, 大多数都是考虑使用双指针从头到尾遍历. 这样用for循环就会衍生出一个问题: 在遍历列表/数组/切片等的过程中, 此时该列表/数组/切片等的长度会发生变化. 然后有很多大佬直接改用while循环进行解答. 其实, 我们可以换位思考一下: 正向遍历有影响, 我可以反向遍历啊. 想到这个, 题目就很好解了. 1、从nums的最后一个开始遍历, 然后与前一个进行对比. 2、如果相等, 则删除该位置的数. 3、不等, 则继续往前遍历. """ def removeDuplicates(self, nums): for num_index in range(len(nums)-1, 0, -1): if nums[num_index] == nums[num_index - 1]: nums.pop(num_index) return len(nums) class Solution2: def removeDuplicates(self, nums: List[int]) -> int: # 定义两个指针pre,cur pre, cur = 0, 1 # 遍历数组 while cur < len(nums): # 当两个指针所指的数组值相等时 if nums[pre] == nums[cur]: # pop掉cur指针所指的值 nums.pop(cur) else: # 不等时,pre指针和cur指针各向前进一位 pre, cur = pre + 1, cur + 1 # 返回最后数组的长度 return len(nums)
5edeab6e076e75e4eeb60b4916656f093cd4c33a
omeriliski/short_examples
/ass8.py
208
4.0625
4
year = "" while len(str(year)) != 4: year = int(input("Dört haneli bir sayı giriniz: ")) if (year%4 == 0) & (year%400 == 0): print(f"{year} is a leap year") else: print(f"{year} is not a leap year")
ec42250a166ca3699ac80fe8c06d96f5ce397efb
kahelum/Python_review
/Python_숫자자료형/Python_숫자자료형/Python_18_파일입출력.py
1,899
3.78125
4
# 파일입출력 # open() : 파일을 특정한 모드로 여는 함수. 읽을 때는 r, 쓸 때는 w를 사용. # read() : 파일 객체로부터 모든 내용을 읽는 함수 # readline() : 파일 객체로부터 한 줄씩 문자열을 읽는 함수 # readlines() : 전체 내용을 한 번에 리스트에 담는 함수 f = open("Python_18_input.txt", "r") f.seek(9) data = f.read() print(data) f.close() print("---------------------------------") o = open("Python_18_input.txt", "r") count = 0 while count < 3: data = o.readline() count = count + 1 print("%d번째 줄 : %s" %(count, data), end = "") o.close() print() print("---------------------------------") p = open("Python_18_input.txt", "r") list = p.readlines() print(list) print("---------------------------------") for i, data in enumerate(list): print("%d번째 줄 : %s" %(i + 1, data), end = '') p.close() print() print("---------------------------------") with open("Python_18_input.txt", "r") as e: list = e.readlines() for i, data in enumerate(list): print("%d번째 줄 : %s" %(i + 1, data), end = '') print() print("---------------------------------") def process(filename): with open(filename, "r") as n: # 키 : 알파벳, 값 : 빈도수 dict = {} data = n.read() for i in data: if i in dict: dict[i] += 1 else: dict[i] = 1 return dict dict = process("Python_18_input.txt") print(dict) print("---------------------------------") # 빈도수를 기준으로 내림차순 정렬 수행 dict = sorted(dict.items(), key = lambda a:a[1], reverse = True) # dict.items() -> a / 값 -> a[1] *즉 값을 기준으로 정렬하겠다라는 뜻 print(dict) for data, count in dict: if data == '\n' or data == ' ': continue print("%d번 출현 : [%c]" %(count, data))
b092c9359ba7df8ae4f09893472d772b6c219783
marronjo/teaching-python
/week4.py
210
4.09375
4
#practice nesting for loops #printing out 10x10 multiplication tables for number1 in range(1,11): for number2 in range(1,11): print(number1*number2,end="\t") print("\n") number = 4 second = 5
76cbd2d0d242ea07f5edeb7dc516a5af0b83cf1c
annguyenict172/coding-exercises
/exercises/queue_and_stack/check_building_with_sunset.py
1,152
3.546875
4
import unittest from collections import namedtuple # Note that buildings are streams, rather than a list def check_building_with_sunset(buildings): Building = namedtuple('Building', ('id', 'height')) building_with_views = [] for idx, height in enumerate(buildings): while len(building_with_views) and height >= building_with_views[-1].height: building_with_views.pop() building_with_views.append(Building(idx, height)) return [b.id for b in building_with_views] class TestResult(unittest.TestCase): def test_empty_building_list(self): self.assertEqual([], []) def test_height_increasing_buildings(self): self.assertEqual(check_building_with_sunset([1, 2, 3, 4, 5, 6, 7, 8]), [7]) def test_height_decreasing_buildings(self): self.assertEqual(check_building_with_sunset([8, 7, 6, 5, 4, 3, 2, 1]), [0, 1, 2, 3, 4, 5, 6, 7]) def test_equal_height_buildings(self): self.assertEqual(check_building_with_sunset([1, 1, 1, 1, 1]), [4]) def test_arbitrary_buildings(self): self.assertEqual(check_building_with_sunset([1, 5, 8, 4, 9, 2, 3]), [4, 6])
f87a186bc7789ec0284f2c34583eede01576d3bc
MaartenAmbergen/Programming_2018
/pe6_4.py
669
3.53125
4
def new_password(oldpassword, newpassword): numberinpassword = 0 for i in newpassword: if i in '1234567890': numberinpassword = numberinpassword + 1 if oldpassword == newpassword: print("Je nieuwe password mag niet hetzelfde zijn als de oude") return False elif len(newpassword) < 6: print("je password moet minimaal 6 karakters bevatten") return False elif numberinpassword == 0: print("er moet een cijfer voorkomen in je nieuwe password") return False else: print("dit password voldoet aan de eisen") return True new_password("test33", "Test233")
d39aeda79e214fe8c899bbd8646ea89b640d01d0
ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck
/problems/LC140.py
971
3.5625
4
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: trie = {} for word in wordDict: curTrieLevel = trie for char in word: if char not in curTrieLevel: curTrieLevel[char] = {} curTrieLevel = curTrieLevel[char] curTrieLevel[True] = True res = set() self.explore(s, trie, trie, [], 0, res) return list(res) def explore(self, s, trie, curTrieLevel, sentence, index, res): if index >= len(s): if True in curTrieLevel: res.add("".join(sentence).rstrip()) return if s[index] not in curTrieLevel: return if True in curTrieLevel[s[index]]: self.explore(s, trie, trie, sentence + [s[index], " "], index + 1, res) self.explore( s, trie, curTrieLevel[s[index]], sentence + [s[index]], index + 1, res )
bea4faee109012980ffb1887b2f42faa20d4a88b
zmm0404/python-
/实战4_超市抹零.py
447
3.765625
4
print('请输入苹果的价格:') A = input() print('请输入香蕉的价格:') B = input() C = float(A)+float(B) # 总价格 print('商品的总价格为:') print(C) print(type(C)) print('-----------------------------') print('价格转化为字符型结果为:') D = str(C) # 浮点型转化成字符型 print(D) print(type(D)) print('-----------------------------') print('抹零') E = int(C) # 取整 print(E) print (type(E))
6812384794e52e6bf5f4e54b517e1b62126cd8eb
jreiher2003/code_challenges
/hackerrank/python/collections/named_tuple.py
577
3.84375
4
from collections import namedtuple Point = namedtuple('Point', 'x, y') pt1 = Point(1,2) pt2 = Point(3,4) dop_product = ( pt1.x * pt2.x ) + ( pt1.y * pt2.y ) print dop_product avg = namedtuple('Avg', 'ID, MARKS, NAME, CLASS') raymond = avg(1,97,"Raymond",7) print raymond.MARKS from collections import namedtuple N = int(raw_input()) avg = 0 Student = namedtuple('Student', raw_input().strip().split()) for i in range(N): x = Student._make(raw_input().strip().split()) avg += int(x.MARKS) avg1 = float(avg)/N print "{0:.2f}".format(avg1)
6877b737d9f747852278f4e06bb0fa8b0691587a
JollenWang/study
/python/demo100/26.py
307
3.546875
4
#!/usr/bin/python #-*- coding:utf-8 -*- #author : Jollen Wang #date : 2016/05/10 #version: 1.0 ''' 【程序26】 题目:利用递归方法求5!。 ''' def fun(i): if i == 0: return 1 return i * fun(i - 1) print("fun(0)=%d" %fun(0)) print("fun(1)=%d" %fun(1)) print("fun(5)=%d" %fun(5))
c8bbb1128d1890416568538b3de8a43edbe869f0
mtargon48/Engineering_4_notebook
/Python/Calculator.py
646
3.84375
4
import math def doMath(a,b,c): a = int(a) b = int(b) if c == 1: return str(a+b) else: if c == 2: return str(round(a-b,2)) if c == 3: return str(round(a*b, 2)) if c == 4: return str(round(a/b, 2)) if c == 5: return str(round(a%b, 2)) number_1 = input('Enter your first number: ') number_2 = input('Enter your second number: ') a = number_1 b = number_2 print("Sum:\t\t" + doMath(a,b,1)) print("Difference:\t" + doMath(a,b,2)) print("Product:\t" + doMath(a,b,3)) print("Quotient:\t" + doMath(a,b,4)) print("Modulo:\t\t" + doMath(a,b,5))
2cbcb91639895c342c986ab0a39872b13ac77b51
prasanthravula/Python-scripts
/Arrays.py
2,444
3.875
4
#import array #a=array.array('i',[1,2,3,4]) #from array import * #a=array('i',[1,2,3,4]) #Arrays are mutable and have same type of data import array as arr a=arr.array('i',[1,2,3,4,5]) #Acessing Elements print(a) print(a[1]) print(a[-4]) #Adding elements print(len(a))# print the length of array a.append(6) # adding one element to array print(a) a.extend([7,8,9])# adding more than one element to array print(a) a.insert(0,10)# insert element at particular position print(a) #Removing Elements print(a.pop()) # remove and return element print(a) print(a.pop(8)) # remove and return element at particular index print(a) print(a.pop(-1)) # remove and return element at particular index print(a) a.append(10) print(a) print(a.remove(10)) # remove particular element at frist occurance print(a) #Concatination of elements b=arr.array('i',[5,6,7,8,92,3,4,1]) c=arr.array('i',[1,2,3,4,5]) d=a+b print("conat:",d)#print(type(d)) array type:array.array #slicing elements print(d[0:5]) #print frist four elements print(d[0:-1]) #pritn all elements except last one print(d[0:-2]) #pritn all elements except last two print(d[::-1]) # prints the reverse form of array but original one remains same and exhuast the memory print(d) #Looping through array #for loop for i in d: print(i) for i in d[0:2]: print(i) for i in d[0:-10]: print(i) #While loop temp=0 while temp<len(d): print(d[temp]) temp+=1 #HashMaps,HashTabels #example Dictionaries also type of hashtables my_dict={1:'py',2:'Ai',3:'Dl'} print(type(my_dict)) new_dict=dict() print(new_dict) print(type(new_dict)) new_dict=dict(dave='001',sai='002') print(new_dict) # Example nested Dectionaries emp_details={'Employee':{'Dave':{'Id':'007','salary':'2000','Age':'19'}, 'subba':{'Id':'008','salary':'23000','Age':'29'}}} print(emp_details) #Accessing values in dictionaries or hashtables print(my_dict[1]) print(my_dict.keys()) print(my_dict.values()) print(new_dict.get('dave')) for x in my_dict: print(x) for x in my_dict.values(): print(x) for x in my_dict.items(): print(x) #Updating values in Dictionaries my_dict[2]='ML' my_dict[4]='AI' print(my_dict) #Deleating Dictionaries my_dict.pop(3) my_dict.popitem() del my_dict[2] print(my_dict) # Dict to Data Frames(df) import pandas as pd df=pd.DataFrame(emp_details['Employee']) print(df)
0a64ffaeb270d953065f26f61bfec05ec5cdcc04
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/anagram/c9107408074a4ba69ac3b1825e90e421.py
445
3.828125
4
def detect_anagrams(word, candidates): # normalize the word due to case insensitivity word = word.lower() letters_in_word = list(word) letters_in_word.sort() matches = [] for candidate in candidates: normalized = candidate.lower() if normalized == word: continue letters_in_candidate = list(normalized) letters_in_candidate.sort() if letters_in_candidate == letters_in_word: matches.append(candidate) return matches
b72366ea9b2fb512c131ec2c8840adfb487797d1
maryanncummings/csci107
/week of 11-4/fact_while.py
252
4.09375
4
def factorial(n): total = 1 i = n while i != 1: total *= i i = i - 1 return total def main(): n = int(input("Enter number: ")) n_fact = factorial(n) print(str(n) + "! is " + str(n_fact)) main()
7b1638c53e1c0196e49618f2d5dc63b15279ae8b
chasefrankenfeld/how_to_think_like_a_computer_scientist
/chapters1_to_3/turtle_stuff.py
398
3.6875
4
import turtle wn = turtle.Screen() wn.bgcolor('lightgreen') wn.title('Turtle Game') ben = turtle.Turtle() ben.pencolor("purple") ben.shape("turtle") ben.color('blue') ben.pensize(3) ben.penup() ben.stamp() for i in range(12): ben.forward(160) ben.pendown() ben.forward(10) ben.penup() ben.forward(30) ben.stamp() ben.backward(200) ben.right(30) wn.mainloop()
5ed2c69b281d37b8b1085fb5afd4a91032954117
eltnas/ExerciciosPythonBrasil
/03 - EstruturaDeRepeticao/27.py
357
3.796875
4
qtdTurma = int(input('Quantas turmas: ')) alunosTurma = [] turma = 1 for i in range(qtdTurma): print('Turma {}'.format(turma)) qtdAlunos = int(input('Quantidade de alunos: ')) turma += 1 alunosTurma.append(qtdAlunos) mediaAlunos = sum(alunosTurma) / len(alunosTurma) print('A media de alunos é de {} por sala!'.format(mediaAlunos))
9e5fc0532d83bafbf5de7b17a77ee1edfa2b9495
Aasthaengg/IBMdataset
/Python_codes/p02897/s426837309.py
165
3.65625
4
def main(): n = int(input()) t = (n+1) // 2 if n == 1: print(1) elif n % 2 == 0: print(0.5) else: print(t*1.0 / n) main()
e72cbf8f6e67d4d3f92e0319a80b4ff66db60eed
shshamim63/python_basic
/time_delta.py
264
3.59375
4
from datetime import datetime t = int(input()) for i in range(t): time_1 = datetime.strptime(input(), "%a %d %b %Y %X %z") time_2 = datetime.strptime(input(), "%a %d %b %Y %X %z") result = abs(int((time_1 - time_2).total_seconds())) print(result)
a6160ba95554d2e756c3e4313e5344e2d8c1a452
AdityaShidlyali/Python
/Learn_Python/Chapter_6/3_functions_returning_2_values.py
636
4.4375
4
# function which returns two values # basically it dosent returns two defferent values it returns tuple with two or more values # after returning the tuple we can unpack the tuple to store the elements in different variables def func (data_1, data_2) : add = data_1+data_2 multiply = data_1*data_2 tuple_1 = (add, multiply) # however we replace this line with tuple_1(data_1+data_2, data_1*data_2) return tuple_1 # we can print the multiple values at once print(func(2,3)) # we can also unpack the tuple by storing its values in different variables addition, multiplicatoin = func(2,3) print(addition, multiplicatoin)
9e49731c4d4bfa668aecdefb3ce0b31b4ebd0d05
AdamZhouSE/pythonHomework
/Code/CodeRecords/2396/60671/258838.py
437
3.5
4
length=int(input()) str0=input() ll=str0.split() list0=[] for i in ll: list0.append(int(i)) pla=[] for i in range(length): needToSort=list0[i:] dontNeedToSort=list0[:i] minnum=min(*needToSort) minplace=needToSort.index(minnum) pla.append(minplace+i+1) inner=needToSort[:minplace+1] outer=needToSort[minplace+1:] inner.sort() list0=dontNeedToSort+inner+outer print(*pla)
8fb8bdfb20f00ee4edc046c9b3cb4dc8290abfc1
Darasimi-Ajewole/HackerRank
/Strings/funny_strings.py
459
3.71875
4
#-*-coding:utf8;-*- #qpy:3 #qpy:console def check_funny(string): s = [ord(char) for char in string ] r = s * 1; r.reverse() for k in range(len(s) - 1): a = abs(s[k] - s[k+1]) b = abs(r[k] - r[k+1]) if a != b: print("Not Funny") return print("Funny") if __name__ == "__main__": n = int(input()) for i in range(n): string = input() check_funny(string)
706ec874932b48dc9bcc2648d91486317ef01ad1
yaoyong2019/py
/liebiesehngchengshi_.py
437
3.53125
4
L = [] for x in range(1,11): L.append(x * x) print(L) print([x*x for x in range(1,11)])#列表生成式 print([x*x for x in range(1,11) if x %2 == 0]) print([m+n for m in 'abc' for n in 'xyz']) import os print([d for d in os.listdir('.')])#列出当前目录下文件和目录 L1 = ['Hello', 'World', '18', 'Apple', 'None'] print([s.lower() for s in L1]) d = {'x': 'A', 'y': 'B', 'z': 'C' } print([k + '=' + v for k, v in d.items()])
8afbd927a8be71208f7719f10d4d3c70d7ae51a7
qsyPython/Python_play_now
/chaizhiyong/day1/绘制图形.py
354
3.578125
4
import turtle turtle.screensize(302,278) turtle.write("hello world",font=("宋体",200,"normal")) turtle.showturtle() turtle.pensize(2) turtle.begin_fill() turtle.circle(200,steps = 3) turtle.color("red") turtle.end_fill() turtle.reset() turtle.pensize(2) turtle.begin_fill() turtle.circle(200,180) turtle.color("red") turtle.end_fill() turtle.done()
944ab02e5ca556bab63ce2c04a1375727f987149
tortuepin/edison
/utils.py
236
3.71875
4
import sys def ljust(string, length): count_length = 0 for char in string: if ord(char) <=255: count_length += 1 else: count_length += 2 return string + (length-count_length) * ' '
01cdef94ce8c0bde4272a3b9f94acca6d77346c6
aj112358/data_structures_advanced
/Arrays/Caesar_cipher_class.py
1,951
4.40625
4
"""A module that implements a Caesar cipher, but allows you to define shifts other than three (taken from book). Created By: AJ Singh Date: Feb 21, 2021 """ class CaesarCipher: """Class for doing encryption and decryption using a simple substitution cipher.""" def __init__(self, shift): """Construct the encoder and decoder strings for the given shift.""" # Initializing temporary arrays for encryption and decryption, respectively. encoder = [None] * 26 decoder = [None] * 26 # Constructing the arrays. for k in range(26): encoder[k] = chr((k + shift) % 26 + ord("A")) decoder[k] = chr((k - shift) % 26 + ord("A")) # Converting to string (to make immutable). self._forward = "".join(encoder) self._backward = "".join(decoder) def encrypt(self, plaintext): """Return string representation of ciphertext.""" return self._transform(plaintext, self._forward) def decrypt(self, ciphertext): """Return string representation of plaintext.""" return self._transform(ciphertext, self._backward) def _transform(self, original, code): """Utility to perform a transformation, based on a given code alphabet. @param original: String to convert (can be either plaintext or ciphertext). @param code: Alphabet we use for conversion (either encoder or decoder) """ msg = list(original) for k in range(len(msg)): if msg[k].isupper(): j = ord(msg[k]) - ord("A") # Determining correct index for new character. msg[k] = code[j] return "".join(msg) if __name__ == "__main__": cipher = CaesarCipher(3) message = "THE EAGLE IS IN PLAY; MEET AT JOE S." coded = cipher.encrypt(message) print('Secret:', coded) answer = cipher.decrypt(coded) print('Message:', answer)
0f90b085d6b7fe0dc27f9a1034f2b5e7d7ad5db2
rexarabe/Python_projects2
/String/string11.py
166
4.34375
4
"""The split() method split the string into substrings if it finds instance of the separator:""" a = "Hello, World!" print(a.split(",")) #returns ['Hello', 'World!']
c53170b3444e2ae890b4d80385fc769dc02576f3
CodyBankz/SisonkeRising
/CarCollection.py
625
3.796875
4
''' Author Koketso Maphothoma A Dictionary(Map) that groups my Favourite cars.''' # A Function to display my favourite Cars ( The Dictionary/Map group ) def display_Cars(): My_Favourite_Cars = { 1 : " Mercedes Benz AMG G63 " , 2 : " Ford Mustang G550 " , 3 : " BMW M6 " , 4 : " VW Sirocco R " , 5 : " Mercedes Benz AMG C63 " , 6 : " Mercedes Benz AMG SLS " } print(" This are Koketso's favourite cars : ") for favouriteCar in My_Favourite_Cars : print(favouriteCar , My_Favourite_Cars.get(favouriteCar)) ''' Calling a function to display ''' display_Cars()
a172b1aaf95948989ee3a7ffdee4382399c2360f
Albertara/git_hdrif
/Forritun/Tímaverkefni/te_slembitala.py
1,258
3.59375
4
from random import * from math import * from time import * #liður 1 a = 1 while(a == 1): for i in range(10): print (randint(1,20), end=" ") print("\r\n") voff = str(input("Viltu keyra forritið aftur?(já/nei)")) if voff == "nei": a = 0 #liður 2 yo = 1 while(yo == 1): t1 = randint(1,6) t2 = randint(1,6) t3 = randint(1,6) print("Teningur 1:" , t1) print("Teningur 2:" , t2) print("Teningur 3:" , t3) if t1 == t2 == t3: print ("Allir teningar eru eins") elif t1 == t2: print ("2 teningar eru eins") elif t1 == t3: print ("2 teningar eru eins") elif t2 == t3: print ("2 teningar eru eins") else: print ("Engir teningar eru eins") blub = str(input("Viltu keyra forritið aftur?(já/nei)")) if blub == "nei": yo = 0 #liður 3 teljari = 0 g = 1 while(g == 1): teljari += 1 print ("Reyndu að finna töfra töluna ╰( ⁰ ਊ ⁰ )━☆゚.*・。゚: ") teningur = randint(1,10) swag = int(input("Sláðu inn heiltölu(1-10): ")) if swag == teningur: print("Þú giskaðir á töfratöluan ╰( ⁰ ਊ ⁰ )━☆゚.*・。゚, það tók þig" , teljari , "tilraunir") teljari = 0 vondur = str(input("Viltu keyra þetta forrit aftur?(já/nei):")) if vondur == "nei": print ("Bless") exit()
91ca4a4c946e0e0818d83c9319e08fec79b20450
ArunPrasad017/python-play
/coding-exercise/Day64-SerializeDeserializeTree.py
992
3.546875
4
def serialize(self, root): """Encodes a tree to a single string :type root: TreeNode :rtype: str """ def serialize(root): def recurse_serialize(root, lst): if root is None: lst.append = ["None"] else: lst.append(root.val) if root.left: recurse_serialize(root.left, lst) if root.right: recurse_serialize(root.right, lst) return "".join(lst) return recurse_serialize(root, []) def deserialize(data): def recurse_deserialize(lst): if lst[0] == "None": lst.pop(0) return None root = TreeNode(lst[0]) lst.pop(0) root.left = recurse_deserialize(lst) root.right = recurse_deserialize(lst) return root data_list = data.split(",") root = recurse_deserialize(data_list) return root
11c589aeb045cf61d48d6930f8b8e958d68ddb9c
redbean88/python
/starcraft.py
4,038
3.59375
4
from random import * class Unit: def __init__(self, name , hp , speed): # 생성자 ( self 제외 , 동일한 arg를 받는다) self.name = name self.hp = hp self.speed = speed print("{0} 유닛이 생성되었습니다.".format(name)) def move(self , location): print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name , location , self.speed)) def damaged(self,damage): print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage)) self.hp -= damage print("{0} : 현재 체력은 {1} 입니다.".format(self.name , self.hp)) if self.hp <= 0 : print("{0} : 파괴되었습니다.".format(self.name)) class AttackUnit(Unit): def __init__(self, name , hp , speed , damage): # 생성자 ( self 제외 , 동일한 arg를 받는다) Unit.__init__(self, name , hp, speed) self.damage = damage def attack(self , location): print("{0} : {1} 방향으로 적군을 공격 합니다.[공격력 : {2}]"\ .format(self.name,location,self.damage)) # 마린 class Marine(AttackUnit): def __init__(self): AttackUnit.__init__(self , "마린",40,1,5) # 스팀팩 (이동속도증가, 공격속도증가, 체력 10 감소) def stimpack(self): if self.hp > 10: self.hp -= 10 print("{0} : 스팀팩을 사용합니다.".format(self.name)) else: print("{0} : 체력이 부족합니다.".format(self.name)) # 탱크 class Tank(AttackUnit): def __init__(self): AttackUnit.__init__(self , "탱크",150 ,1 ,35) self.seize_mode = False seize_developed = False # 개발 여부 def set_seize_mode(self): if Tank.seize_developed == False: return if self.seize_mode == False: print("{0} : 시즈모드 전환".format(self.name)) self.damage *= 2 self.seize_mode = True else: print("{0} : 일반모드 전환".format(self.name)) self.damage /= 2 self.seize_mode = False class Flyable: def __init__(self , flying_speed): self.flying_speed = flying_speed def fly(self , name , location): print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]".format(name , location , self.flying_speed)) # 다중상속 class FlyableAttackUnit(AttackUnit , Flyable): def __init__(self , name ,hp , damage , flying_speed): AttackUnit.__init__(self, name, hp ,0 , damage) # 지상 speed 0 Flyable.__init__(self ,flying_speed) def move(self , location): self.fly(self.name , location) # 레이스 class Wraith(FlyableAttackUnit): def __init__(self): FlyableAttackUnit.__init__(self , "레이스", 80 , 20 , 5) self.clocked = False def clocking(self): if self.clocked == True: print("{0} : 클록킹 해제".format(self.name)) self.clocked == False if self.clocked == False: print("{0} : 클록킹 시작".format(self.name)) self.clocked == True def game_start(): print("[알림] 새로운 게임을 시작합니다.") def game_over(): print("gg") # 게임 진행 game_start() m1 = Marine() m2 = Marine() m3 = Marine() t1 = Tank() t2 = Tank() w1 = Wraith() attack_units = [] attack_units.append(m1) attack_units.append(m2) attack_units.append(m3) attack_units.append(t1) attack_units.append(t2) attack_units.append(w1) # 전군 이동 for unit in attack_units: unit.move("1시") Tank.seize_developed = True # 공격 모드 준비 for unit in attack_units: if isinstance(unit , Marine): unit.stimpack() elif isinstance(unit ,Tank): unit.set_seize_mode() elif isinstance(unit ,Wraith): unit.clocking() # 공격 for unit in attack_units: unit.attack("1시") # 전군 피해 for unit in attack_units: unit.damaged(randint(5, 20)) game_over()
c9d33499505ac1181b6a7df6426268833b6b61f2
cdvr1993/interviews
/airbnb/list-iterator/list-iterator.py
1,907
3.921875
4
class Iterator2D(object): def __init__(self, lists): self._lists = lists self._prev = (-1, -1) self._current = (0, -1) def __iter__(self): return self def _next_index(self): r, c = self._current while r < len(self._lists): c += 1 if c < len(self._lists[r]): break else: c = -1 r += 1 return (r, c) def has_next(self): r, c = self._next_index() return 0 <= r < len(self._lists) and 0 <= c < len(self._lists[r]) def __next__(self): if self.has_next(): self._prev = self._current self._current = self._next_index() return self._lists[self._current[0]][self._current[1]] raise StopIteration() def remove(self): """Removes the element at current position It is not possible to call this before next() and more than one time for each call. """ if self._current == self._prev or self._current[1] == -1: return del self._lists[self._current[0]][self._current[1]] self._current = self._prev if self._current[0] == -1: self._current = (0, -1) def test_iterator(): lists = [ [1,2,3], [], [], [4,5], [6], [7,8,9,10] ] it = Iterator2D(lists) for item in it: print(item) print(it._lists) def test_iterator_remove(): lists = [ [1,2,3], [], [], [4,5], [6], [7,8,9,10] ] it = Iterator2D(lists) # This calls does not affect it.remove() it.remove() it.remove() for item in it: it.remove() # The second call does not affect it.remove() print(item) # At the end the list is empty print(it._lists) def main(): test_iterator() test_iterator_remove() if __name__ == '__main__': main()
6b187f82e297d56c35a184657b0f902f0ce869f2
ishauchuk/homework
/hw_09/task_02.py
380
4.09375
4
# Создать lambda функцию, которая принимает на вход неопределенное количество # именных аргументов и выводит словарь с ключами удвоенной длины. {‘abc’: 5} -> {‘abcabc’: 5} func = lambda **kwargs: {k + k: v for k, v in kwargs.items()} print(func(a=2, bb=3))
9030bdd84cb702e644ea2f98088aa56fd948839f
sobriquette/interview-practice-problems
/Pramp/hasCommonSubsequence.py
240
3.609375
4
def has_subsequence(a, b): chars_a = set(a) for c in b: if c in chars_a: return 1 return 0 if __name__ == "__main__": num_tests = int(input()) for i in range(num_tests): a, b = input().split() print(has_subsequence(a, b))
a342327d7783771be0d2d53aad560647522bbf47
chezmatt/python_fundamentals
/pythonfund6.py
695
3.6875
4
def f(x): for i in range(5): return { 'a': 1, 'b': 2, }[x def gradeCalc (score, times): for i in range (times): while switch(n): if case(0): print "You typed zero." break if case(1, 4, 9): print "n is a perfect square." break if case(2): print "n is an even number." if case(2, 3, 5, 7): print "n is a prime number." break if case(6, 8): print "n is an even number." break print "Only single-digit numbers are allowed." break
e78b0feee3d5497efaea2ae3a047c4d87c27f445
Jeromeschmidt/newSuperHeroTeamDueler
/p2/hero.py
1,222
4.125
4
import random class Hero: # We want our hero to have a default "starting_health", # so we can set that in the function header. def __init__(self, name, starting_health=100): '''Instance properties: name: String starting_health: Integer current_health: Integer ''' # we know the name of our hero, so we assign it here self.name = name # similarly, our starting health is passed in, just like name self.starting_health = starting_health # when a hero is created, their current health is # always the same as their starting health (no damage taken yet!) self.current_health = starting_health def fight(self, opponent): ''' Current Hero will take turns fighting the opponent hero passed in. ''' # TODO: Fight each hero until a victor emerges. # Phases to implement: #1) randomly choose winner winner = random.choice([self, opponent]) print(str(winner.name) + " has won!") if __name__ == "__main__": # If you run this file from the terminal # this block is executed. hero1 = Hero("Wonder Woman") hero2 = Hero("Dumbledore") hero1.fight(hero2)
4d38f301e94e459467583eb0567fe70ce29144eb
aloktiwari1404/Kid-Learning-game
/name.py
792
3.6875
4
from tkinter import * import pics as pi def pics(): # global root_name global e9,root_name temp = Entry.get(e9) root_name.destroy() pi.main(temp) def name(): global root_name,e9 root_name=Tk() root_name.title('Kids Memory Games') x=Canvas(bg='cadetblue3', height=600,width=850,borderwidth=5) base=PhotoImage(file="cut.png") x.create_image(650,300,anchor=NE,image=base) x.pack() l9=Label(root_name,text='Enter your name : ',font=("times 24 bold"),bg='cadetblue3') e9=Entry(root_name,borderwidth=2) b9=Button(root_name, text='Submit',bg='cadetblue3',command=pics) l9.place(x=200,y=220) e9.place(x=480,y=232) b9.place(x=500,y=282) root_name.mainloop() #def collect(): #e8=e9
5c368c64af68701e016a39039ad1afc6b9848b15
klknet/geeks4geeks
/algorithm/greedy/job_sequence.py
1,043
4.0625
4
""" Q: given a arr of jobs which have deadline time and can earn profit if finish the job before the deadline, it is also that each job can process on an unit time, at every time ,only ont job can be processed, find the maximum profit. 1)Sort the job arr according decreasing order 2)Process the job for each: a)put the job to result sequence if the job fit the deadline """ def print_job_scheduling(arr, t): n = len(arr) # sort accord decreasing order arr.sort(key=lambda x: x[2], reverse=True) # time slots for indicate job fit the deadline slots = [False] * t job = [-1] * t for i in range(n): for j in range(arr[i][1] - 1, -1, -1): if not slots[j]: slots[j] = True job[j] = arr[i][0] break print(job) arr = [['a', 2, 100], # Job Array ['b', 1, 19], ['c', 2, 27], ['d', 1, 25], ['e', 3, 15]] arr = [['a', 4, 20], ['b', 1, 10], ['c', 1, 40], ['d', 1, 30]] print_job_scheduling(arr, 4)
da6d268dcf81788d0b27f7f76c573ec4e85254fe
RITSTARClub/star-site
/semesters.py
1,656
3.703125
4
# -*- coding: utf-8 -*- import re from datetime import datetime FIRST_YEAR = 2013 FIRST_SEMESTER = 2013.2 FALL_START_MONTH = 8 ### ### Semesters are always formatted as year.semester (e.g., “2013.2”, or “2014.1”) ### def is_fall_now(): return datetime.now().month >= FALL_START_MONTH def get_current_semester(): # Get the current month and year. now = datetime.now() # Treat August as the start of fall semester. semester = now.year + (0.2 if is_fall_now() else 0.1) # Return the formatted semester number. return semester def get_all_semesters(): # Create the list of semesters. semesters = [FIRST_YEAR + 0.2] year = FIRST_YEAR + 1 now = datetime.now() while year <= now.year: semesters.append(year + 0.1) if year != now.year or is_fall_now(): semesters.append(year + 0.2) year += 1 return semesters def get_semester_from_query(query): match = re.search('\\bsemester:([0-9.]{6})\\b', query) if match: return float(match.group(1)) else: return None def prev_semester(semester): if round(semester - int(semester), 1) == 0.2: return semester - 0.1 else: year = int(semester) - 1 return year + 0.2 def next_semester(semester): if round(semester - int(semester), 1) == 0.1: return semester + 0.1 else: year = int(semester) + 1 return year + 0.1 def semester_date(semester): year = int(semester) semester = semester - year month = (1 if round(semester, 1) == 0.1 else FALL_START_MONTH) return datetime(year, month, 1) def semester_pretty(semester): year = int(semester) semester_str = 'Spring' if round(semester - year, 1) == 0.1 else 'Fall' return semester_str + ' ' + `year`
b2a73f3f53cb4739d85e035e2594181d881ca147
AnnaHun/Python_Study
/python_base/day02/code03.py
188
3.84375
4
price = float(input("请输入商品单价")) amount = int(input("请输入商品数量")) money = float(input("请输入金额")) result = money - price * amount print("应找回"+result)
300f8f5bee31838de001b1a149b87ea29141ce72
jadeshi/scikit-learn
/sklearn/utils/directional_gini.py
1,921
3.5
4
import numpy as np def directional_feature_importance(model,normalize=True): '''Computes a version of Gini importance that includes information about the direction of correlation, analogous to a beta coefficient in linear regression, for a single DecisionTreeRegressor. This is a slight modification of a function to calculate normal Gini importance, found at the following link: https://stackoverflow.com/questions/49170296/scikit-learn-feature-importance-calculation-in-decision-trees ''' values = model.tree_.value.T[0][0] left_c = model.tree_.children_left right_c = model.tree_.children_right impurity = model.tree_.impurity node_samples = model.tree_.weighted_n_node_samples feature_importance = np.zeros((model.tree_.n_features,)) for idx,node in enumerate(model.tree_.feature): if node >= 0: # Determine if each split in the tree corresponds to a positive or negative correlation between feature and prediction left_value = values[left_c[idx]] right_value = values[right_c[idx]] diff = right_value - left_value diff /= np.abs(diff) feature_importance[node]+= diff *(impurity[idx]*node_samples[idx]- \ impurity[left_c[idx]]*node_samples[left_c[idx]]-\ impurity[right_c[idx]]*node_samples[right_c[idx]]) # Number of samples at the root node feature_importance/=node_samples[0] if normalize: feature_importance /= np.sum(np.abs(feature_importance)) return feature_importance def compute_ensemble_directionality(rf): '''Computes directional Gini importance for a RandomForestRegressor''' outputs = [] for tree in rf.estimators_: output = directional_feature_importance(tree) outputs.append(output) outputs = np.mean(outputs,axis=0) return outputs
30bd501b50901ef35cf877102f0ca3911bb24c47
DVDBZN/Schoolwork
/CS136 Database Programming With SQL/SQLite3Programs/PRA28 - Primary Keys/PrimaryKeys/PrimaryKey.py
2,342
4.46875
4
import sqlite3 import sys #Connections conn = sqlite3.connect("Customers.sqlite3") cur = conn.cursor() #CREATE table with a PRIMARY KEY try: conn.execute("CREATE TABLE Customer" + "(CustID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE," + "FirstName Text, LastName TEXT)") print "Table created" except: print "Table exists" def display(): #Reusable select statement select = "SELECT * FROM Customer ORDER BY CustID" cur.execute(select) #If selected data is empty, notify user if cur.fetchone() is None: print "\nNo records exist.\n" return #Select again to include all records cur.execute(select) #Table header Print hyphen 35 times print "\n ID | First Name | Last Name\n" + "-" * 35 #Print each selected row for row in cur.fetchall(): #Formatting to make the output readable print ( " " + "{0: <7}".format(str(row[0])) + "| " + "{0: <11}".format(row[1]) + "| " + row[2]) def insert(): #Prompt for name firstName = raw_input("Enter first name: ") lastName = raw_input("Enter last name: ") try: #INSERT Names into table #No ID is inserted because AUTOINCREMENT is used cur.execute("INSERT INTO Customer (FirstName, LastName) VALUES(?, ?)", (firstName, lastName)) print "\nSuccessfully inserted\n" except: print "\nInsert unsuccessful\n" def end(): save = raw_input("Save changes? (y/n)").upper() #Save if save == "Y" or save == "YES": conn.commit() #Close conn.close() sys.exit() def main(): while True: print "\n" + "-" * 35 + "\nChoose an option:" try: #Menu choices choice = int(raw_input("\n\t1...Display table\n\t" + "2...Insert new record\n\t" + "3...Exit\n")) except: #If bad input is entered print "\nInvalid choice\n" continue if choice == 1: display() elif choice == 2: insert() elif choice == 3: end() else: print "\nInvalid choice\n" continue main()
6557a4a298aa0989d9a5ef9ec58db5aefe9c84c3
q798010412/untitled2
/6.24/队列_array.py
482
3.875
4
class Queue: def __init__(self): self.queue = [] self.front = 0 self.size = 0 def __repr__(self): str1 = '<' + str(self.queue)[1:-1] + '>' return str1 def put(self, data): self.queue.append(data) self.size += 1 def get(self): dequeue = self.queue[self.front] self.size -= 1 self.queue = self.queue[1:] return dequeue n = Queue() n.put(1) n.put(2) n.put(3) n.get() print(n)
39a15574b949944713f903be196ce96fd05cd712
ivek1337/UPROG
/Vježba 1/Zadatak 2 - Ispis znakovnog niza (stringa) - direktno i funkcijom print.py
469
3.640625
4
print('a)\tProgramski jezik Python dobio je naziv po seriji "Monty Python", bit ce zabavno') #Za navodnke unutar navodnika koriste se i jednostruki i dvostruki navodnici print("b)\t'IDLE - Integrated DeveLopment Enviroment'") print("c)\t'int, float, bool, str'") print("d)\tInt, float, bool, str") print("e)\tInt\n\tfloat\n\tbool\n\tstr") #\t --> tabulator (ostavlja 4 prazna mjesta ispred rijeci/ znaka \n --> naredba za prebacivanje rijeci/ znaka u novi red
df579b09894a3f89373b185bd98df29265a64efe
rusucosmin/pychallenge
/2.py
184
3.53125
4
#http://www.pythonchallenge.com/pc/def/ocr.html s = "" with open("3.html") as f: for line in f.readlines(): s += line for el in s: if el >= 'a' and el <= 'z': print(el),
6a77ab678956098124e05210cba49f17994a6d86
TypAnna/GruProgDD1331
/Övning6/uppg2Memory.py
219
3.609375
4
def funB(a, b): a[1]= "hej" b = ("katt", "lo") def funA(): a = [[1, 2], [3, 4]] b = (5, 6) funB(a, b) #what does the memory look like here? print("this is p", a) print("this is q", b) funA()
40012567a57448deb5bc557fbaa09d084ee20030
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/MichaelM/lesson3/mailroom.py
7,466
3.984375
4
esteemed_donors_headers = ["Donor Name", "Total Donation", "Number of Donations", "Ave Donation"] esteemed_donors = [["John Jacob Astor", 10], ["John Jacob Astor", 100], ["John Jacob Astor", 1000], ["John Jacob Astor", 10000], ["Alan Rufus, 1st Lord of Richmond", 10], ["Henry Ford", 10], ["Henry Ford", 100], ["Henry Ford", 1000], ["Cornelius Vanderbilt", 10], ["Jakob Fugger", 10], ["Jakob Fugger", 100]] def create_ty_letter(user_response): """ takes user input and incorporates this input into a list of donors and returns text to the screen Extended description: If a donor (user_response) exists the function will take the input, add their current donation and print to screen an email template containing the new data. If the donor does not exists the donor will be added to the list and the user will be prompted for a donation amount after which the new data will be incorporated into email and printed to screen. Parameters: my_int (int): integer to be padded Returns: result (string): a padded number """ found_donor_count = 0 if user_response.lower() == "list": for row in list_donors(): print(''.join([str(elem) for elem in row])) print() if user_response.lower() != "list": for donor in esteemed_donors: if user_response.title() == donor[0]: found_donor_count += 1 print() # new donor if found_donor_count == 0 and user_response.lower() != "list": response_1 = "" response_2 = 0.0 sum_amt = 0.0 response_1 = user_response.title() response_2 = input("How much is {}'s donation? >".format(user_response.title())) response_2 = float(response_2) add_donor(user_response.title(), response_2) for donor in esteemed_donors: if donor[0] == response_1: sum_amt = sum_amt + donor[1] print("{0:,.2f} added to {1}'s total. " "{1}'s total contribution is {2:,.2f}".format(response_2, user_response.title(), sum_amt)) print("\nThank you email:\n{}".format(spam("new", response_1, response_2, "ty"))) print() # existing donor if found_donor_count != 0 and user_response.lower() != "list": response_2 = 0.0 sum_amt = 0.0 response_1 = user_response.title() response_2 = input("{} found. How much is the donation? >".format(user_response.title())) response_2 = float(response_2) add_donor(user_response.title(), response_2) for donor in esteemed_donors: if donor[0] == response_1: sum_amt = sum_amt + donor[1] print("{0:,.2f} added to {1}'s total. " "{1}'s total contribution is {2:,.2f}".format(response_2, user_response.title(), sum_amt)) print("\nThank you email:\n{}".format(spam("existing_donor", response_1, response_2, "ty", sum_amt))) print() def spam(donor_type, donor, donation_amt, spam_type, total_amt_donated=0): """ creates an email thank you text prints the text to the screen. The template text contains parameters within the body {Extended description} Parameters: donor_type (string): integer to be padded donor (string): integer to be padded donation_amt (string): integer to be padded spam_type (string): integer to be padded total_amt_donated (float): integer to be padded Returns: result (string): the email text """ donation = "${0:,.2f}".format(int(donation_amt)) total_donation = "${0:,.2f}".format(int(total_amt_donated)) results = "" if donor_type == "new" and spam_type == "ty": results = f"[Subject]: Thank you for your generous donation\n" \ f"\n" \ f"[Body]: {donor},\n" \ f"Thank you for your generous donation. We are always grateful to greet new members of " \ f"our ever expanding family.\n" \ f"Your current and future beneficent contributions will go towards " \ f"administering our clients with our services.\n" \ f"Your initial contribution of {donation} illustrates an exceedingly benevolent nature.\n" \ f"\n" \ f"Kind regards,\n" \ f"The Minimalist Society\n" \ f"[End]" elif donor_type == "existing_donor" and spam_type == "ty": results = f"[Subject]: Once again, thank you for your generous donation\n" \ f"\n" \ f"[Body]: {donor},\n" \ f"Thank you for your generous donation. Your beneficent contribution of {donation} will go " \ f"towards administering our clients with our services.\n" \ f"Our records show to date your generosity " \ f"of {total_donation} illustrates an exceedingly benevolent nature.\n" \ f"\n" \ f"Kind regards,\n" \ f"The Minimalist Society\n" \ f"[End]" return results def create_report(): """ creates a report summarizing donors and donations and prints the report to the screen. {Extended description} Parameters: {none} Returns: {none} """ tmp_donor_list = [] for row in list_donors(): donor_sum = sum([t[1] for t in esteemed_donors if t[0] == row]) donation_cnt = len([t[1] for t in esteemed_donors if t[0] == row]) donor_ave = donor_sum / donation_cnt tmp_donor_list.append([row, donor_sum, donation_cnt, donor_ave]) print("{name:<40}{total_donation:<20}{donation_cnt:<30}{ave_donation:}".format( name=esteemed_donors_headers[0], total_donation=esteemed_donors_headers[1], donation_cnt=esteemed_donors_headers[2], ave_donation=esteemed_donors_headers[3])) tmp_donor_list = sorted(tmp_donor_list, key=lambda x: x[1], reverse=True) for row in tmp_donor_list: print("{name:<40}{total_donation:<20}{donation_cnt:<30}{ave_donation:}".format(name=row[0], total_donation=row[1], donation_cnt=row[2], ave_donation=row[3])) print() def list_donors(): """ Returns a list of distinct donors {Extended description} Parameters: {none} Returns: distinct_donors (list): distinct donor list """ donors = [] for donor in esteemed_donors: donors.append(donor[0]) distinct_donors = set(donors) return distinct_donors def add_donor(donor, amt): """ adds a new donor to the list {Extended description} Parameters: donor (string): new donor amt (int): donation amount Returns: {none} """ esteemed_donors.append([donor, amt])
d146f3642318734e49e1da765c31dcb90e8b79ec
Lobarr/interview-practice
/ds/treeInterface.py
1,835
3.90625
4
ERR_NOT_IMPLEMENTED = NotImplementedError('must be implemented by subclasses') class Tree: """ abstract base class representing a tree structure """ class Node: """ an abstraction representing the location of a single element """ def getElement(self): raise ERR_NOT_IMPLEMENTED def __eq__(self, check): raise ERR_NOT_IMPLEMENTED def __ne__(self, check): raise not (self == check) def root(self): raise ERR_NOT_IMPLEMENTED def parent(self, node): raise ERR_NOT_IMPLEMENTED def numChildren(self, node): raise ERR_NOT_IMPLEMENTED def children(self, node): raise ERR_NOT_IMPLEMENTED def __len__(self): raise ERR_NOT_IMPLEMENTED def isRoot(self, node): return self.root() == node def isLeaf(self, node): return self.numChildren(node) == 0 def isEmpty(self): return len(self) == 0 def depth(self, node) -> int: if self.isRoot(node): return 0 return 1 + self.depth(self.parent(node)) def height(self, node): if self.isLeaf(node): return 0 else: return 1 + max(self.height(child) for child in self.children(node)) class BinaryTree(Tree): def left(self, node): raise ERR_NOT_IMPLEMENTED def right(self, node): raise ERR_NOT_IMPLEMENTED def sibling(self, node): parent = self.parent(node) if not parent: return None else: return self.right(parent) if node == self.left( parent) else self.left(node) def children(self, node): if self.left(node) != None: yield self.left(node) if self.right(node) != None: yield self.right(node)
079f1b15a09af5a61a22af19d4c15c0151a6a1d8
gauravtatke/codetinkering
/dsnalgo/Sort.py
5,658
3.5625
4
#import math def __merge(numlist, lindex, mindex, rindex, reverse=False): n1 = mindex - lindex + 1 #no of items in left list n2 = rindex - mindex #no of items in right list llist = [] rlist = [] for i in range(n1): llist.append(numlist[lindex+i]) #llist.append(float('inf')) #adding infinity at last for j in range(n2): rlist.append(numlist[mindex+j+1]) #rlist.append(float('inf')) i = 0 j = 0 if reverse: #To sort in descending order llist.append(float('-inf')) #adding infinity at last rlist.append(float('-inf')) for k in range(lindex, rindex+1): #loop from start to end index if llist[i] >= rlist[j]: numlist[k] = llist[i] i = i+1 else: numlist[k] = rlist[j] j = j+1 else: llist.append(float('inf')) #adding infinity at last rlist.append(float('inf')) for k in range(lindex, rindex+1): #loop from start to end index if llist[i] <= rlist[j]: numlist[k] = llist[i] i = i+1 else: numlist[k] = rlist[j] j = j+1 def msort(numlist, beg, end, reverse=False): #merge sort if beg < end: mid = (beg + end)//2 msort(numlist, beg, mid, reverse) msort(numlist, mid+1, end, reverse) __merge(numlist, beg, mid, end, reverse) return numlist def isort(numlist, beg, end, reverse=False): #insertion sort i = beg #initial index for key in numlist[beg+1:end+1]: #from beg+1 to end i = i+1 #current index in numlist j = i-1 if reverse: while j >= beg and numlist[j] < key: numlist[j+1] = numlist[j] j = j-1 numlist[j+1] = key else: while j >= beg and numlist[j] > key: numlist[j+1] = numlist[j] j = j-1 numlist[j+1] = key def __partition(numlist, beg, end, reverse=False): key = numlist[end] i = beg-1 if reverse: for j in range(beg, end): if numlist[j] >= key: i = i+1 numlist[i], numlist[j] = numlist[j], numlist[i] numlist[i+1], numlist[end] = numlist[end], numlist[i+1] return i+1 for j in range(beg, end): #should run to end-1 if numlist[j] <= key: i = i+1 numlist[i], numlist[j] = numlist[j], numlist[i] #swap the elements numlist[i+1], numlist[end] = key, numlist[i+1] return i+1 def __partition_intup(numlist, beg, end, reverse=False): ''' returns a tuple (q,t) such that numlist[beg..q-1]< numlist[q] and numlist[t+1..end] > numlist[t] and numlist[q..t] are same ''' q = t = end pivot = numlist[end] i = beg-1 j = beg while j <= q-1: if numlist[j] < pivot: i = i+1 numlist[i], numlist[j] = numlist[j], numlist[i] elif numlist[j] == pivot: numlist[j], numlist[q-1] = numlist[q-1], numlist[j]#copy same elem near to pivot q = q-1 #move q to left j = j-1 #run loop one more time for new value of numlist[j] j = j+1 num_repeat = t-q+1 q = i+1 #this is starting index for elements in q..t for k in range(num_repeat): #loop copies numlist[q...t] from end to correct position i = i+1 numlist[i], numlist[t] = numlist[t], numlist[i] t = t-1 #nex iteration copies numlist[t-1] t = i #print(q,t) return (q, t) def qsort(numlist, beg, end, reverse=False): if beg < end: mid = __partition(numlist, beg, end, reverse) qsort(numlist, beg, mid-1, reverse) qsort(numlist, mid+1, end, reverse) def qsort_tup(numlist, beg, end, reverse=False): if beg < end: q, t = __partition_intup(numlist, beg, end, reverse) qsort_tup(numlist, beg, q-1, reverse) qsort_tup(numlist, t+1, end, reverse) def bsort(numlist, beg, end, reverse=False): #Bubble Sort if reverse: for i in range(beg, end+1): for j in range(end, beg, -1): if numlist[j] > numlist[j-1]: numlist[j], numlist[j-1] = numlist[j-1], numlist[j] else: for i in range(beg, end+1): for j in range(end, beg, -1): if numlist[j] < numlist[j-1]: numlist[j], numlist[j-1] = numlist[j-1], numlist[j] def isort_rec(numlist, beg, end, reverse=False): if beg == end: return key = numlist[end] isort_rec(numlist, beg, end-1, reverse) k = end-1 if reverse: while k >= beg and numlist[k] < key: numlist[k+1] = numlist[k] k = k-1 numlist[k+1] = key else: while k >= beg and numlist[k] > key: numlist[k+1] = numlist[k] k = k-1 numlist[k+1] = key def sort(numlist, beg=0, end=None, func=msort, reverse=False): if not end: end = len(numlist)-1 print('Calling {0}()'.format(func)) return func(numlist, beg, end, reverse) if __name__ == '__main__': numlist1 = [3, 4, 2, 5, 9, 7, 1, 6] numlist2 = [23, 43, 12, 32, 65, 76, 17, 29] numlist3 = [5,1,7,3,4,2,5,8,4,9,5,4,10,11,17,9,5,3,4] sort(numlist1) #sort(numlist2, 0, len(numlist2)-1, func=qsort) #sort(numlist3, 0, len(numlist3)-1, func=bsort) print(numlist1) #print(numlist3)
dbbd738826f61f4f6d1555639ee2e652645113a6
bashbash96/InterviewPreparation
/LeetCode/Facebook/Easy/543. Diameter of Binary Tree.py
1,329
4.34375
4
""" Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. Example 1: Input: root = [1,2,3,4,5] Output: 3 Explanation: 3is the length of the path [4,2,1,3] or [5,2,1,3]. Example 2: Input: root = [1,2] Output: 1 Constraints: The number of nodes in the tree is in the range [1, 104]. -100 <= Node.val <= 100 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ return diameter_of_bin_tree(root)[1] # time O(n) # space O(h) def diameter_of_bin_tree(node): if not node: return 0, 0 left = diameter_of_bin_tree(node.left) right = diameter_of_bin_tree(node.right) curr_path_length = left[0] + right[0] longest_path = max(left[1], right[1], curr_path_length) return max(left[0], right[0]) + 1, longest_path
ad259dfa34633d24596b1616ccc4a227fbdaac4b
Alexeggers/Codeeval
/Medium/minimum_coins.py
393
3.609375
4
from sys import argv with open(argv[1], "r") as file: test_cases = [int(x.strip()) for x in file.read().splitlines() if x] def check_coins(counter,case,coin): counter += int(case/coin) case = case%coin return counter,case for case in test_cases: counter = 0 for coin in range(5,0,-2): counter, case = check_coins(counter, case, coin) print(counter)
35879663171b3835e11e88c9cb7e80eecbfe196e
manali1312/pythonsnippets
/dictionaries.py
281
3.6875
4
sampleMap={'manali':1,'mandar':0} '''if 'mandar' in sampleMap: print("here") val=sampleMap.pop('mandar') ''' sampleMap['manali'] += 1 sampleMap['shubham'] = 0 for key,value in sampleMap.items(): print(key+" "+str(value)) #print(sampleMap['manali'])
ea659fe229def2521427fcad35549332b8d50ac6
skhan75/CoderAid
/Algorithms/Arrays & Strings/subarray_with_sum_0.py
1,321
4.09375
4
""" Check if a Sub array with sum 0 exists or not For finding a subarray with a subset sum which equals to a given sum, refer "DynamicProgramming/subset_sum" Complexity: O(n) Logic: ------ For optimal runtime, we use hashing to keep a track of the sum as we move forward in the array. - Iterate from 0 --> n in the array - Keep calculating sum for the iterations and put them in a hashset. - We have a subarray that sums out to 0: - if the sum repeats itself (i.e. if its already present in the hashset) - or if the sum becomes 0 - or if there's a 0 in array """ def has_subbarray_0_sum(arr): s = set() sum = 0 for i in range(len(arr)): sum += arr[i] if (sum in s) or (sum is 0): return True s.add(sum) return False import unittest class Test(unittest.TestCase): def test_has_subbarray_0_sum(self): data_true = [[4, 2, -3, 1, 6], [4, 2, 0, 1, 6], [3, 4, -7, 3, 1, 3, 1, -4, -2, -2]] for test in data_true: res = has_subbarray_0_sum(test) self.assertTrue(res) data_false = [[-3, 2, 3, 1, 6], [1, 2, 3, 4, 5, 6]] for test in data_false: res = has_subbarray_0_sum(test) self.assertFalse(res) if __name__ == "__main__": unittest.main()
332b20d9b441425f28dcf33891f25bb8d6b39e8f
PBearson/cracking-the-coding-interview
/9-interview-questions/2-linked-lists/2-5.py
4,853
3.984375
4
# Given 2 linked lists representing two integers, add the "integers" and return the sum as a linked list. # The digits are stored in reverse order, i.e., the head is the ones digit. The output should have similar ordering. # Example: # Input: 7 -> 1 -> 6 and 5 -> 9 -> 2 # Output: 2 -> 1 -> 9 (since 617 + 295 = 912) # Follow up: Now do it when the digits are stored in forward order. # Example: # Input: 6 -> 1 -> 7 and 2 -> 9 -> 5 # Output: # 9 -> 1 -> 2 (since 617 + 295 = 912) # Idea: We need a function for converting from a linked list to an int and from an int to a linked list. # To convert to an int, we traverse the node like so: 912 = 2 * 10^0 + 1 * 10^1 + 9 * 10^2 # To convert to a linked list, the head value is (912 % 10^1) / 10^0 = 2 -> (910 % 10^2) / 10^1 = 1 -> (900 % 10^3) / 10^2 = 9 # Unfortunately this way is considered "cheating". We need another way. # Idea 2: Iterate over the linked lists and add their digits together. If a certain digit is greater than 10, then we must carry the 1 to the next digit. # This can be done in-place, i.e., we just update one of the linked lists. # Follow up idea: First add the digits in each place verbatim. Then iterate through the linked lists and if the next digit is greater than 10, subtract 10 # and increment the current node by 1. from singlylinkedlist import SinglyLinkedList as LL from singlylinkedlist import Node import math def LLToIntReverse(ll): result = 0 power = 0 curr = ll.head while curr != None: result += curr.value * 10 ** power power += 1 curr = curr.next return result def intToLLReverse(value): ll = LL() firstDigit = value % 10 ll.head.value = firstDigit value -= firstDigit curr = ll.head power = 1 while value > 0: digit = int(value % (10 ** (power + 1)) / (10 ** power)) curr.next = Node(digit) value -= digit * 10 ** power power += 1 curr = curr.next return ll def sumLinkedListsReverseCheating(ll1, ll2): sum = LLToIntReverse(ll1) + LLToIntReverse(ll2) return intToLLReverse(sum) def getListLength(ll): if(ll.head is None): return 0 length = 0 curr = ll.head while curr is not None: length += 1 curr = curr.next return length def sumLinkedListsForward(ll1, ll2): ll1Length = getListLength(ll1) ll2Length = getListLength(ll2) if ll1Length < ll2Length: for i in range(ll2Length - ll1Length): node = Node() node.next = ll1.head ll1.head = node elif ll1Length > ll2Length: for i in range(ll1Length - ll2Length): node = Node() node.next = ll2.head ll2.head = node ll1Curr = ll1.head ll2Curr = ll2.head while ll1Curr is not None or ll2Curr is not None: if ll1Curr is None: digit = ll2Curr.value ll1Curr = Node(digit) elif ll2Curr is None: break else: ll1Curr.value += ll2Curr.value if ll1Curr.value > 9: if ll1Curr == ll1.head: newHead = Node(1) newHead.next = ll1Curr ll1Curr.value -= 10 else: ll1Prev.value += 1 ll1Curr.value -= 10 ll1Prev = ll1Curr ll2Prev = ll2Curr ll1Curr = ll1Curr.next ll2Curr = ll2Curr.next return ll1 def sumLinkedListsReverse(ll1, ll2): ll1Curr = ll1.head ll2Curr = ll2.head carry = 0 while ll1Curr is not None or ll2Curr is not None: if ll1Curr is None: digit = ll2Curr.value ll1Curr = Node(digit) elif ll2Curr is None: break else: digit = ll1Curr.value + ll2Curr.value + carry ll1Curr.value = digit % 10 if digit > 9: carry = 1 else: carry = 0 ll1Curr = ll1Curr.next ll2Curr = ll2Curr.next if carry == 1: ll1.insert(1) return ll1 ll1 = LL(9) ll1.insertMultiple([7, 8]) ll2 = LL(6) ll2.insertMultiple([8, 5]) llSum = LL(5) llSum.insertMultiple([6, 4, 1]) assert llSum.toString() == sumLinkedListsReverse(ll1, ll2).toString() ll1 = LL(3) ll1.insertMultiple([2, 4]) ll2 = LL(5) ll2.insert(6) llSum = LL(8) llSum.insertMultiple([8, 4]) assert llSum.toString() == sumLinkedListsReverse(ll1, ll2).toString() ll1 = LL(6) ll1.insertMultiple([1, 7]) ll2 = LL(2) ll2.insertMultiple([9, 5]) llSum = LL(9) llSum.insertMultiple([1, 2]) assert llSum.toString() == sumLinkedListsForward(ll1, ll2).toString() ll1 = LL(4) ll1.insertMultiple([2, 3]) ll2 = LL(6) ll2.insert(5) llSum = LL(4) llSum.insertMultiple([8, 8]) assert llSum.toString() == sumLinkedListsForward(ll1, ll2).toString()
37a90fe337c082bed8b055d0f60e8e941001471a
mlparthtrivedi/ML
/titanic survival prediction/titanic_survival_predication_new.py
11,504
3.671875
4
# -*- coding: utf-8 -*- #Import Necessary Libraries import numpy as np import pandas as pd #visualization libraries import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline #ignore warnings import warnings warnings.filterwarnings('ignore') #Read in and Explore the Data train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") #Data Analysis features_details = train.describe(include = "all"); nan_value_detail = pd.isnull(train).sum(); #Data Visualization #draw a bar plot of survival by sex sns.barplot(x="Sex", y="Survived", data=train) #print percentages of females vs. males that survive print("Percentage of females who survived:", train["Survived"][train["Sex"] == 'female'].value_counts(normalize = True)[1]*100) print("Percentage of males who survived:", train["Survived"][train["Sex"] == 'male'].value_counts(normalize = True)[1]*100) #draw a bar plot of survival by Pclass sns.barplot(x="Pclass", y="Survived", data=train) #print percentage of people by Pclass that survived print("Percentage of Pclass = 1 who survived:", train["Survived"][train["Pclass"] == 1].value_counts(normalize = True)[1]*100) print("Percentage of Pclass = 2 who survived:", train["Survived"][train["Pclass"] == 2].value_counts(normalize = True)[1]*100) print("Percentage of Pclass = 3 who survived:", train["Survived"][train["Pclass"] == 3].value_counts(normalize = True)[1]*100) #draw a bar plot for SibSp vs. survival sns.barplot(x="SibSp", y="Survived", data=train) #I won't be printing individual percent values for all of these. print("Percentage of SibSp = 0 who survived:", train["Survived"][train["SibSp"] == 0].value_counts(normalize = True)[1]*100) print("Percentage of SibSp = 1 who survived:", train["Survived"][train["SibSp"] == 1].value_counts(normalize = True)[1]*100) print("Percentage of SibSp = 2 who survived:", train["Survived"][train["SibSp"] == 2].value_counts(normalize = True)[1]*100) #draw a bar plot for Parch vs. survival sns.barplot(x="Parch", y="Survived", data=train) plt.show() #sort the ages into logical categories train["Age"] = train["Age"].fillna(-0.5) test["Age"] = test["Age"].fillna(-0.5) bins = [-1, 0, 5, 12, 18, 24, 35, 60, np.inf] labels = ['Unknown', 'Baby', 'Child', 'Teenager', 'Student', 'Young Adult', 'Adult', 'Senior'] train['AgeGroup'] = pd.cut(train["Age"], bins, labels = labels) test['AgeGroup'] = pd.cut(test["Age"], bins, labels = labels) #draw a bar plot of Age vs. survival sns.barplot(x="AgeGroup", y="Survived", data=train) plt.show() train["CabinBool"] = (train["Cabin"].notnull().astype('int')) test["CabinBool"] = (test["Cabin"].notnull().astype('int')) #calculate percentages of CabinBool vs. survived print("Percentage of CabinBool = 1 who survived:", train["Survived"][train["CabinBool"] == 1].value_counts(normalize = True)[1]*100) print("Percentage of CabinBool = 0 who survived:", train["Survived"][train["CabinBool"] == 0].value_counts(normalize = True)[1]*100) #draw a bar plot of CabinBool vs. survival sns.barplot(x="CabinBool", y="Survived", data=train) plt.show() #Cleaning Data train = train.drop(['Cabin'], axis = 1) test = test.drop(['Cabin'], axis = 1) train = train.drop(['Ticket'], axis = 1) test = test.drop(['Ticket'], axis = 1) train = train.fillna({"Embarked": "S"}) #create a combined group of both datasets data = [train, test] #extract a title for each Name in the train and test datasets for dataset in data: dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False) pd.crosstab(train['Title'], train['Sex']) #replace various titles with more common names for dataset in data: dataset['Title'] = dataset['Title'].replace(['Lady', 'Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Jonkheer', 'Dona'], 'Rare') dataset['Title'] = dataset['Title'].replace(['Countess', 'Lady', 'Sir'], 'Royal') dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss') dataset['Title'] = dataset['Title'].replace('Ms', 'Miss') dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs') train[['Title', 'Survived']].groupby(['Title'], as_index=False).mean() #map each of the title groups to a numerical value title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Royal": 5, "Rare": 6} for dataset in data: dataset['Title'] = dataset['Title'].map(title_mapping) dataset['Title'] = dataset['Title'].fillna(0) #d above is from here. Next, we'll try to predict the missing Age values from the most common age for their Title. # fill missing age with mode age group for each title mr_age = train[train["Title"] == 1]["AgeGroup"].mode() #Young Adult miss_age = train[train["Title"] == 2]["AgeGroup"].mode() #Student mrs_age = train[train["Title"] == 3]["AgeGroup"].mode() #Adult master_age = train[train["Title"] == 4]["AgeGroup"].mode() #Baby royal_age = train[train["Title"] == 5]["AgeGroup"].mode() #Adult rare_age = train[train["Title"] == 6]["AgeGroup"].mode() #Adult age_title_mapping = {1: "Young Adult", 2: "Student", 3: "Adult", 4: "Baby", 5: "Adult", 6: "Adult"} for x in range(len(train["AgeGroup"])): if train["AgeGroup"][x] == "Unknown": train["AgeGroup"][x] = age_title_mapping[train["Title"][x]] for x in range(len(test["AgeGroup"])): if test["AgeGroup"][x] == "Unknown": test["AgeGroup"][x] = age_title_mapping[test["Title"][x]] #map each Age value to a numerical value age_mapping = {'Baby': 1, 'Child': 2, 'Teenager': 3, 'Student': 4, 'Young Adult': 5, 'Adult': 6, 'Senior': 7} train['AgeGroup'] = train['AgeGroup'].map(age_mapping) test['AgeGroup'] = test['AgeGroup'].map(age_mapping) #dropping the Age feature for now, might change train = train.drop(['Age'], axis = 1) test = test.drop(['Age'], axis = 1) #drop the name feature since it contains no more useful information. train = train.drop(['Name'], axis = 1) test = test.drop(['Name'], axis = 1) #map each Sex value to a numerical value sex_mapping = {"male": 0, "female": 1} train['Sex'] = train['Sex'].map(sex_mapping) test['Sex'] = test['Sex'].map(sex_mapping) #map each Embarked value to a numerical value embarked_mapping = {"S": 1, "C": 2, "Q": 3} train['Embarked'] = train['Embarked'].map(embarked_mapping) test['Embarked'] = test['Embarked'].map(embarked_mapping) #fill in missing Fare value in test set based on mean fare for that Pclass for x in range(len(test["Fare"])): if pd.isnull(test["Fare"][x]): pclass = test["Pclass"][x] #Pclass = 3 test["Fare"][x] = round(train[train["Pclass"] == pclass]["Fare"].mean(), 4) #map Fare values into groups of numerical values train['FareBand'] = pd.qcut(train['Fare'], 4, labels = [1, 2, 3, 4]) test['FareBand'] = pd.qcut(test['Fare'], 4, labels = [1, 2, 3, 4]) #drop Fare values train = train.drop(['Fare'], axis = 1) test = test.drop(['Fare'], axis = 1) #Choosing the Best Model from sklearn.model_selection import train_test_split x = train.drop(['Survived', 'PassengerId'], axis=1) y = train["Survived"] x_train, x_val, y_train, y_val = train_test_split(x, y, test_size = 0.22, random_state = 0) # Gaussian Naive Bayes from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score gaussian = GaussianNB() gaussian.fit(x_train, y_train) y_pred = gaussian.predict(x_val) acc_gaussian = round(accuracy_score(y_pred, y_val) * 100, 2) print(acc_gaussian) # Logistic Regression from sklearn.linear_model import LogisticRegression logreg = LogisticRegression() logreg.fit(x_train, y_train) y_pred = logreg.predict(x_val) acc_logreg = round(accuracy_score(y_pred, y_val) * 100, 2) print(acc_logreg) # Support Vector Machines from sklearn.svm import SVC svc = SVC() svc.fit(x_train, y_train) y_pred = svc.predict(x_val) acc_svc = round(accuracy_score(y_pred, y_val) * 100, 2) print(acc_svc) #Decision Tree from sklearn.tree import DecisionTreeClassifier decisiontree = DecisionTreeClassifier() decisiontree.fit(x_train, y_train) y_pred = decisiontree.predict(x_val) acc_decisiontree = round(accuracy_score(y_pred, y_val) * 100, 2) print(acc_decisiontree) # Random Forest from sklearn.ensemble import RandomForestClassifier randomforest = RandomForestClassifier() randomforest.fit(x_train, y_train) y_pred = randomforest.predict(x_val) acc_randomforest = round(accuracy_score(y_pred, y_val) * 100, 2) print(acc_randomforest) # KNN or k-Nearest Neighbors from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier() knn.fit(x_train, y_train) y_pred = knn.predict(x_val) acc_knn = round(accuracy_score(y_pred, y_val) * 100, 2) print(acc_knn) # Stochastic Gradient Descent from sklearn.linear_model import SGDClassifier sgd = SGDClassifier() sgd.fit(x_train, y_train) y_pred = sgd.predict(x_val) acc_sgd = round(accuracy_score(y_pred, y_val) * 100, 2) print(acc_sgd) # Gradient Boosting Classifier from sklearn.ensemble import GradientBoostingClassifier gbk = GradientBoostingClassifier() gbk.fit(x_train, y_train) y_pred = gbk.predict(x_val) acc_gbk = round(accuracy_score(y_pred, y_val) * 100, 2) print(acc_gbk) models = pd.DataFrame({ 'Model': ['Support Vector Machines', 'KNN', 'Logistic Regression', 'Random Forest', 'Naive Bayes', 'Decision Tree', 'Stochastic Gradient Descent', 'Gradient Boosting Classifier'], 'Score': [acc_svc, acc_knn, acc_logreg, acc_randomforest, acc_gaussian, acc_decisiontree, acc_sgd, acc_gbk]}) models.sort_values(by='Score', ascending=False) #kfold cross validation from sklearn.model_selection import cross_val_score rf = RandomForestClassifier(n_estimators=100) scores = cross_val_score(rf, x_train, y_train, cv=10, scoring = "accuracy") print("Scores:", scores) print("Mean:", scores.mean()) print("Standard Deviation:", scores.std()) #features minify importances = pd.DataFrame({'feature':x_train.columns,'importance':np.round(randomforest.feature_importances_,3)}) importances = importances.sort_values('importance',ascending=False).set_index('feature') importances.head(15) importances.plot.bar() # 2 less important features remove and train train_df = train.drop("Parch", axis=1) test_df = test.drop("Parch", axis=1) train_df = train.drop("CabinBool", axis=1) test_df = test.drop("CabinBool", axis=1) from sklearn.model_selection import train_test_split x_def = train_df.drop(['Survived', 'PassengerId'], axis=1) test_def = test_df.drop(['PassengerId'], axis=1); y_def = train_df["Survived"] x_train_def, x_val_def, y_train_def, y_val_def = train_test_split(x_def, y_def, test_size = 0.22, random_state = 0) # Random Forest random_forest = RandomForestClassifier(n_estimators=100, oob_score = True) random_forest.fit(x_train_def, y_train_def) Y_prediction = random_forest.predict(x_val_def) random_forest.score(x_train_def, y_train_def) acc_random_forest = round(random_forest.score(x_train_def, y_train_def) * 100, 2) print(round(acc_random_forest,2,), "%") #obb score (out of bag score) print("oob score:", round(random_forest.oob_score_, 4)*100, "%") #confusion metrix from sklearn.model_selection import cross_val_predict from sklearn.metrics import confusion_matrix predictions = cross_val_predict(random_forest, x_train_def, y_train_def, cv=3) CM = confusion_matrix(y_train_def, predictions) #precision and recall from sklearn.metrics import precision_score, recall_score print("Precision:", precision_score(y_train_def, predictions)) print("Recall:",recall_score(y_train_def, predictions)) #f1 score from sklearn.metrics import f1_score f1_score(y_train_def, predictions)
f116e00dae76f2a9c2d9a56649100538824ffcf9
LagSeeN/ITE-428-Event-Driven-Programming-Classroom
/Databases/pracSqlExtra6.py
1,165
3.6875
4
import sqlite3 def sqlquery(db, myParam): with (sqlite3.connect(db)) as conn: conn.row_factory = sqlite3.Row sql_commad = '''SELECT CategoryName, count(ProductId) As 'Count Product', sum(UnitPrice * UnitsInStock) As "Sum of Value" FROM Categories LEFT OUTER JOIN Products ON Categories.CategoryID = Products.CategoryId GROUP By CategoryName HAVING "Sum of Value" > ? ORDER By "Sum of Value"; ''' cursor = conn.execute(sql_commad, myParam) found = len(conn.execute(sql_commad, myParam).fetchall()) print('\nFound {} Category(s)'.format(found)) count = 1 for i in cursor: print('{}.) {:<20} {:>3} PD. {:>10,.2f} Baht'.format(count, i['CategoryName'], i['Count Product'], i['Sum of Value'])) count += 1 if __name__ == '__main__': database = './MyData/Sqlite_Northwind.sqlite3' stockValue = int(input('See Value of Stock by Category > : ')) p = [stockValue] sqlquery(database, p)
2ae4f6a878b25a035d5a36e9b65b2c45e8c4e2e3
yash-sinha-850/Personal
/dfs_iterative.py
619
3.796875
4
class Node: def __init__(self,name): self.name=name self.adj_list=[] self.visited=False class depth_first_search: def dfs(self,startnode): stack=[] stack.append(startnode) startnode=True while stack: actualnode = stack[-1] stack.pop() print(actualnode.name) for i in actualnode.adj_list: if not i.visited: i.visited=True stack.append(i) n1=Node("A") n2=Node("C") n3=Node("B") n4=Node("D") n5=Node("E") n1.adj_list.append(n2) n1.adj_list.append(n3) n2.adj_list.append(n4) n3.adj_list.append(n5) dfs=depth_first_search() dfs.dfs(n1)
c04f24ee1fe125b29794bd41bab7e89d1cdecaf6
zenvin/PythonCrashCourse
/PART 1/chapter_4/buffet.py
481
4.3125
4
#think of five simple foods and store them in a tuple buffet_food = ("steak", "fried chicken", "mashed potatoes", "rice pilaf", "meatloaf") #use a loop to print each food the restaurant offers for food in buffet_food: print(food) #replace two items with different foods. Add a line that rewrites the tuples and then use a for loop to print buffet_food = ("steak", "chow-mein", "soon dubu", "rice pilaf", "meatloaf") print("\nModified menu:") for food in buffet_food: print(food)
ad2da04a2812e82d8604e5ddda260bbcd812fee5
Pawanvyas/Python-Code
/Average.py
259
4
4
x=int(input("marks in maths is:")) y=int(input("marks in science is:")) z=int(input("marks in social science is:")) v=int(input("marks in english is:")) b=int(input("marks in sanskrit is:")) a=(x+y+z+v+b)/5 print("average marks is:",a)
64b2b9d59c9341653dc69674af8a109c8ab38625
junjian0812/JdproductTest
/src/test01.py
594
3.625
4
# -*- coding:utf-8 -*- ''' Created on 2017年6月28日 @author: lijj ''' import random from builtins import int secret=random.randint(1,100) print("------我的测试程序----------") print(secret) #tem = input("不放输入一个数字:") #guess =int(tem) guess=0 while guess !=secret: tem =input('输入一个数字吧:') guess =int(tem) if guess==secret: print('我曹,猜对了!!') else: if guess >secret: print('歌,大了') else: print('嘿,小了') print('游戏结束,不玩啦')
d9d8879d2ccfaf2d39bb4eacda235f6f1c67f483
zhangjiahuan17/leetcodePython
/Array/451. Sort Characters By Frequency.py
803
3.953125
4
# -*- coding: utf-8 -*- # !/usr/bin/env python # Time: 2018/7/29 16:30 # Author: sty # File: 451. Sort Characters By Frequency.py from collections import defaultdict class Solution: def frequencySort(self, s): """ :type s: str :rtype: str """ res_dict = defaultdict(int) for i in s: res_dict[i] += 1 s_dict = sorted(res_dict.items(), key=lambda e:e[1], reverse=True) res_str = [] for k, v in s_dict: res_str.append(k * v) return ''.join(res_str) import collections class Solution1(object): def frequencySort(self, str): """ :type str: str :rtype: str """ return "".join([char * times for char, times in collections.Counter(str).most_common()])
eec2d166178da383e08e28aded16f285e47b550e
gauravdaunde/training-assignments
/99Problems/List Problems/P13.py
1,873
3.875
4
''' Run-length encoding of a list (direct solution). Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X. Example: * (encode-direct '(a a a a b c c a a d e e e e)) ((4 A) B (2 C) (2 A) D (4 E)) ''' #taking input of list elements at a single time seperating by space and splitting each by split() method demo_list = input("Enter elememts sep by space: ").split(' ') #creating new lists encoded_list = list() previous_item = demo_list[0] #assigning first element of demo_list to previous_item previous_item_count = 0 for current_item in demo_list: #iterating through all elements of demo_list if current_item == previous_item: #checking if previously added element is same as current element of list, for checking repetative elements previous_item_count += 1 else: #if not repetative element if previous_item_count == 1: #if element not repeating, means have only one occurance thndirectly encoded_list.append(previous_item) else: encoded_list.append([previous_item_count,previous_item]) #appending previously created sublist(temp_list) copy to new_list previous_item_count = 1 previous_item = current_item #assigning current_item to previous_item else: #for last item if previous_item_count == 1: #if element not repeating, means have only one occurance thndirectly encoded_list.append(previous_item) else: encoded_list.append([previous_item_count,previous_item]) #appending previously created sublist(temp_list) copy to new_list #pritning demo_list and its encoded list print(f"old list: {demo_list}") print(f"encoded list: {encoded_list}")
172240337f909d44ebea5199e846c038ee1931a1
gquesnot/BotAi
/util/threadclass.py
514
3.65625
4
from abc import abstractmethod from threading import Thread, Lock class ThreadClass: def __init__(self): self.lock = Lock() self.stopped = False self.started = False def start(self): self.stopped = False self.started = True t = Thread(target=self.run) t.start() def stop(self): self.stopped = True self.started = False def isStarted(self): return self.started @abstractmethod def run(self): pass