blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
b757b0de629d1c89c44094d70099797a48e4c85f
ABPande/MyPythonRepo
/Python/Basics/py_R1/revision.py
1,331
3.96875
4
dict1 = {'key1':"v1",'key2':"v2",'key3':"v3"} print (dict1) newKey = "key4" print (f"{newKey} is being added to dict1") dict1[newKey] = "v4" print (dict1) list1 = ["v5","v6"] for key,value in dict1.items(): print (f"key is {key}, value is {value}") if (key > "key2"): print (f"\t{key} is greater than key2, its value...
ed6cc31fbe5c49d6b27cfce5354a904a46e4fe87
Ckaiique/estudando-python
/aula de while/repetiçoes_while.py
107
3.875
4
x=10 while x > 0: # enquando x for maior que 0 vai ficar repetido print(x) x= x-1 print ("Fogo")
48e80bb8500e85e296afe9d0cffd9da747aa0745
Ckaiique/estudando-python
/aula de while/UsandoBreack.py
210
3.890625
4
x = 1 soma = 0 while True: n =int(input(" Digite o numero:")) if n == 0: break soma = soma + n x = x + 1 print(f"Media : {soma / 5:5.2f}") print(f"foram digitados {x} numeros")
6412b71238e526beced4805187264d278e0c1151
Ckaiique/estudando-python
/if_else_elif/categorias_2.py
429
3.78125
4
# programa 4.7 Categoria x preço, usando elif categoria = int(input("Digite a categoria do produto:")) if categoria == 1: preço = 10 elif categoria == 2: preço = 18 elif categoria == 3: preço = 23 elif categoria == 4: preço = 26 elif categoria == 5: preço = 31 else: print("Categoria invali...
64b5d3ede99a60fd8619555d7bda320526d1798f
Ckaiique/estudando-python
/matematica/matematica.py
531
3.890625
4
#exerciocio numero 1 connvertar 20+10*30 resultado tem que da 900 print ((20+10) *30) # o resultado desse jeito deu 900 # mas eu estava tentado fazer #print (20+10*30) = 320, errado .. # converta 4**2 / 30 print ((4**2)/30) #converta (9**4+2*6-1) print ((9**4 +2)* 6-1) # deu certo do jeito assim print ((9**4...
c4687f8e06ea5144c8fadb1607a4a3cf523c5464
ZhongruiNing/ProjectEuler
/Code of ProjectEuler/problem10.py
796
3.875
4
from math import sqrt import numpy as np import time #判断素数 def isprime(num): #flag=0,素数,flag=1,合数 flag = 0 if num == 1: flag = 1 return flag if num == 2: return flag for i in range(2,int(sqrt(num))+1,1): if num % i == 0: flag = 1 ...
57b3f847aa1d8a5f1c47e1136acfef1e6e77698c
ZhongruiNing/ProjectEuler
/Code of ProjectEuler/problem27.py
1,084
3.828125
4
from math import sqrt def isprime(num): # flag=1,素数,flag=0,合数 flag = 1 if num == 2: return flag for i in range(2, int(sqrt(num)) + 1, 1): if num % i == 0: flag = 0 return flag return flag result = 0 result_a = 0 result_b = 0 for a in rang...
fd16aed1ff77e10be274c2b19a90dc9e3e260553
libbybakalar/Python
/Project2.py
8,153
3.796875
4
# Libby Bakalar # 4/29/19 # This program will read in user ids and names from a file and # give the user the option to login in, create a new user, or # reset their password. import os import time clear = lambda:os.system('cls') dictionary = {} def main(): init(dictionary) def init(dictionary...
1d0ebac3d405a84e6ae04abc18e84af2a1eed4e6
PiKwaii93/ProjetPython
/game.py
3,361
3.546875
4
from Joueur import Joueur from Mot import Mot from Phrase import Phrase from random import randint class GAME : def __init__(self) : self.joueur1 = Joueur("Francis") self.joueur2 = Joueur("Maurice") self.Combat() def Combat(self) : x = 0 print("\n") ...
c8c6e327317638653a5f775580499767f9f8bd65
walllab/reciprocal_smallest_distance
/rsd/nested.py
7,875
3.625
4
''' Code for creating nested directory structures to avoid having a single directory with millions of files. Code for creating nested temp files and dirs. ''' import os import hashlib # sha import uuid import shutil # SET THE DEFAULT TMP DIR ROOT. if os.environ.has_key('NESTED_TMP_DIR'): DEFAULT_TMP_DIR = os.envi...
cb81211e53074a35e91b7ec44008f190b7746a02
KirillGorsh/PythonBasics
/dictionaries_loops.py
1,246
3.84375
4
student1 = {'name' : "'Kirill", 'gpa': 4.0, 'LastName': 'Gorshenin'} student2 = {'name': 'Hamza', 'gpa': 3.7, 'LastName': 'Smith'} for info in student1: print('key is:', info) for info in student1.keys(): print('key is:', info) print('Looping key') for key in student1.keys(): print('value is:', student1[...
66950a94f95ce65c2baea8ac710ca1f053aeb523
sandeepjrs/machine_learing
/google_developer/4_2_lession.py
1,593
3.59375
4
from sklearn import datasets iris = datasets.load_iris() X = iris.data #data is like [.6,.9, .78] --> featuere y = iris.target #label example [stosa] --> label from sklearn.cross_validation import train_test_split #splitting the data for the training test # X_train and y_train are the feature and label for traing...
91edd25a58993af74c24da626e0bc91a5175d7fa
Awesth/TweetLinkCollector
/CSVTreatment.py
640
3.609375
4
import csv def csvToDictionary(myList): with open('ListOfPeople.csv', 'r') as csvFile: reader = csv.reader(csvFile) temp = [] for row in reader: temp.append(row) myList += [val for sublist in temp for val in sublist] def saveListToCSV(myList): with open('List...
cbeed12db16dad02eccbd4cebc250813a7d62df0
wsinbol/DataStructure
/HashTable/SimplyHashTable.py
2,308
3.765625
4
# -*- coding:utf-8 -*- ''' 基于开放寻址法-线性探测的散列表 开放寻址方法: 1.线性探测 2.二次探测 3.双重散列 ''' class HashTable(object): def __init__(self, _size = 0): self._table = [None for i in range(_size)] self._size = _size def hash_function(self,key): return key % self._size def insert(self, val): # 千万别用 == if self._table[self.ha...
d9b0e9e29c42bc6d0f5a8df3c4749b41b9d37080
wsinbol/DataStructure
/Tree/binary_search_tree.py
4,926
4
4
''' 二叉搜索树 二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值 ''' ''' void BST(TreeNode root, int target) { if (root.val == target) // 找到目标,做点什么 if (root.val < target) BST(root.right, target); if (root.val > target) BST(root.left, t...
7c70b2638aefc406466c2dcdb37a1822200d0680
wsinbol/DataStructure
/LinkedList/DoubleLinkedList.py
3,074
4.0625
4
''' 双向链表 ''' # -*- coding:utf-8 -*- class Node(object): def __init__(self, data, _prev=None, _next=None): self.data = data self._prev = _prev self._next = _next class DoubleLinkedList(object): ''' 方法: insert_new_value_to_head 在头部插入新结点 insert_new_value_after_target_node 在给定结点后 插入新结点 insert_new_value_befo...
5562b6a7fb8054527541ed431767ef1facc8b3ab
wsinbol/DataStructure
/DynamicProgramming/matrix_route.py
1,014
3.65625
4
''' 要求: 从矩阵左上角出发,最终走到右下角,只能向下或者向右移动 求所经过路径的最小和! ''' import numpy as np arr = [ [1,3,5,9], [2,1,3,4], [5,2,6,7], [6,8,4,3] ] matrix = np.array(arr) row, col = np.shape(matrix) sum_arr = np.zeros((4,4)) route = [(0,0)] # 初始化第一行 sum = 0 for i in range(col): sum += arr[0][i] sum_arr[0][i] = sum # 初始化第一列 sum = ...
d3f0e28a56a18dcc5d7075fc6336301b058b371c
wsinbol/DataStructure
/BackTracking/n_queen.py
1,071
3.578125
4
import numpy as np def isValid(board, row, col): n = len(board) # 检测列是否有皇后互相冲突 for i in range(n): if board[i][col] == 1: return False # 检测右上方是否有皇后互相冲突 i = row - 1 j = col + 1 while i >=0 and j < n: if board[i][j] == 1: return False i -= 1 j += 1 # 检测左上方是否有皇后互相冲突 m = row - 1 w = col - 1 while...
b3c03635c468f1ea0d71c0e7a6c9e7b61b164148
wsinbol/DataStructure
/Math/pre_sum.py
1,524
3.59375
4
''' 要求:算出一共有几个和为 k 的子数组 前缀和 pre_sum[i]就是nums[0]到nums[i-1]的和 则 nums[i]到nums[j]的和即为:pre_sum[j+1] - pre_sum[i] ps: 这个题有点问题 ''' def sub_array_sum(nums, k): n = len(nums) sum_n = [0] for i in range(n): sum_n.append(sum_n[i]+nums[i]) print('the pre_sum:',sum_n) total = 0 for i in range(1,n+1): for j in range(i...
cb1e5d7785a9d8635c808e58eb2d2cdf29b02e5c
wsinbol/DataStructure
/Search/koko_eats_bananas.py
1,149
3.984375
4
''' Koko 每小时最多吃一堆香蕉,如果吃不下的话留到下一小时再吃; 如果吃完了这一堆还有胃口,也只会等到下一小时才会吃下一堆。 在这个条件下,让我们确定 Koko 吃香蕉的最小速度(根/小时) ''' # 第一版解法 def min_eating_speed_1(piles, hour): max_num = max(piles) speed = 1 while speed <= max_num: if can_finish(piles, speed, hour): return speed speed += 1 return max_num # 第二版解法 def min_eating_...
687e1ce328a54759e7340908b82c7f850aeaa56a
wsinbol/DataStructure
/Trie/trie.py
2,052
3.5625
4
''' @Description: Trie树 Trie 树,也叫“字典树”。顾名思义,它是一个树形结构。它是一种专门处理字符串匹配的数据结构,用来解决在一组字符串集合中快速查找某个字符串的问题。 属于多模式串匹配算法。 单模式串匹配算法,是在一个模式串和一个主串之间进行匹配,也就是说,在一个主串中查找一个模式串。 多模式串匹配算法,就是在多个模式串和一个主串之间做匹配,也就是说,在一个主串中查找多个模式串 @Date: 2020-06-22 15:35:22 @Author: Wong Symbol @LastEditors: Wong Symbol @LastEditTime: 2020-06-23 15:57:23 '''...
48a1c2d3e31a068ef03eb2860cb67ff703b97349
gina12242001/8-5-Problems
/nondestructive:destructive & Eval.py
1,023
3.71875
4
a = [1,2,3] b = a a[0] = 6 # print a, b import copy a = [1,2,3] b = copy.copy(a) a[0] = 6 # print a, b myList = [1,2,3,4,5] # [3,4,5,1,2] n = 2 [2,3,4,5] + [1] tempList = myList[2:] firstElement = myList[0:2] print tempList, firstElement elements = myList[1] print elements tempList.append(elements) print t...
d02b6a79624fec82075bc8313f5c2ebcfe69b316
cruigo93/leetcode
/medium/1379.py
1,402
3.59375
4
from typing import List import time class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode: p = original ...
c8f25d15d69e0d7761df7c88329199538b76d34b
cruigo93/leetcode
/easy/643.py
573
3.625
4
from typing import List class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: max_avg = 0 running_avg = 0 avgs = [] for i in range(len(nums)): running_avg += nums[i] if i >= k: running_avg -= nums[i-k] if (i+...
0736fe729dc75ee485be8baf44dfe1e4dd6c8fb4
cruigo93/leetcode
/january/day11.py
730
3.671875
4
from typing import List from collections import defaultdict class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: p = m q = n last = m + n - 1 while p > 0 and q > 0: if nums1[p-1] > nums2[q-1]: nums1[last] = nums1[...
d77d6eee559c566baca2268f9072e9b917162209
cruigo93/leetcode
/easy/1662.py
371
3.703125
4
from typing import List class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: s1 = "".join(word1) s2 = "".join(word2) return s1 == s2 def main(): s = Solution() word1 = ["a", "cb"] word2 = ["ab", "c"] print(s.arrayStringsAreEqual(wor...
59031a5870b4061e9c553858707a39c787c00ae7
bemsuero/python
/ex18.py
355
3.625
4
def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") def print_one(arg1): print(f"arg1: {arg1}") def print_none(): print("I got nothin'.") print_two("One", "Two") print_two_again("OneAgain", "TwoAgain")...
f813482ac60ace41af53fb72806222f841446251
Evandr0/python
/Python para Zumbis/TWP130 Maior de tres.py
445
3.96875
4
''' Faça um programa que leia três números e mostre o maior deles. Comentário de várias linhas ''' a = int(input('Digite o primeiro número: ')) b = int(input('Digite o primeiro número: ')) c = int(input('Digite o primeiro número: ')) if a>= b and a >= c: print ("O primeiro número é o maior %d" %a) elif b...
c47cec4ee62d9b2f5d79b4b21de5f80a0aae844e
gothandy/ingenuity
/ingenuity/timer/leak.py
1,886
3.546875
4
import time def leaking_suit(air_volume_with_person_in_suit, hole_size_mm2, oxygen_percentage, seconds): volume_air_lost_per_second = hole_size_mm2 * (air_volume_with_person_in_suit / 2) /100 volume_not_oxygen_lost_per_second = volume_air_lost_per_second * ((100 - oxygen_percentage) / 100) volume_of...
d17c3ae550065b6e2d9cb1fd5fd93f9647e07940
ajakaiye33/Learn_python_the_hard_way
/the_hard_lessons/ex29.py
937
3.984375
4
people = 20 cats = 30 dogs = 15 if people < cats: print("Too many cats! The world is doomed!") if people > cats: print("Not too many cats! The world is saved!") if people < dogs: print("The world is drooled on!") if people > dogs: print("The world is dry!") dogs += 5 if people >= dogs: print...
f0cbdaa6b75edc896101b5be4d3afa35453a3499
ajakaiye33/Learn_python_the_hard_way
/the_hard_lessons/function_variable.py
941
4.0625
4
def cheeese_and_crackers(cheese_count, box_of_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {box_of_crackers} boxes of crackers!") print("Man that's enough for a party!") print("Get a blanket. \n") # here the arguement were applied directly to the function print("We can just ...
78da3102efb178f2e19f937c46bb362227e5ce22
mangonval/Blackjack
/main.py
2,528
3.53125
4
from blackjack import Blackjack from dealer import Dealer from human_player import HumanPlayer def initialize_blackjack_game(): for _ in range(2): player.hand.add_card_to_hand(blackjack.get_random_card_from_deck()) dealer.hand.add_card_to_hand(blackjack.get_random_card_from_deck()) blackjack = B...
9bb6e1717ab73e323c376ca22d54f1bf96915bad
Rajnish20/Machine-Learning
/polynomial_regression.py
2,574
3.8125
4
#Polynomial Regression #importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing the data_set dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values #splitting the dataset into train and test set """from sklearn.m...
b0b7ba081383087eb76851e4c644877c3952a2e6
21ivan/first-repository
/ClassWork.py
453
3.828125
4
a=int(input('input a ')) b=int(input('input b ')) if a>=b: print ('max =', a, 'min =',b) else: print ('max =', b, 'min =',a) ############################### num = int(input('input num')) if (num%2)==0: print("parne") else: print('ne parne') ############################### num=int(input('input chislo - '...
c4f889e173b5da1afcf27bf902bde080fb9c14f4
LososAlex/encoder
/Atbash.py
618
3.671875
4
def atbash(text): alphabet = ['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'] alt_alphabet = alphabet[::-1] text = text.split() answer_text = [] for i in text: ...
809e02bced75684faeeaa8924113e8d063420bd4
suprabhatgurrala/cx4230-distribution-center
/worker.py
877
3.65625
4
import random class Worker: # Object to represent a warehouse worker def __init__(self, mean_mistake_prob=.1, mean_efficiency=10): """ Initialization function reliability: how often a warehouse worker makes a mistake that results in a package requiring rerouting ef...
72dd2e20957da6bcb1923cf08be42987fabcc0fe
Nico-Boyajian/Python-Analysis
/PyBank/main.py
2,044
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 23 10:44:06 2019 @author: nicoboyajian """ import csv import os budget_data = os.path.join('..',"Resources","budget_data.csv") total_months=0 total_profit =0 average_change=0 greatest_increase=0 greatest_decrease=0 total_difference =0 average_ch...
482f1b419b5922a3fd257006d7d49ef6939e5461
Z4MUS/CP1404_PRACTICALS
/SEM 2 PRACTICALS/prac_01/sales_bonus.py
628
3.984375
4
""" Program to calculate and display a user's bonus based on sales. If sales are under $1,000, the user gets a 10% bonus. If sales are $1,000 or over, the bonus is 15%. """ def main(): sales = float(input("Enter sales: $")) while sales >= 0: calculate_bonus(sales) sales = float(input("Enter sal...
4902869aae1e082ed26e16eead8cac7c9c83cd79
PysKa-Ratzinger/personal_project_euler_solutions
/solutions/051-075/55/main.py
542
3.75
4
#!/usr/bin/env python def reverse(n): res = 0 while(n): res *= 10 res += n % 10 n //= 10 return res def isPalyndrome(n): return n == reverse(n) def isLychrelNumber(n): it = 0 while it < 50: n += reverse(n) it += 1 if(isPalyndrome(n)): ...
a1f3b51e01e49eb08eb4476764c9eadd7c716ae8
PysKa-Ratzinger/personal_project_euler_solutions
/solutions/001-025/13/main.py
273
3.6875
4
#!/usr/bin/env python def main(): fileName = input('Input file name: ') f = open(fileName, 'r') res = 0 for number in f: res += int(number) print("If you can trust me, the number you are looking for is " \ + str(res)[:10]) main()
c00bac56c52024e75f87b9893692b58759646ade
frankma/Risk
/aggregation/src/node.py
2,150
3.546875
4
from typing import Set class Node(object): JOINER_NAME = "^" def __init__(self, name: str, parent=None, children: Set = None): self._name = name self._parent = parent self._children = children if children is not None else set() self.__name_full = None pass def get...
f9b8d084146aa98970ca3c3508a3f6f267d78d05
osbelyakova/ISW-HW-2
/task1.py
402
4.0625
4
#!/usr/bin/env python3 """Letter by letter we are looking for the smallest repeating substring""" your_str = str(input("Insert the string: ")) count_substrings = 0 i = 1 while i != len(your_str) + 1: if len(your_str) % i == 0: if str(your_str[0:i] * (len(your_str) // i)) == your_str: count_subs...
2301caf7011079c40b602c3279403702dbf03f80
wsun/abstracts
/abstract.py
2,748
3.578125
4
# CS205 Final Project # Janet Song and Will Sun # # Abstract class, represents an abstract. class Abstract: # Construct a new Abstract from the filename provided. def __init__( self, filename ): self.__path = filename #TODO: load file and process self.__title = None self.__te...
b92d1345a5a2603c02c503e0f15f2acc2dd82f2e
chrishardin/GameOfThreadsProject1
/battleship/data/player.py
1,095
3.65625
4
import ship as S class Player: def __init__(self): self.numShips = 0 # The number of ships the player currently has self.shipList = [] # List of ships the player currently has self.guesses = [] # List of coordinates the player has guessed # Creates a ship from a start an...
8978220700fcf7ed48d7b0840bebd70696ee3fd8
VRamazing/UCSanDiego-Specialization
/Assignment 2/fibonacci/fibonacci.py
359
4.15625
4
# Uses python3 # Task. Given an integer n, find the nth Fibonacci number F n . # Input Format. The input consists of a single integer n. # Constraints. 0 ≤ n ≤ 45. def calc_fib(n): if n==0: return 0 elif n==1: return 1 else: arr=[1,1] for i in range(2,n): arr.append(arr[i-1]+arr[i-2]) return arr[n-1] n...
077db2a0f5904ba96886cc827b25c8d384e7e1b7
VRamazing/UCSanDiego-Specialization
/Assignment 3/greedy_algorithms_starter_files/fractional_knapsack/fractional_knapsack.py
2,169
4.15625
4
# Uses python3 import sys # Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem. # Input Format. The first line of the input contains the number n of items and the capacity W of a knapsack. # The next n lines define the values and weights of the items. The i-th line c...
fc387002e83728b9c0104f1cdb10f63b98c947c6
LayaFlo/PythonProgramming
/PythonProgramming/4.2.While-structureWithEndingCriteria.py
159
3.890625
4
while True: var = input("Write something: ") if var == "quit": print("Bye bye!") break if var != "quit": print(var)
2238342807e7b06db4dda73176589b425db5dd2c
LayaFlo/PythonProgramming
/PythonProgramming/5.1.ReadingFile.py
201
3.828125
4
#Program which reads the entire content of the facts.txt file and prints it on the screen readfile = open("facts.txt") content = readfile.read() print("Following was read from the file:", content)
bac7b47ed9d58596004998bf1d827d0b2e5a0f1d
ScottSko/Python---Pearson---Third-Edition---Chapter-7
/Chapter 7 - Algorithm Workbench - Q # 6.py
273
4.0625
4
def main(): verifier = "n" names = ["Sapphire", "Emerald", "Topaz", "Ruby"] for string in names: if string == "Ruby": print("Hello Ruby") verifier = "y" if verifier == "n": print("No Ruby") main()
613094b2ea39227833bb2501a410b2dcedbb1d4d
ifpb-cz-ads/pw1-2020-2-ac04-team-ricardoweligton
/atividade_4_02/questao_06.py
369
4.09375
4
# 6) Modifique o programa anterior de forma que o usuário também digite o início e o fim da # tabuada, em vez de começar com 1 e 10. print("\n--------- Questao 6 --------- \n") n = int(input("Tabuada de: ")) inicio = int(input("Comecando em: ")) fim = int(input("E terminando em: ")) while inicio <= fim: print(f...
620323ff5e0c51b2c619e132e57523c07f206efc
ifpb-cz-ads/pw1-2020-2-ac04-team-ricardoweligton
/atividade_4_02/questao_13.py
590
4.28125
4
""" 13) Escreva um programa que leia números inteiros do teclado. O programa deve ler os números até que o usuário digite 0 (zero). No final da execução, exiba a quantidade de números digitados, assim como a soma e a média aritmética. """ print("\n--------- Questao 13 --------- \n") n = 0 x = 0 soma = 0 whi...
3407a0f3e24c1006014ec5f1d0cdb843bd5afb8d
natthawit-jan/project2IOT
/python.py
240
3.8125
4
mymixList = ["hey", 1, ["ValueinList1", "ValueinList2", 2 ]] for element in mymixList: if isinstance(element, list): print (element) else: print("it is not a list.") print("its okay") print ("good")
09c71013e9a36af51de74b6bd1e443adce5ca4d9
ktandon91/DataStructures
/6. Random/iterator_example.py
427
3.984375
4
class Reverse: def __init__(self, ele): self.data = ele self.index = len(self.data)-1 def __iter__(self): return self def __next__(self): if self.index < 0: raise StopIteration value = self.data[self.index] self.index -= 1 return value ...
07b2b034d9aeebd42e8e4ed1710bb42906532634
ktandon91/DataStructures
/6. Random/decorator_.py
520
3.71875
4
from functools import wraps def decorate_name(func): @wraps(func) def wrapper_function(*args,**kwargs): return "Inside wrapper {} ".format(func(*args,**kwargs)) return wrapper_function @decorate_name def function1(first_name, last_name="Tandon"): """ This is the docstring of function 1 ...
cbeb6a4b06cd9f36bf351c269ca71de0793e2081
ktandon91/DataStructures
/3. DyPro/rod_price.py
1,021
4.28125
4
""" Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obt...
529df1dbdf79b20f2cb5fd787d84da71df30bdd5
gmiles32/roleplay-game-python
/Character.py
2,207
3.890625
4
class Character: """ Represents a character, either hero or enemy, in roleplay game. Acts as convenient storage for character stats, including character name, health, and maximum amount of damage the character is capable of. """ """ Constructor for Character class. Creates character ob...
d1cec75e5655eb278c56c51ddd6faaef18af2dd4
Sajid16/Problem-Solving
/Hackerrank_Certification_Problems/reverse_words_swap_cases.py
656
4.09375
4
def reverse_words_order_and_swap_cases(sentence): result_list = [] final_sentence = "" sentence_to_word = sentence.split() sentence_to_word = list(reversed(sentence_to_word)) reversed_sentence = (" ".join(sentence_to_word)) sentence_to_char_list = list(reversed_sentence) for char in sentence...
21abe401490983c3801a5077842d24a8ad88d37d
Sajid16/Problem-Solving
/list_comprehension_hackerrank.py
436
3.53125
4
if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) result = 0 final_list = [] for i in range(x+1): for j in range(y+1): for k in range(z+1): result = i+j+k if result != n: lis...
7fd32f01d5968a760baccc8bb1303ceb5f42a7c3
monikasulik/csv-coding-task
/csv_parser/__init__.py
2,699
3.9375
4
import csv class Parser: days = ['mon', 'tue', 'wed', 'thu', 'fri'] def __init__(self, csv_file): csv_reader = csv.DictReader(csv_file) for row in csv_reader: # NOTE: Assuming the csv will always have two lines, one line # for the headers and one row of values ...
02c53c059f4263a21ad92fc8ccbb38a70b771533
ludmylasoares/PythonBrasil
/EstruturaSequencial/14_calcula_multa_excesso_pescador.py
812
3.796875
4
''' Autora: Ludmyla Oliveira Soares Data: 28/04/19 14. João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma m...
0ee4ad160731fe9c613c8db2ffd8346581515b99
ludmylasoares/PythonBrasil
/EstruturaSequencial/13_peso_ideal_por_sexo.py
784
4.09375
4
''' Autora: Ludmyla Oliveira Soares Data: 28/04/19 13. Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: Para homens: (72.7*h) - 58 Para mulheres: (62.1*h) - 44.7 >>> ÍNDICE DE MASSA CORPORAL <<< Após a realiza...
e8725b170323050344ef621295cbf3b4d53e43d0
scientific-programing-UIBK/scipro_assignments
/HW3/04_03.py
4,450
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 29 16:25:31 2020 Write a function which converts binary strings to decimal numbers. The function should handle unsigned (positive) numbers only. @author: francesc """ if __name__ == '__main__': def binary_to_decimal(in_num): import sys...
1d16c64984bdf6e68867147a027e5b5c8681f75e
savithrijayamala/Python-practice
/sum.py
146
4.09375
4
num1 = input("Enter the first number: ") num2 = input("Enter the second number: ") sum = num1 + num2 print("The sum of two numbers is: ", sum)
420624f6d72b75e4d3d7f72a891a197c16778214
denghuichao/LeetCode-py
/MinimumSizeSubarraySum.py
964
3.78125
4
class Solution(object): """ Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length un...
2dd4e11ce6207d758e2ca3d384af28353c657bad
sjgallagher2/PyLexicon
/categories.py
1,474
3.671875
4
# Categories and subcategories for words, translation examples, idioms # I think this will be easier, and sufficient... class Category: COMMON=0 PHYSICS=1 MATH=2 def get_category_name(c): if c == Category.COMMON: return "Common" if c == Category.PHYSICS: # Forgo the elif because it's not n...
3b8a4e4405be103495b8e2f97ac55ec6bf607165
WMcloud3/bankAccount
/basic.py
1,662
4.0625
4
class BankAccount: bank_name = "Ninja Savings and Loans" def __init__(self, int_rate = 0.02, balance = 0): self.int_rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount print(self.balance) def withdraw(self, amount): if self.bal...
ea632d6384e4235eb6a4cc8f3adacb3ed4e64654
iamshubhamsalunkhe/Python
/basics/string1.py
165
4.125
4
# n = input("Enter string") f=n.find('r') print(f) if f>=0 : print("r is found in string with index nmber",f) else: print("r is not found in string ")
7c5473cfdcd09d8570d3c98ba2a2aac0cb8236bf
iamshubhamsalunkhe/Python
/fileoperation/class code/exception_handling_file_handling.py
262
3.9375
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 11 17:03:09 2019 @author: Shubham """ fname=input("Enter filename with extension") try: fobj=open(fname,"r") for i in fobj: print(i) except: print("File not found or can not be opened",fname)
6d21e5935301cd19d119a3ba567b232a81a070ed
iamshubhamsalunkhe/Python
/numpy/numpy1.py
1,434
3.703125
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 17:09:59 2019 @author: Shubham """ import numpy as np data1 = [[1,2,3,4],[5,6,7,8]] print("data1 =",data1) print("the data type of data is ",type(data1)) a=np.array(data1) print("NP array is",a) print("The data type of np array a is ",type(a)) print("The data type ...
4979ce2d4a7b44bb491b5151a3acef5218a1852d
iamshubhamsalunkhe/Python
/NLP/lemmazation_Stemmer.py
1,072
3.84375
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 25 15:14:14 2019 @author: Shubham """ '''Lemmatization usually refers to doing things properly with the use of a vocabulary and morphological analysis of words, normally aiming to remove inflectional endings only and to return the base or dictionary form of a word''' ...
683354238d01811f3191a4ab9ee251c7c0131cf8
iamshubhamsalunkhe/Python
/funct_with_mult_argue/funct_with_mult_arguement.py
303
3.953125
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 14:48:40 2019 @author: Shubham """ #program to create a func with multiple arguement def newfunction(a,b,c,d): result = a*b-c+d print("The answer is ",result) newfunction(1,2,3,4) newfunction(a=1,b=2,c=3,d=5) newfunction(c=1,d,3,a=2,b=6)
82234bc9ffaa3acb0a0bb64d040ec8e249789414
iamshubhamsalunkhe/Python
/basics/Continueandbreak.py
336
4.4375
4
#continue is used to skip a iteration and jump back to other iteration """ for i in range(1,11,1): if(i==5): continue print(i) """ ''' ##break is used to break a iteration or stop a iteration at specific point for i in range(1,11,1): if(i==5): continue if(i==8): break ...
a46695b11bfa13a2d98ae213078b562f8ec2592b
iamshubhamsalunkhe/Python
/basics/day1.py
959
3.984375
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ ''' print("hello") n= input("Enter your name") print("hello your name is " , n) a=int(input("Enter a number")) b=int(input("Enter a number")) c = a+b print("The sum of two number is " , c) print("the sum is " , (a+b)) print("mean valu...
d152fdf0af08198151acdbb6c3e4af8f6e8d1061
iamshubhamsalunkhe/Python
/basics/1_hello.py
483
3.875
4
print("hello") print("welcome") #### print('hello') ## errors missing parentheses print 'hello' ##arrays is collection of similar values ## e = [1,2,3,4] ##Lists ##list can contain multiple datatype init ##dictionary ## ## info = {"Name" : "Shubham" , "Age":20 , "Edu":"BSc.I.T"} ##tuple ##tuples are immutable...
e7654e4764b524c6d6fa2bfb816735e303df1358
iamshubhamsalunkhe/Python
/basics/WhileLoopBILL.py
255
4.09375
4
total = 0 choice = "yes" while(choice=="yes"): rate = eval(input("Enter a rate :")) quantity = eval(input("Enter the quantity:")) total = (rate*quantity)+total choice=input("Wish to continue - yes/no : ") print("Your total Bill is",total)
a08cda2a12c2c104a7ca1502df2b7ea30fd05d14
frendydw/uva-online-judge-solutions
/Python/Contest Volumes (10000...)/11942 - Lumberjack Sequencing.py
485
3.640625
4
n = int(input()) print("Lumberjacks:") for i in range(n): arr = list(map(int, input().split())) flag = True if arr[0] < arr[-1]: for i in range(0, len(arr)-1): if arr[i] > arr[i+1]: flag = False break else: for i in range(0, len(arr)...
0a0546a206e3ea1f66ec7a32916fc0fc25e252cc
frendydw/uva-online-judge-solutions
/Python/Problem Set Volumes (100...1999)/575 - Skew Binary.py
301
3.671875
4
def sumOfDigits(num): num = str(num) skew = int(num) * (pow(2, len(num)) -1) if len(num) == 1: return skew return int(num[0]) * (pow(2, len(num)) -1) + sumOfDigits(int(num[1:])) while True: n = int(input()) if n == 0: break print(sumOfDigits(n))
4cf201fd8dbcde5a1ac9ec5b31c9a2a0514e3a0d
frendydw/uva-online-judge-solutions
/Python/Contest Volumes (10000...)/11332 - Summing Digits.py
315
3.640625
4
def sumOfDigits(num): num = str(num) if len(num) == 1: return int(num) return int(num[0]) + sumOfDigits(int(num[1:])) while True: n = int(input()) if n == 0: break m = n while m > 9: m = sumOfDigits(m) print(sumOfDigits(m))
9686238853726762418eb7663c9fb2c7c7e7f0f3
frendydw/uva-online-judge-solutions
/Python/Problem Set Volumes (100...1999)/579 - Clock Hands.py
292
3.9375
4
while True: clock = input() if clock == '0:00': break hour, minute = clock.split(':') hour_angle = 0.5 * (int(hour) * 60 + int(minute)) minute_angle = 6 * int(minute) angle = abs(hour_angle-minute_angle) print('{:.3f}'.format(min(360 - angle, angle)))
a535e2a1ece36f31054eb0855bfdec7509046332
frendydw/uva-online-judge-solutions
/Python/Contest Volumes (10000...)/12250 - Language Detection.py
622
3.9375
4
index = 0 while True: word = input() if (word == '#'): break if (word == 'HELLO'): print('Case {}: ENGLISH'.format(index+1)) elif (word == 'HOLA'): print('Case {}: SPANISH'.format(index+1)) elif (word == 'HALLO'): print('Case {}: GERMAN'.format(index+1)) elif (wor...
6955a9ea61a0f8d363da9d394f887d09de3b3120
ttnyoung/fastcampus_python_advanced
/myvenv/Chapter02/05.실습문제2.4.1.py
431
3.796875
4
# 실습문제 2.4.1 # word_list 에 들어 있는 문자열 중 첫글자가 # a 인 것만 뽑아서 리스트로 만드세요. word_list = ['apple', 'watch', 'apolo', 'star', 'abocado'] # 리스트 내포 사용하기 전 # result = [] # for word in word_list: # if word[0] == 'a': # result.append(word) # print(result) # 리스트 내포 사용한 후 result = [i for i in word_list if i[0] == 'a'] pr...
73d2a8ec46b94675fdaffe022b5f1dc46415e616
ttnyoung/fastcampus_python_advanced
/myvenv/Chapter05/01.CREATE_TABLE.py
449
3.625
4
# 모듈 추가 import sqlite3 # 데이터베이스 열기 conn = sqlite3.connect('Chapter05/SQL_DDL.db') # 커서 생성 cur = conn.cursor() # SQL 명령 작성 CREATE_SQL = """ CREATE TABLE IF NOT EXISTS Item( id integer primary key autoincrement, code text not null, name text not null, price integer not null ); "...
f54560b073e1c7f7d02f180d33847e943a647dcd
ttnyoung/fastcampus_python_advanced
/myvenv/Chapter02/02.문자열포매팅.py
627
3.90625
4
# 문자열 포매팅이 없다면? # 기준님 수강기간이 7일 남았습니다. name = '기준' duration = 7 message = name + '님 수강기간이 ' + str(duration) + '일 남았습니다.' print(message) # 문자열 포매팅 사용시!!! message_format = f'{name}님 수강기간이 {duration}일 남았습니다.' print(message_format) # format 메서드 사용 a = 'Hello {2} {1} {0}'.format('apple', 'pineapple', 'pen') print(a) b =...
d54773b3f32729d8076b34ada3d07c1be629e2b3
standrewscollege2018/2020-year-13-python-classwork-OmriKepes
/classes and objects python.py
1,650
4.625
5
''' This program demonstrates how to use classes and objects.''' class Enemy: ''' The enemy class has life, name, and funcations that do something.''' def __init__(self, name, life): '''This funcation runs on instantiation and sets up all attributes.''' self._life = life self._name = na...
8135b0206f4f25c97d64aeab6f43418671b8c4f9
leelatarun/rocka
/week5_2_1.py
215
3.875
4
hrs = input("Enter Hours:") rate = input("Enter the Rate:") h = float(hrs) r = float(rate) if h > 40 : reg = h*r opt = (h - 40.0) * (r * 1.25 ) pay = reg + opt else : pay= h*r print(pay)
c0250ad523fa26803a85e52eb099a24471d6d322
andri95/Verklegt1_AHERO
/Models/inputHandler.py
4,362
3.6875
4
from Models.airplaneData import AirplaneData from Models.destinationData import DestinationData from Models.staffData import StaffData from Models.voyageData import VoyageData from Models.errorHandler import ErrorHandler import datetime class InputHandler: '''The reason for the InputHandler class is to take the lo...
65d134291d801e68c6639f6238890fb96269dd30
tomerhc/colorup
/color_ops.py
2,229
4.03125
4
from collections import namedtuple from math import sqrt import os import cv2 import colortrans import re def sort_colors(color_list): """ sort colors by brightness. doing it so when i use the colors to make the powerline shell I can be fairly certain ill have light colors as foreground and dark colors...
4eff197f117ef0a0b38385aa25d1319d53358c2b
gustavojoteror/MachineLearningPython
/03_Clustering/01_Intro2Clustering.py
3,319
3.828125
4
# Introduction of clustering # # Example: customer dataset and you need to apply customer segmentation. Customer segmentation is the practice of partitioning # a customer base into groups of individuals that have similar characteristics. Stategy that allows a business to target a # specific group of customers so ast o ...
458f7caa80c6a687aa244963108c4534781725b8
Vigsam/Robotics_Using_Raspberry_Pi
/Python_Basic_Programs/001_if_statement.py
190
3.8125
4
a = 8 b = 15 c = 20 print(a) print(b) print(c) if(c > a): print("C is the greatest number!") if(c > b): print("A is the greatest number!") else: print("C is smaller")
62bbc2bf39d7d65ad320741702b60330ab5adeac
sheerlinvuong/Map-Project
/vpython/parsestring.py
397
3.859375
4
def findLargestNumber(text): ls = list() for w in text.split(): try: ls.append(int(w)) except: pass try: return max(ls) except: return None print (findLargestNumber('I saw 3 dogs, 17 cats, and 14 cows!')) print (findLargestNumber('0;-...
1d5cfde1f6d0b4ae13dddb4d892a42a50576a2eb
Will-is-Coding/exercism-python
/meetup/meetup.py
1,132
3.9375
4
from datetime import date import calendar class MeetupDayException(Exception): pass def meetup_day(year, month, day, suffix): """Return the next date of the meetup given the year, month, day name and suffix""" dayList = list(calendar.day_name) teenths = range(13, 20) dayInMonth = [] for dayI...
4873d8070a2d54482d0ea387eb1c901cfba8ef9e
Will-is-Coding/exercism-python
/pangram/pangram.py
503
4.21875
4
import re def is_pangram(posPangram): """Checks if a string is a pangram""" lenOfAlphabet = 26 """Use regular expression to remove all non-alphabetic characters""" pattern = re.compile('[^a-zA-Z]') """Put into a set to remove all duplicate letters""" posPangram = set(pattern.sub('', posPangr...
051b4c48fa6e206d83e00d81b8a6ca6a846ef7f2
jolammi/adventofcode2020
/aoc/day4/puzzle1.py
1,042
3.71875
4
import traceback def read_data(): with open("input.txt", "r") as handle: data = handle.read() data = data.split("\n\n") # separate documents to their own lists data = [i.replace("\n", " ") for i in data] # remove newlines data = [i.split(" ") for i in data] # split to sublists o...
db203855e6812c571d5316bc44e7dd740b76b8fc
rpinnola47/PYTHON
/TP 6 Fdla/EJERCICIO 3.py
151
3.78125
4
def columna(a): for i in range(0,a): print("*") medida=int(input("ingrese la altura de la columna de *: ")) resultado=columna(medida)
c0593fc5b9d1f0c56ff1039dd16fa37039fd869b
rpinnola47/PYTHON
/CLASES Fdla/clase listas.py
1,008
4.125
4
""" estrucutura de datos: listas: puede estar conformada por varios elementos, que estan organizados en "fila de cajitas" cada cajita tiene un solo valor. cada posicion tiene UN SOLO VALOR A LA VEZ pero todas esta agrupadas en una misma variable *cada caja tiene su indice(arranca desde cero) """ #crea...
2ecd5bb932b6a28b625c9b866247778edc866ff9
rpinnola47/PYTHON
/TP 6 Fdla/EJERCICIO 4.py
277
3.765625
4
def par(a): if a%2==0: par=True else: par=False return par numero=int(input("ingrese un numero ")) resultado=par(numero) if resultado==True: print("es un numero par") if resultado==False: print("no es par")
5c0a57621e60206c6999399e706f8ecb22e98056
DoubleHK/ATM-Machine
/ATM.py
5,511
3.953125
4
# The registered pin numbers are stored under pinData pinData = open("pin.txt", "r") cardData = open("cardNumber100.txt", "r") pin = pinData.readlines() card = cardData.readlines() pinList = [pin.rstrip('\n') for pin in open('pin.txt')] cardList = [card.rstrip('\n') for card in open('cardNumber100.txt')] atmData = ["Wi...
a4cc54bcc6c3f591a8c5e4367836f19f537c070b
Maryville-SWDV-610-Spring2020-4W/week-5-sorting-and-searching-questions-henryvu25
/listDict.py
674
3.9375
4
phoneList = [] phoneList.append(['Bob','555-1234']) phoneList.append(['Jane','432-7890']) phoneList.append(['Chris','653-9283']) phoneList.append(['Jill','103-4583']) phoneList.append(['Wendy','849-4638']) phoneList.append(['Marvin','757-4537']) print(phoneList) def findNumber(name): for each in phoneList: ...
1eb94d8674938e57508f7592929171af68efb996
Mkrishnaveni/python-progrms
/garbg.py
270
3.609375
4
#!/usr/bin/python class Point: def __init__( self, x=0, y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print class_name, "destroyed" pt1 = Point() pt2 = pt1 pt3 = pt1 print id(pt1), id(pt2), id(pt3) del pt1 del pt2 del pt3
336f55689625027b212637079ce53051dbd364f6
Matthew-Mullins/pathfinding
/algorithms/AStar.py
3,090
3.5625
4
from algorithms import Algorithm import math import time class AStar(Algorithm): def __init__(self, master, grid): Algorithm.__init__(self, master, grid) def lowest_f_score(self, open_set, f_score): lowest = next(iter(open_set)) for position in open_set: if f_score[position]...