blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9964a700cfd632e32891bc9bf4df4276f698cc29
sanoyo/effective-python
/chapter16/problem_code.py
629
3.90625
4
# 問題のあるコード def index_words(text): """indexの位置を返すメソッド Arguments: text 文字列 Returns: """ result = [] if text: result.append(0) for index, letter in enumerate(text): if letter == ' ': result.append(index + 1) return result address = 'Four s...
fef83b5002fc31a0a1e19fdaa54fa09af644858b
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Linked_Lists/Problem-7/sol1.py
836
4.34375
4
# Function to check if a Linked List is a Palindrome from Linked_Lists.main.linkedList import LinkedList, Element import copy def check_palindrome(ll): """ Check if a Linked List is a Palindrome Args: ll(LinkedList): The linked list to check Returns: Boolean: Indicates if linked list ...
65b397bd43150dc0d52bf94b270e9afeee170366
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Sorting_and_Searching/Problem-1/main.py
1,061
4.375
4
# Given two sorted lists, write a method to merge list b into list a in sorted order def merge(list_a, list_b): """ Merge two sorted lists Args: list_a: First list list_b: Second list Returns: List: The merged list """ # last index of list A index_a = len(list_a) - ...
ab4551b8e3f2c48066ac214970505631180725f6
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Recursion_and_DP/Problem-3/follow_up.py
1,030
4.125
4
# A magic index in an array is defined to be an index such that A[i] = i. # Given a sorted array of integers, write a method to find a magic index, if one exists, # in array A. # FOLLOW UP # What if elements are not distinct? def magic_index_follow_up(seq, start, end): """ Finds the magic index Args: ...
d96604779b97f3bf40a154d53a0980c5b27d8521
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Linked_Lists/Problem-3/main.py
960
4.1875
4
from Linked_Lists.main.linkedList import LinkedList, Element # Implement an algorithm to to delete a node in the middle of a singly linked list, # given only access to that node # TIP: This problem cannot be solved if the given node is the last node def delete_node(n): if n is not None: if n.next is not ...
fd12d99a28dd39d55f1434fba119306ce069ae96
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Arrays and Strings/Problem 7/main.py
965
3.875
4
# Write an algorithm such that if an element in an MXN matrix is 0 # its entire row and column are set to 0 def set_zeros(matrix): row = [0]*len(matrix) column = [0]*len(matrix[0]) for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: row[...
12d2b94d895596acbee15df47c7bdbac2215ce50
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Stacks_and_Queues/Problem-3/sol.py
2,816
3.921875
4
# Implement a SetOfStacks of PLATES with a popAt(index) function from stack import Stack class SetOfStacks(object): """ Class to create a list of stacks Attributes: capacity(Integer): The capacity of the SetOfStacks instance """ def __init__(self, capacity): self.capacity = capac...
dd93230105fd8e328941c85c7605cf13713f33e7
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Recursion_and_DP/Problem-3/main.py
787
4.1875
4
# A magic index in an array is defined to be an index such that A[i] = i. # Given a sorted array of integers, write a method to find a magic index, if one exists, # in array A. # FOLLOW UP # What if elements are not distinct? def magic_index(seq, start, end): """ Finds the magic index Args: seq: ...
87d02c3f94ccf9a1676a01cb9756c73c7ddeb2bc
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Linked_Lists/Problem-1/main.py
1,425
4.15625
4
# Remove duplicate elements from a linked list from Linked_Lists.main.linkedList import LinkedList, Element # SOLUTION I # TIME COMPLEXITY = O(N) def remove_duplicate(n): """ Remove duplicate elements from a linked list Args: n: Linked List instance """ if not n.is_empty(): curr =...
431bb696821ad655693b13d3077af8a7013e7242
MANOJPATRA1991/Cracking-the-coding-interview-solutions-in-Python
/Recursion_and_DP/Problem-11/main.py
2,326
4.125
4
# Given a boolean expression consisting of the symbols 0, 1, &, |, and ^, and # a desired boolean result value 'result', implement a function to count the # number of ways of parenthesizing the expression such that it evalues to # 'result'. import functools import collections import re def memoize(f): """ Minima...
ac467ee3594a75bb74635df2d7aa177d1abee5fd
svakili/lotto_picker
/test/basic_test_suite.py
1,787
3.6875
4
import unittest from lotto_picker import lotto class LottoTests(unittest.TestCase): def setUp(self): self.lotto_picker = lotto.Lotto() def test_with_chars(self): # ensures non-numeric strings are ignored. picker = lotto.Lotto() numbers_map = picker.check_numeric_strings(['bog...
c468eb6d0a0793b57bb902d48b70cd142c776737
mfouesneau/faststats
/faststats/distrib.py
11,868
3.515625
4
""" Class Distribution This class implements a distribution object that is defined by its pdf (probability density function) Interestingly, I could not find in numpy/scipy a class that could implement a distribution just from its pdf. The idea of such object is to be able to compute statistics of this distribution w...
98e69163e49a26e50d1808f71cb4b10484f807ac
nianien/algorithm
/src/main/python/leetcode/editor/cn/AddBinary.py
1,412
3.5
4
# 67.add-binary # 给你两个二进制字符串,返回它们的和(用二进制表示)。 # # 输入为 非空 字符串且只包含数字 1 和 0。 # # # # 示例 1: # # 输入: a = "11", b = "1" # 输出: "100" # # 示例 2: # # 输入: a = "1010", b = "1011" # 输出: "10101" # # # # 提示: # # # 每个字符串仅由字符 '0' 或 '1' 组成。 # 1 <= a.length, b.length <= 10^4 # 字符串如果不是 "0" ,就都不含前导零。 # # ...
e3be920099eaa4652b5901fa320c535d8a2f2167
nianien/algorithm
/src/main/python/leetcode/editor/cn/RemoveDuplicatesFromSortedList.py
1,564
3.78125
4
# 83.remove-duplicates-from-sorted-list # 存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。 # # 返回同样按升序排列的结果链表。 # # # # 示例 1: # # # 输入:head = [1,1,2] # 输出:[1,2] # # # 示例 2: # # # 输入:head = [1,1,2,3,3] # 输出:[1,2,3] # # # # # 提示: # # # 链表中节点数目在范围 [0, 300] 内 # -100 <= Node.val <= 1...
e1497613f2589a3ff08a2531f31fe213e8db372c
nianien/algorithm
/src/main/python/leetcode/editor/cn/BestTimeToBuyAndSellStockIii.py
3,192
3.5625
4
# 123.best-time-to-buy-and-sell-stock-iii # 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 # # 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 # # 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 # # # # 示例 1: # # # 输入:prices = [3,3,5,0,0,3,1,4] # 输出:6 # 解释:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。 #   随后,在第 7 天(股...
a0070dd6f10df34e81a0a1d8ae67329569f3eccb
nianien/algorithm
/src/main/python/leetcode/editor/cn/PerfectSquares.py
1,823
3.625
4
# 279.perfect-squares # 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 # # 给你一个整数 n ,返回和为 n 的完全平方数的 最少数量 。 # # 完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。 # # # # # 示例 1: # # # 输入:n = 12 # 输出:3 # 解释:12 = 4 + 4 + 4 # # 示例 2: # # # 输入:n = 1...
b4cacd659dd0301214ab1999c8478a1c775021b2
nianien/algorithm
/src/main/python/leetcode/editor/cn/SwappingNodesInALinkedList.py
1,611
3.9375
4
# 1721.swapping-nodes-in-a-linked-list # 给你链表的头节点 head 和一个整数 k 。 # # 交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。 # # # # 示例 1: # # # 输入:head = [1,2,3,4,5], k = 2 # 输出:[1,4,3,2,5] # # # 示例 2: # # # 输入:head = [7,9,6,6,7,8,3,0,9,5], k = 5 # 输出:[7,9,6,6,8,7,3,0,9,5] # # # 示例 3: # # # 输入:...
2cb149dc84b2444213111d324b3f616f8d1d34c3
NotOrca22/learning_algorithms
/1.6.3/trip.py
594
3.578125
4
import math import unittest class Trip(unittest.TestCase): def test_trip(self): costs = [] for i in range(int(input())): costs.append(float(input())) total = sum(costs) perPerson = sum(costs)/len(costs) amtPaid = 0 for i in range(len(costs)): ...
ad2f69077f2ec20ef2bd13c28cc1b96668eb5d7e
gotoc/Complete-Python-Bootcamp-1
/Advanced Functions Test/Problem 1.py
614
4.375
4
# Problem 1 # Use map to create a function which finds the length of each word in the phrase (broken by spaces) and return the values in a list. # The function will have an input of a string, and output a list of integers def word_lengths(phrase): #map(lambda w: len(w), phrase.split()) #lst = phrase.split() ...
08f373d7cb6419a4e65008cfdc1422173ee80dac
sachaMorin/neural-net
/layers.py
3,478
4.21875
4
"""Layers definition. Layers should be added to neural network instance via the NeuralNetwork.add_layer() method with desired size as parameter. ex: net = NeuralNetwork() net.add_layer(LinearRelu(100)) """ import numpy as np import math class Linear: """Linear layer parent class. Subclasses should i...
f187bc9ece77468326ffc9396d37a0566ba97854
Hyunjae-Kim/Coding-test-tutorial
/codeup_100/1065.py
140
3.734375
4
num1, num2, num3 = list(map(int, input().split())) if num1%2==0: print(num1) if num2%2==0: print(num2) if num3%2==0: print(num3)
51a633363adbb2cbd3f75533e56e73a7de4c70d3
Hyunjae-Kim/Coding-test-tutorial
/codeup_100/1045.py
168
3.59375
4
num1, num2 = list(map(int, input().split())) print('{}\n{}\n{}\n{}\n{}\n{:.2f}'.format( num1+num2, num1-num2, num1*num2, int(num1/num2), num1%num2, num1/num2))
498becff271877198b3705422bab11e337165c2b
Hyunjae-Kim/Coding-test-tutorial
/BOJ/1d_array/4344.py
214
3.515625
4
case_n = int(input()) for i in range(case_n): num, *score, = map(int, input().split()) mean_ = sum(score)/num ratio = 100*sum(list(map(lambda i: i>mean_, score)))/num print('{:.3f}%'.format(ratio))
4de0610b3b165e18bf2f79fe01b5a97eb9361e96
Hyunjae-Kim/Coding-test-tutorial
/codeup_100/1041.py
64
3.625
4
word = ord(input()) word_output = chr(word+1) print(word_output)
14f160750171ef6119aead0d6cc67fb1e062834d
Hyunjae-Kim/Coding-test-tutorial
/codeup_100/1024.py
67
3.765625
4
word = input() for s in range(len(word)): print("'%s'"%word[s])
1094f5803568b5de772f7ef274131588ec2ece8b
wei4558264/if2
/if2.py
267
4.09375
4
# else if 另外如果 age = input("你的年齡是?") age = int(age) if age < 13: print('你是國小生') elif age >= 13 and age < 18: print('你是中學生') elif age >= 18 and age <= 22: print('你是大學生') else: print('你應該是社會人士了!')
fa13e1cbe8dfac02de2ad8158b70f175e71417e3
ashshetty-prog/PredictingWDI
/prior_analysis.py
17,069
4.375
4
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns """First, we need to read the files and create pandas dataframes from the excel files.""" """ Let's list out the columns we have in the metadata """ """ Point 1: "You can judge a nation, and how successful it will be, based on how it treats it...
dc64d71862fa5ca02c6648d235e7eca745838749
giabao2807/python-study-challenge
/python-oop/method-in-python/class-method.py
410
3.578125
4
class Person: count = 0 def __init__(self, name: str, age: int): self.name = name self.age = age Person.count += 1 @classmethod def show_count(cls): """Trả lại số object trong chương trình""" print(f"Hiện có {cls.count} object Person trong chương trình") putin...
ec905576d0b86b4649999fd8ae0c441de352b7b1
giabao2807/python-study-challenge
/basic-python/string-operations.py
1,589
4.15625
4
astring = "giabao1" astring2 = 'giabao1' print(astring) print(astring2) #lenghth print("lenghth of string %d" %len(astring)) print("index of o %d" %astring.index("o")) print("count a %d" %astring.count("a")) print("cut index 2->5 %s" %astring[2:5]) print(astring[2:5:2]) #reverse astring3 = "Hello world!" print(ast...
552a7a38a32e17d7639b55e2e2ef6354205d44bc
giabao2807/python-study-challenge
/python-enhance/generator-in-python/fibonacci.py
862
3.859375
4
'''yeild hoạt động tương tự như return có chỗ trả lại giá trị cho hàm gọi ,tuy nhiên lại không kết thúc việc thực hiện hàm Mô hình hoạt động giống next của iterator => giúp nó có thể sinh ra iterator mà k cần thực thi phương thức next()''' class FibonacciIterable: def __init__(self, count=10): self.a, s...
520632bde4f2d1ce6822164e478c7e4ea4e0952b
giabao2807/python-study-challenge
/python-oop/method-in-python/instance-method.py
563
3.796875
4
#tương tự c# class Person: def __init__(self, name: str, age: int): self.name = name self.age = age def print(self, format = True): """In thông tin ra console format: có định dạng thông tin hay không """ if not format: print(self.name, self.age) ...
ea713c5c0c21a41886e263d378b585e91a06f43c
Don98/ML
/LiHongYi/week1/PM2.5.py
5,628
3.546875
4
#!/usr/bin/env python 3.6 #-*- coding:utf-8 -*- # @File : LR_Gradient.py # @Date : 2019-03-03 # @Author : 黑桃 # @Software: PyCharm import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler # 读取文件 path = "E:/机器学习/Machine_Learning_Homework/Homework2/" train = pd.rea...
b6f417501a0077f763da8fd3a9065a7cb252f4de
ParulProgrammingHub/assignment-1-devang2011
/10.py
324
4
4
pri = float(input(" Enter the principal ")) rate = float(input(" Enter the interest rate ")) years= float(input(" Enter the number of years ")) def simple_interest(pri,rate,years): simple_interest=float((pri*rate*years/100)) returnsimple_interest print(" Simple interest is ", simple_interest(pri,rate,year...
b21e96af2a899ca19829cf7cfb20714e4c3c341a
ParulProgrammingHub/assignment-1-devang2011
/11.py
349
3.8125
4
pri = float(input(" Enter the principal ")) rate = float(input(" Enter the interest rate ")) years= float(input(" Enter the number of years ")) def compound_interest(pri,rate,years): if years<=0: return pri else: return compound_interest(pri+pri*rate/100,rate,years-1) print(" Compount is ", compou...
f54503d86eebabb6bc0d84ef70ac48ffdc3e41e8
nicoleorfali/Primeiros-Passos-com-Python
/p36.py
820
4.09375
4
# Análise de tipos de triângulos print('-='*30) print(f'Analisador de Triângulos e seus Lados') print('-='*30) s1 = int(input('Digite o tamanho do primeiro segmento: ')) s2 = int(input('Digite o tamanho do segundo segmento: ')) s3 = int(input('Digite o tamanho do terceiro segmento: ')) if (s1 < s2 + s3) and ...
72b876f3362adccf0262f2de5141a93dcf700850
nicoleorfali/Primeiros-Passos-com-Python
/p49.py
1,290
4.03125
4
# Calculadora print('{:=^40}'.format(' CALCULADORA DA NICOLE ')) #para centralizar a string opcao = 0 print(''' [1] soma [2] multiplicação [3] cálculo do maior [4] novos números [5] sair ''') n1 = float(input('Informe o primeiro número: ')) n2 = float(input('Informe o segundo número: ')) opcao = int(inp...
41ef78e4b0a3b7420813393ba95d9fd04f6091fb
nicoleorfali/Primeiros-Passos-com-Python
/p61.py
616
3.640625
4
# Cadastro do Trabalhador from datetime import datetime dados = {} dados['Nome'] = str(input('Nome: ')) nasc = int(input('Ano de Nascimento: ')) dados['idade'] = datetime.today().year - nasc #também dá pra usar datetime.now().year dados['CTPS'] = int(input('Carteira de trabalho (0 se não tiver): ')) if dados['CTPS']...
d1df6e8f17f24cb004db0e3a485d99a19cd114c7
nicoleorfali/Primeiros-Passos-com-Python
/p20.py
263
3.96875
4
# Análise de strings nome_completo = str(input('Digite o seu nome: ')).strip() #strip tirando espaços indesejáveis nc = nome_completo.lower().split() if 'silva' in nc: print('Você tem Silva no nome') else: print('Você não tem Silva no nome')
292e6a05e834cded8cdccb135d52a860c5eef852
nicoleorfali/Primeiros-Passos-com-Python
/p16.py
443
3.796875
4
# Sorteio de alunos from random import choice, shuffle nome1 = input('Nome do primeiro aluno: ') nome2 = input('Nome do segundo aluno: ') nome3 = input('Nome do terceiro aluno: ') nome4 = input('Nome do quarto aluno: ') alunos = [nome1, nome2, nome3, nome4] escolhido = choice(alunos) print(f'O aluno escolhid...
9f7375e43bdc129fbfc2c2437d754deabf0a7583
nicoleorfali/Primeiros-Passos-com-Python
/p8.py
171
3.96875
4
# Programa que converte unidades - metros para centímetros e milímetros n = float(input('Digite o valor em m: ')) print(f'{n}m equivale a {n*100}cm e a {n*1000}mm')
fd8d691a52b5cd93fc177cc807e51a942e047a22
nicoleorfali/Primeiros-Passos-com-Python
/p24.py
404
3.640625
4
# Radar eletrônico: caso o usuário esteja acima de 80km/h, será multado em R$7 por km acima do limite v = float(input(('Informe a velocidade do carro em km/h: '))) if v > 80: multa = (v - 80) * 7 print(f'Usuário está acima da velocidade permitida') print(f'O valor da multa é R${multa:.2f}') else: print...
852a38a2f13f7bd5e85c942595c6ac9d7f54178d
TristaWWP/Python-programming-reference-
/Chapter-6.py
3,370
3.921875
4
""" 6-1 """ friend_info = {'first_name' : 'wenping', 'last_name' : 'wang', 'age' : '25', 'city' : 'chongqong'} first_name = friend_info['first_name'] last_name = friend_info['last_name'] age = friend_info['age'] city = friend_info['city'] print(first_name + last_name + age + city) """ 6-2 """ num = {'wwp' : '13', 'zc...
d1ce7965545bd7071087ce07f4eece51a03ac141
miniamisha/DS-in-python
/DAY3/linkedlist.py
717
3.984375
4
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def insertEnd(self, data): new = Node(data) if self.head == None: self.head = new return temp = self.head ...
761c0fae8e14295c23c533d9a9d85c511683ea92
0x2fb/DailyProgrammer
/#354 [Easy] Integer Complexity 1.py
741
3.71875
4
import math def is_prime(n): if n < 2: return False for i in range(2, int(math.sqrt(n))+1): if n % i == 0: return False return True def prime_generator(n): for i in range(n): if is_prime(i): yield i def get_factors(n): factors = [] for i in p...
b0aad9f9e2f94ddd85c1f45c79f687312f7b78c1
BurntLeftovers/cs50
/Pset6-credit.py
3,467
4.375
4
# Program should return Amex, Mastercard, Visa, or Invalid after running checks on a credit card number provided by users # There are 2 checks - first is the checksum: is it a valid credit card number # second is validation - does it conform to the pattern of one of the 3 card companies from cs50 import get_string fro...
e3e30c97e7dcb00a453014de99e03182a9bf85de
Henrysyh2000/Assignment10
/hash_str.py
929
4.3125
4
def hash_str(string): """ return a interger hash value for the given string. you should follow the hash function property: 1. hash same thing gives the same result. 2. hash different thing should give different result. The more different, the better. :param string: the string to be ...
f06f54bf6acff37ca71907a7d31da70f3d2c61bc
julgq/platzi-curso-intermedio-python
/list_and_dicts.py
597
3.671875
4
def run(): my_list = [1, "Hello", True, 4.5] my_dict = {"firstname": "Facundo", "lastname": "Garcia"} super_list = [ {"firstname": "Facundo", "lastname": "Garcia"}, {"firstname": "Pepe", "lastname": "Martinez"}, {"firstname": "Samuel", "lastname": "Amauri"}, {"firstname": "Abel", "lastname": "Jimnez"}, {"...
a9be0f22e545f4bdbed3331cbaa43ea72c16dffc
Pablo404/lab
/python/prueba2.py
1,283
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 23:32:26 2019 @author: Celad """ nominas = [1900, 2000, 1800, 2400, 1700, 1950, 2000, 1806, 2400, 1700] gasto_mensual=sum(nominas) gasto_anual=gasto_mensual*12 #print(gasto_mensual) #print(gasto_anual) #print(max(nominas)) #print(min(nominas)) #p...
c36d2b3b077ea67e2c6702665c3af1b1c5a00f2e
ainarejos/Python
/PytA3/Gos.py
1,366
3.859375
4
class Gos: def __init__(self, energia, hambre, estado): self.energia=energia self.hambre=hambre self.estado=estado def menjar(self, cantidad): if (self.estado=="famolenc"): for x in range(cantidad): if self.hambre>0: self.hambre=se...
a2533c8e0f29234ef2dd193f23b83357f94733d7
MayankShah1/Algorithms
/Sorting-Algorithms/RandomSelect.py
625
3.90625
4
# import QuickSort to use partition function import RandomizedQuicksort # Quick Select function def quickselect(array, low, high, i): ''' (list of int, int, int, int) -> int Returns the i_th smallest element in array. >>> quickselect([4, 1, 3, 2, 5], 0, 4, 2) 2 ''' if low >= high: ...
5ccb88a5ffb028e2dd5237b5590f9c45af7095af
wangxiaolinlin/1803
/11.day/名片系统作业.py
351
3.796875
4
list = [] dic = {} i = 0 while i < 3: name = input("请输入姓名") age = int(input("请输入年龄")) six = input("请输入性别") heigt = int(input("请输入体重")) i+=1 dic["name"]=name dic["age"]=age dic["six"]=six dic["heigt"]=heigt list.append(dic) print(list) for o in list: for k,v in i.items(): print("%d:%d"%(k,v))
abc6b64022789015fc57bba40994d07fb85b5e10
wangxiaolinlin/1803
/高级1803/03day/隔壁老王.py
2,078
3.734375
4
#创建人类 class Person(): def __init__(self,name): self.name = name self.gun = None self.hp = 100 def zhuangzidan(self,danjia,bullet): danjia.addBullet(bullet) def zhuangdanjia(self,gun,danjia): gun.addDanJia(danjia) def takeGun(self,gun):#老王拿枪 self.gun = gun def openGun(self,diren):#老王开枪 #拿到一发子弹 if di...
9c95777515ce7f57afe5c40d59db41a486feef7e
wangxiaolinlin/1803
/高级1803/06day/异常.py
324
3.90625
4
try: num = int(input("请输入整数:")) result = 8 / num print(result) except ValueError: print("请输入正确的整数") except ZeroDivisionError: print("除0错误") except Exception as result: print("未知错误 %s"%result) else: print("正常执行") finally: print("执行完成,但是不保证正确")
9ce58f754770ec1eec7533e7d825708ae6ee8591
wangxiaolinlin/1803
/高级1803/06day/多态.py
489
3.703125
4
class Dog(object): def __init__(self,name): self.name = name def game(self): print(self.name+"蹦蹦跳跳的玩耍...") class XiaoTianDog(Dog): def game(self): print(self.name+"飞到天上去玩耍") class Person(object): def __init__(self,name): self.name = name def game_with_dog(self,dog): print("%s和%s快乐的玩耍..."%(self.name,dog.n...
caa1f9c112c928b69e563a604cf2ff32e14a13a4
j-u-n-i-o-r/malep2007
/ASSIGNMENT 1 FOR TELLING DATE OF BIRTH.py
402
4.0625
4
import calendar age= int(input("age:")) date= int(input("Date of Birth:")) month=int(input("month of Birth:")) current_year = int(input("current year:")) year_of_birth = current_year-age day_of_birth = calendar.weekday(year_of_birth,month,date) day_string = calendar.day_name[day_of_birth] print("YOU W...
54da82e98520b93ff0854c1c1650aac357d0f317
Nikkolathi/holbertonschool-higher_level_programming-2
/0x07-python-test_driven_development/3-say_my_name.py
544
4.59375
5
#!/usr/bin/python3 """ A function that prints My name is <first name> <last name> """ def say_my_name(first_name, last_name=""): """ A function that prints My name is <first name> <last name> """ str_msg1 = "first_name must be a string" str_msg2 = "last_name must be a string" if (is_str(first_...
5d99a3b0de832051acfd4a867009442ce3302dc0
Nikkolathi/holbertonschool-higher_level_programming-2
/0x03-python-data_structures/7-add_tuple.py
400
3.703125
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): tuple_a = validate_tuple(tuple_a) tuple_b = validate_tuple(tuple_b) return ((tuple_a[0] + tuple_b[0], tuple_a[1] + tuple_b[1])) def validate_tuple(tup=()): size = len(tup) if (size == 0): return ((0, 0)) if (size == 1): ...
84d6f7e1769b7b864966b93de261702397c1abac
Nikkolathi/holbertonschool-higher_level_programming-2
/0x04-python-more_data_structures/2-uniq_add.py
188
3.765625
4
#!/usr/bin/python3 def uniq_add(my_list=[]): sum = 0 unique_list = dict(zip(my_list, ['unique'] * len(my_list))).keys() for e in unique_list: sum += e return (sum)
311f7c6e3ee7b44cd9e776b6732cb6524f3494f7
Nikkolathi/holbertonschool-higher_level_programming-2
/0x07-python-test_driven_development/2-matrix_divided.py
1,498
4
4
#!/usr/bin/python3 """ Divides all elements of a matrix with validations. """ def matrix_divided(matrix, div): """ Matrix division by a scalar returns Matrix (as the movie but in reverse) """ size = len(matrix[0]) type_msg = "matrix must be a matrix (list of lists) of integers/floats)" siz...
5d7c6aadbf404f85842cc90b7f6eaef071e7b3c3
harshavardhini00/python_files
/prog/grade.py
358
3.921875
4
score = input("Enter Score: ") try: h=float(score) except: print("enter a number") quit() if h>=0.0 and h<=1.0: if h>=0.9: print("A") elif h>=0.8: print("B") elif h>=0.7: print("C") elif h>=0.6: print("D") elif h<0.6: print("F") e...
6662ab369beedc6c0a407ba0f74646d1e05a7a46
harshavardhini00/python_files
/prog/split.py
290
3.90625
4
fname = input("Enter file name: ") fh = open(fname) count = 0 for lines in fh: lines=lines.rstrip() if lines.startswith('From:'): d=lines.split() print(d[1]) count=count+1 print("There were", count, "lines in the file with From as the first word")
b39d08eeaff087ff40ab38f5850b08f47405e4ba
dg183/pythonpython
/components/Snake.py
3,269
4.03125
4
# Assume a standard co-ordinate grid where # the bottom-left corner is (0, 0), and # co-ordinates increase as you go up or # right. # # If you take a step `up` then your x # co-ordinate doesn't change, and your y # co-ordinate increases by 1, therefore: # UP = (0, 1) # # Similarly: # DOWN = (0, -1) # LEFT = (-1, 0) # ...
7f2b84f3b35054ca986daa981c5cd8db66ffcf5c
jailsonpj/pythonico
/cap11/exe11.1.py
141
3.65625
4
aux = { } for linha in open('words.txt'): (nome,valor) = linha.split(' ') if nome not in aux: aux[nome] = valor print(aux)
d697669fafcf6a7e82db5b7d2a1a2c2b6cbed5c4
ezair/Crytrography-Ciphers
/squares.py
1,383
4.03125
4
''' Eric Zair squares.py Description: This program calculates the squares of a given p, q, and n value ''' #calulate the lengendre of any given number. #returns an integer. def legendre(number, mod_value): if pow(number, (mod_value-1)/2, mod_value) == 1: return 1 else: return -1 #just prints out squares a...
d4568c445fb4f09ad1c254510a619b57d933be18
MrNullPointer/AlgoandDS
/LeetCode/Problem19.py
1,091
3.890625
4
''' Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. ''' # Definition for singly-linked list. # class ListNo...
aa513a4401725604cbcc11c9615b576584f6a36e
MrNullPointer/AlgoandDS
/LeetCode/Problem4.py
917
3.96875
4
# There are two sorted arrays nums1 and nums2 of size m and n respectively. # # Find the median of the two sorted arrays. The overall run time complexity sho # uld be O(log (m+n)). # # You may assume nums1 and nums2 cannot be both empty. # # Example 1: # # # nums1 = [1, 3] # nums2 = [2] # # The median is 2.0 # # # ...
4887a07b8cdb98d14a6abe5b5c7dd4be563073ba
MrNullPointer/AlgoandDS
/Udacity_NanoDegree/Recursion_revisited/tower_of_hanoi.py
414
4
4
def tower_of_Hanoi(num_disks): """ :param: num_disks - number of disks TODO: print the steps required to move all disks from source to destination """ return towers(num_disks,'1','2','3') def towers(num_disks,source,aux,dest): if num_disks <= 0: return towers(num_disks-1,source,dest...
8d998fbfbe33ee2ee2dd2ca51f03c0e4c4b49300
MrNullPointer/AlgoandDS
/Udacity_NanoDegree/Recursion/sum_array.py
326
3.765625
4
def sum_array(arr): if len(arr) == 1: return arr[0] return arr[0] + sum_array(arr[1:]) # def sum_array(arr,index): # if len(arr) - 1 == index: # return arr[index] # return arr[index] + sum_array(arr,index + 1) arr = [1,2,3,4,5,6,2,3,4,5,545,6,6,76,66,454,5,4,43,3,4,5] print(sum_array...
a2d4936a84613ce1b8a2e0a53a4ce04ce787715a
MrNullPointer/AlgoandDS
/Udacity_NanoDegree/Linked_Lists_2ndAttempt/linked_list_practice.py
2,400
4.125
4
''' . Append data to the tail of the list and prepend to the head . Search the linked list for a value and return the node . Remove a node . Pop, which means to return the first node's value and delete the node from the list . Insert data at some position in the list . Return the size (length) of the linked list ''' c...
145a0d34e692dd66fdfdf7e74dcc3e17fd4df7e0
MrNullPointer/AlgoandDS
/Udacity_NanoDegree/Data_structures_Revisited/LinkedListRevisited.py
1,892
4.1875
4
''' Implementation of a singly linked list ''' # class Node(object): # def __init__(self,val = None): # self.val = val # self.next = None # # def set_val(self,val): # self.val = val # def get_val(self): # return self.val # # def set_next(self,node): # self.next =...
3e70c1994503518e0903d2e6e95647286a6e2cff
MrNullPointer/AlgoandDS
/Udacity_NanoDegree/Trees/traverse_a_tree.py
1,692
3.984375
4
class Node(object): def __init__(self,value = None): self.value = value self.left = None self.right = None def get_value(self): return self.value def get_left_child(self): return self.left def get_right_child(self): return self.right def set_value(se...
49161aae0e2e770d5c00fd359d5b30a8c443e918
plus44/hcr-2016
/src/laptop/enum.py
1,008
3.890625
4
#! /usr/bin/python ''' Provides enumerated variable types to the laptop ''' # STANDARD PYTHON IMPORTS # PYTHON LIBRARIES # USER LIBRARIES # GLOBAL VARIABLES # CLASSES # FUNCTIONS def enum(*sequential, **named): ''' Enables the use of enumerated types in python. Returns an Enum() type, the lookup of which retur...
d9b589fccc551de57bb8dabea6a90fa7a0b1055a
plus44/hcr-2016
/src/pi/cam_test.py
1,996
3.609375
4
""" Takes a picture using the RasPi camera, using the LED flash """ # STANDARD PYTHON IMPORTS import os import time import picamera # EXTERNAL LIBRARY IMPORTS import RPi.GPIO as GPIO # GLOBAL VARIABLES FLASH_PIN=4 SLEEP_TIME=3 # seconds PHOTO_DIR_REL='../photo' # Relative to this file's location # CODE AND CLASSES ...
332b5df8507707f7137699e578ffe7badcab3f64
PratikJarande-GSLab/Python-Snippets
/lib/Snippets/CustomExceptions.py
3,733
4.28125
4
""" This is an example of Custom Exception Class. A custom exception class can be declared by inheriting the `Exception` Class. Hierarchy can be achieved by inheriting in the right order. """ class Point(Exception): """ Raise some exception related to a point """ def __init__(self, *args, **kwargs): #...
28a28f3aa15ecebf27167e8b4e3dc71e681dad56
asherniu/CS-263
/CNN/label.py
1,600
3.640625
4
import pandas as pd #Read in the training datafile cols = ["Date", "Tweet"] train_data = "C:/Users/travi/OneDrive/Documents/UCLA/CS263/Final Project/PracticeData/filtered_final.csv" df = pd.read_csv(train_data, header=0, names=cols, encoding="latin-1") #Remove nulls that stop further preprocessing df.dropna(i...
edc73632335cbf58d3334937c83dfff190af19ad
FlorentinoBarrientos13/ECDLR-Kiosk-Scripts
/csvFormatter.py
4,550
3.90625
4
import os,csv ## inits the program def main(): print ("Files in this folder\n") print (os.listdir(os.getcwd())) filename = input("Enter file name\n") read_and_create_new_csv(filename) print("File made. Check the folder name formatted for your new file") ##Takes the csv file, formats it and create...
24614005cd41266af635b51583d8dba3e5567313
Jeysi2004/GRUPO-5
/DISCOS.py
1,584
3.8125
4
precio= input("PRECIOS UNITARIOS: \n 1-Rock=63.00" "\n 4-Salsa=56.00" "\n 3-Pop=87.00" "\n 5-Folclore=120.50") marca=input("Compra(Salsa, Rock, Pop, Folclore): ") costo=float(input("Precio Unitario: ")) cant=int(input("Cantidad de discos: ")) if cant==4: ...
67791f89c6b45c89ec1c2a3a9967903d749e4fef
nushell/nu_scripts
/benchmarks/gradient.py
521
3.734375
4
# this script will print a blue gradient on the screen # First: # pip install ansicolors from colors import * height = 40 width = 160 stamp = "py" for line in range(0, height): row_data = "" for col in range(0, width): fgcolor = 2 + 2 * col if fgcolor > 200 and fgcolor < 210: ...
ee51b940bd6ae79c6c891fee0db84fb2e12d396f
skact/CodePractice
/RockPaperScissors.py
754
4.03125
4
import random yourchoice = int(input('Rock(1), Paper(2), Scissors(3)! ')) computer = random.randint(1,3) if yourchoice == computer: print('Tie! ') else: if yourchoice == 1: if computer == 2: print('You Lose! Maybe next time my dude ') else: print('Congrats! You Win! Ch...
7751aba614d8a260a78e7752a8262861215a9f13
Astridmeng/Learn-python-Friendship-Tester
/2.py
280
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ageDifCal import getAgeDif age1 = int(raw_input("insert your age1:")) age2 = int(raw_input("insert your age2:")) ageDif=int(getAgeDif(age1,age2)) if ageDif <= 12: print("you two can be friends") else: print "opps"
3e2acbcbd836444fb07b6ca578155378fd19eea0
sarahmarie1976/cs-guided-project-problem-solving
/src/06_csSumOfPositive.py
1,041
4.15625
4
""" Given two strings that include only lowercase alpha characters, str_1 and str_2, write a function that returns a new sorted string that contains any character (only once) that appeared in str_1 or str_2. Examples: csLongestPossible("aabbbcccdef", "xxyyzzz") -> "abcdefxyz" csLongestPossible("abc", "abc") -> "abc" ...
96ee28f4afeb5990beb4c139ec4be623473ba6b7
qy2205/regAnalyst
/regression.py
7,909
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: ericyuan """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import linear_model from sklearn.model_selection import cross_validate from pykalman import KalmanFilter class CRESULT: '''class for ...
e957938d2f1365b4fc9224cc3b87389e2d99b6bb
unnoticable/Python-for-Everybody
/Programming4Everybody/week7.py
575
3.96875
4
# Assignment 1 # Use words.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) for line in fh: line = line.rstrip() t = line.upper() print t # Assignment 2 # Use the file name mbox-short.txt as the file name fname = raw_input("Enter file name: ") fh = open(fname) count = 0 summ = 0...
cdc0ef13a52a3b36b96f01b44e358a059f9808ae
unnoticable/Python-for-Everybody
/Programming4Everybody/week6.py
1,569
4.0625
4
fruit = "banana" letter = fruit[1] print letter letter = fruit[0] print letter len(fruit) length = len(fruit) last = fruit[length - 1] print length print last print fruit[-2] # Traversal # while index = 0 while index < length: letter = fruit[index] print letter index = index + 1 index = length - 1 while ...
14a5407693de13d3b1079d505fc2ae739531a93b
NaokiMaeda/PythonPractice
/Basic/NumericExample.py
202
3.84375
4
# -*- coding: utf-8 -*- x = 100 y = 30 print(x + y) # 足し算 print(x - y) # 引き算 print(x * y) # 掛け算 print(x / y) # 割り算 print("足し算 = " + str(x + y)) # 数値→文字列
b2534d83f3a8bf84fc8cd35c41087fb5139d304b
benjimr/Basic-RSA-Encryption
/RSA.py
1,067
3.890625
4
# Ben Ryan # RSA Encryption import random import math def main(): #using small sample numbers p = 17 q = 11 n = p * q t = (p-1) * (q-1) e = getCoprime(t) d = getPrivateKey(e, t) public = (n, e) private = (n, d) ciphertext = applyKey(public, input("Enter text to be encrypted\n")) plaintext = appl...
56ca8ae4180900c606ee1e54ff2b844c97d4571d
acepaitis/algo
/python/MergeSort.py
1,302
3.6875
4
import math def merge(arr, start, middle, end): nLeft = middle - start + 1 nRight = end - middle leftArr = list(range(nLeft + 1)) rightArr = list(range(nRight + 1)) for iLeft in range(0, nLeft): leftArr[iLeft] = arr[start + iLeft] for iRight in range(0, nRight): rightArr[iRight...
116c6626c3885fd5be62bc7b5720e60013761a1d
dev-11/cryptography
/Tests/Algorithms/test_affine_cipher.py
1,721
3.765625
4
import unittest import string from Algorithms import AffineCipher class AffineCipherTests(unittest.TestCase): def test_encrypt_returns_correct_cipher(self): plain_text = 'abcd' alphabet = string.ascii_lowercase a, b = 1, 1 cipher = AffineCipher().encrypt(plain_text, alphabet, a, b)...
06072a0b35078312b85d632e3917416c286fe9cb
dev-11/cryptography
/Tests/Algorithms/test_autokey_cipher.py
1,789
3.78125
4
import unittest import string from Algorithms import AutokeyCipher class AutokeyCipherTests(unittest.TestCase): def test_generate_key_generates_correct_key_when_keyword_is_shorter_than_plain_text(self): plain_text = 'ATTACKAT' keyword = 'L' key = AutokeyCipher().generate_key(keyword, plain...
00e29e7d8386dd0bce5f8634eabad4c491347977
zacharia/project-euler
/e38.py
2,949
3.984375
4
#!/usr/bin/python import math #store the digits we want to pandigital about as a string digits = "123456789" #a faster method to compute the desired permutation without iterating #through all the possibilities. It generates the permutation directly. def fast_nth_perm(digits, n): #temporary storage variables ...
8553d9d9d8a46230c5018eddf6de64ca327ccf06
zacharia/project-euler
/e40.py
2,236
4.34375
4
#!/usr/bin/python import math # A much faster than brute force approach to getting the nth digit of # the irrational number. It counts up in orders of magnitude, and then # extracts the nth digit. def get_nth_digit(n): # this is how many digits long the current numbers are (starts at # 1 for 1,2,..,9; then i...
b304bf463b3873b2cf53f0e01fee359f9059154a
zacharia/project-euler
/e04.py
663
3.796875
4
#!/usr/bin/python from math import * num1 = 999 num2 = 999 def is_palindrome(num): num_string = str(num) half_length = int(ceil(len(num_string) / 2.0)) for i in range(0, half_length): #print "%d: does %c == %c?" % (i, num_string[i], num_string[len(num_string) - i - 1]) if num_string[i] !=...
cc3283542bbe9ef1867f16c16f9c3732fc0ca0a5
zacharia/project-euler
/e17.py
2,404
3.71875
4
#!/usr/bin/python from math import * number_length_ones = {"0" : 0, "1" : 3, "2" : 3, "3" : 5, "4" : 4, "5" : 4, "6" : 3, "7" : 5, "8" : 5, ...
6345c5670d7f25ae21dfc56b1cf3fa0b68d68e88
estewart1/Python
/palindrome.py
172
4
4
def is_palindrome(string): string = str(string) if (string == string[::-1]): return True else: return False st = 123456 print is_palindrome(st)
8b0597b1bed02bcd2c781a6743145e2737ec6bec
estewart1/Python
/summy.py
169
3.984375
4
def summy(string_of_ints): return sum(int(n) for n in string_of_ints.split()) strofints = (" 1 2 3 ") print summy(strofints) #Codewars #Find sum of numbers in a list
16fb08013b882e7f714d877e47adf1ea5c3b8d26
AlexRax277/Lesson_7_tasks_1-4
/project_1.py
5,903
3.703125
4
class Human: def __init__(self, name, surname): self.name = name self.surname = surname self.grades = {} def rate_hw(self, person, course, grade): if grade in range(10): if course in person.grades: person.grades[course] += [grade] else: ...
65dd17b06a63647a912c5ceaeca956ed317e4749
huandoit/pyStudy
/python3-cookbook/Chapter1/1.6.py
936
3.9375
4
# -*- coding: utf-8 -*- """ @Time : 2020/3/17 15:39 @Author : WangHuan @Contact : hi_chengzi@126.com @File : 1.6.py @Software: PyCharm @description: 实现字典中的键映射多个值 """ from collections import defaultdict d = defaultdict(list) d['a'].append(1) d['a'].append(2) d['a'].append(3) for key in d.keys(): print(key,...
80007a2e69eec2bb1003e3f6f9607e637a78812b
huandoit/pyStudy
/leetcode/array/简单/35. 搜索插入位置 - 简.py
663
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode-cn.com/problems/search-insert-position/submissions/ 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 示例 2: 输入: [1,3,5,6], 2 输出: 1 """ ''' 思路一: 使用list内置函数 ''' def searchInsert(self, nums, target)...
3a349d593b1e90f235af3ea152f62c19c286e36c
huandoit/pyStudy
/leetcode/array/简单/217. 存在重复元素.py
864
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 给定一个整数数组,判断是否存在重复元素。 如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。 示例 1: 输入: [1,2,3,1] 输出: true 示例 2: 输入: [1,2,3,4] 输出: false 示例 3: 输入: [1,1,1,3,3,4,3,2,4,2] 输出: true ''' ''' 思路一: 哈希表,依次遍历数组,将已遍历的数组存入字典中,遍历下一个数时与字典中的键进行对比,存在表示有重复项,不存在则是没有 ''' def containsDu...
7e1381e6363581393167823297ba99372275d696
doungge/-
/3.py
838
4.03125
4
## set, get 메소드를 사용하는 이유는 외부로부터 변수값에 직접적으로 접급하는 것을 막기 위해서다. class cal(object): def __init__(self, v1, v2): if isinstance(v1,int): self.v1=v1 if isinstance(v2,int): self.v2=v2 def add(self): return self.v1+self.v2 def subtract(self): return self.v1...