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
3b9c14de993878342e89d659c501c39b27078042
joelstanner/codeeval
/python_solutions/SIMPLE_SORTING/SIMPLE_SORTING.py
873
4.53125
5
""" Write a program which sorts numbers. INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Input example is the following 70.920 -38.797 14.354 99.323 90.374 7.581 -37.507 -3.263 40.079 27.999 65.213 -55.552 OUTPUT SAMPLE: Print sorted numbers in the following way. Please note, t...
428be472613d5a4850ca2b6ebee885b0e6887f41
mrska/iSA_Python
/lessons/day02.py
863
3.9375
4
# suma = 2+2 # print(suma) # print(2+2) # # # better to use first option # # python needs a new line at the end of the file, pep8 # # print("###########################################################################") # # # KALKULATOR # #first_number = int(input('First number: ')) # #second_number = int(input('Second ...
53c0fca2db0d25b2bfdf1b0c65f4de484863fe4c
mrska/iSA_Python
/homeworks/day3/draw_rectangle.py
658
3.6875
4
def draw_rectangle(): # Rysowanie prostokąta o zadanych wymiarach height = input("Podaj wysokosc prostokata: ") width = input("Podaj szerokosc prostokata: ") if height.isdigit() and width.isdigit(): widthMod = int(width) - 2 heightMod = int(height) - 2 if heightMod > 198 or w...
fd244a957274294aee18ab171798048d4857fdcc
mrska/iSA_Python
/homeworks/day3/check_leap_year.py
444
3.78125
4
def check_leap_year(): # Sprawdzanie, czy podany rok jest rokiem przestępnym rok = input("Podaj rok: ") if rok.isdigit(): rok = int(rok) if (rok % 4 == 0 and rok % 100 != 0) or rok % 400 == 0: print("Rok " + str(rok) + " jest rokiem przestępnym") else: print...
1edd8b27b6fc78a679067daa01e6ad7ae9c99ff7
mrska/iSA_Python
/homeworks/day3/list_as_table.py
1,979
3.71875
4
# na podstawie https://pynative.com/python-accept-list-input-from-user/ def list_as_table(): listaUzytkownika = input("Wpisz elementy listy rozdzielone spacja, a listy zagnieżdżone rozdzielone \'-\' ") # np aaaa-a a-b-c aa1 1-2 lista1 = listaUzytkownika.split() lista2 = list() for i in range(0,len(...
660f6a25ad6e25bd977f257e6c118ffa20cd2eea
Satyam52/M.L
/Self/02_Various_Regressions/Section 6 - Simple Linear Regression/practise.py
1,227
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sat May 9 20:52:12 2020 @author: Mr. AKG """ # Simple Linear Regression import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values # Spli...
3da83ba4db37feeac8f9582d721a90f59cbe5fb8
MattLiangYH/Python-Games
/TicTacTo_A.I._version_2.0_beta.py
8,731
3.671875
4
grid1 = [" "," "," "] grid2 = [" "," "," "] grid3 = [" "," "," "] superlst = [grid1,grid2,grid3] print(" "+"c1","c2","c3") print("r1",grid1) print("r2",grid2) print("r3",grid3) tracker = 0 print("Human = O, computer's marker is X") testrand = 0 def move_scanner_bfs(i,j,superlst): if superlst[i].count("O") == ...
73a4fd33c4ba47ff95489c3f92024cef87e498d0
HangZhongZH/Sort
/荷兰国旗问题.py
723
3.546875
4
import random def GenerateRandomArray(length): arr = [] for i in range(length): arr.append(int(random.random() * 100)) return arr def partition(arr, num, l, r): curr = l less = l - 1 more = r + 1 while curr < more: if arr[curr] < num: less += 1 arr[c...
9dcbadb7b02a2aa9a6483479fbf75a71579e5b59
Dorga/PythonTutorial
/15MethodOverloading.py
368
3.609375
4
__author__ = 'jbowman' # https://pythonspot.com/method-overloading/ class Human: name = '' def __init__(self, name=None): self.name = name def sayHello(self): if self.name is not None: print('Hello ' + self.name) else: print('Hello') obj = Human() obj.s...
ada62a229835b5ac9d961bddde0cfef1a290ccda
Dorga/PythonTutorial
/19FactoryMethod.py
543
3.765625
4
__author__ = 'jbowman' # https://pythonspot.com/factory-method/ class Car(object): def factory(type): if type == "Racecar": return Racecar() if type == "Van": return Van() else: assert 0, "Bad car creation: " + type factory = staticmethod(factory) ...
76829bb3d375f31cfbd39dc7ba5216d24f9ae872
chasegan/pixiepython
/pixiepython/utils.py
3,391
4.4375
4
import math import datetime as dt import numbers def is_a_digit(char): """ Check if the provided character is a digit. Returns a boolean result. """ if (char == '0' or char == '1' or char == '2' or char == '3' or char == '4' or char == '5' or char == '6' or char == '7' ...
02d06baf8c684cee55e0d2c2c4b7f13fcd3df8e7
qcxu/Python-Course-Projects
/Lab 6/People_Database.py
623
3.8125
4
__author__ = 'QiongchengXu' import sqlite3 DATABASE_NAME = "Product.db" def main(): insert_record(1, "body wash") retrieve_all_records() def insert_record(pid, name): conn = sqlite3.connect(DATABASE_NAME) sql = "insert into products (product_id, product_name) values ({0}, '{1}')".format(pid, name)...
97f7231f5203ec5ab0da2e7e7a32aa482f72d527
qcxu/Python-Course-Projects
/Assignment 2/CompanyVehicle.py
1,481
3.84375
4
__author__ = 'QiongchengXu' B_BASE_CHARGE = 40 B_MILEAGE_CHARGE = 0.25 D_BASE_CHARGE = 60 D_MILEAGE_CHARGE = 0.25 def main(): code = raw_input("Please enter the customer's classification code: ") rent_days = int(input("Please enter the number of days the vehicle was rented: ")) begin_odometer = int(input...
37739ab42bf729db30d26ee42905b66d1688bd49
qcxu/Python-Course-Projects
/MidtermReview/name.py
281
3.5
4
__author__ = 'QiongchengXu' def main(): print int(2.1+3.7)/2.0 name1 = raw_input("name1: ") name2 =raw_input("name2: ") compare_names(name1, name2) def compare_names(name1, name2): if name1 < name2: print name1 else: print name2 main()
71596007d745eddaeedc21ea3cd9bca66f557c96
ihui/lou
/calculator1.py
627
3.6875
4
#!/usr/bin/env python3 import sys d = sys.argv[1] try: Sa = int(d) except ValueError: print("Parameter Error") if Sa < 3500: tax = 0 else: dS = Sa - 3500 if dS <= 1500: tax = dS * 0.03 elif (dS > 1500 and dS <= 4500): tax = dS * 0.1 - 105 elif (dS > 4500 and dS <= 9000): ...
e45e57bee83b2f2d7ddf87813f73e4f07f145cc2
ramonemiliani93/LifeGo
/Control/pwm.py
1,024
3.625
4
import RPi.GPIO as GPIO #Set mode for GPIO class PWM: """ PWM Controller outputs the pulses for the motors to achieve the desired temperature """ def __init__(self, frequency, cycleStart, cycle, output): self.frequency = frequency self.cycleStart = cycleStart self.cy...
bf01eeaa2a5c8594ee5d7e317b8077ce1f89969f
sazakku/Ejercicios_python
/practice_platzi/binary_search.py
342
3.703125
4
target = int(input("ingresa un numero: ")) epsilon = 0.01 bajo = 0.0 alto = max(1.0, target) response = (alto + bajo) / 2 while abs(response**2 - target) >= epsilon: if response**2 < target: bajo = response else: alto = response response = (alto + bajo) / 2 print(f'la raiz cuadrada de {ta...
78ef9fcbebe000347e316144e58e8b527c7791a5
souviksaha97/Data-Science-Lab
/Data Structures and Algorithms/Data Structures/Stack.py
1,561
3.609375
4
""" Created on Mon May 6 2019 @author: Nodar Okroshiashvili """ """ Stack is a type of linear data structure, where data is organized on top of each other in a form of a stack First element in the stack is placed ath the bottom of the stack, second element is placed on top of first element and this procedure c...
9be6ad545291177e3e895d85c3f3c261efdfe81e
Ahmed42/Graph_algos
/shortest_path.py
3,093
4.25
4
def shortest_path(graph,source, destination = None): ''' Takes a graph, a source node, a destination node and returns the shortest path from the source to the destination node. All nodes are represented by strings. The graph takes the shape: graph = { node : { adjacent nodes and the costs of di...
bf45b99bf95663416734e9f6b1ac547b0177fd19
ashokmeghvanshi/CP-CIPHER-Assignments
/Day-12 Leetcode Graph/Surrounded Regions.py
1,191
3.671875
4
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if len(board)==0: return def check(board,i,j): if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or board...
3e1d5d7176c80f5550a09ad34e858d732a24c17e
ashokmeghvanshi/CP-CIPHER-Assignments
/Day-09 Leetcode Binary Tree/Binary Tree Zigzag Level Order Traversal.py
950
3.625
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if root==None: return root def breadt...
96996ee46d38c59458ca1d85834a4ba37b2c1a52
ashokmeghvanshi/CP-CIPHER-Assignments
/Day-02 Leetcode Arrays/Move Zeroes.py
429
3.578125
4
def MoveZeroes(nums): ''''t=0 while 0 in nums: nums.remove(0) t=t+1 for i in range(t): nums.insert(len(nums),0)''' p,q=0,0 while q<len(nums): if nums[q]==0: q=q+1 else: nums[p],nums[q]=nums[q],nums[p] ...
406c790219ca8fcb61bc80ac6982222aad86e32f
ashokmeghvanshi/CP-CIPHER-Assignments
/Day-08 Leetcode Linked List/Rotate Linked List.py
724
3.578125
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head==None: return None l=[] curr=head while curr!=None: l.append...
118e2935e4aecfa2032c95432eaf9c0ffe555c8f
ashokmeghvanshi/CP-CIPHER-Assignments
/Day-09 Leetcode Binary Tree/Path Sum.py
683
3.703125
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def hasPathSum(self, root: TreeNode, sum1: int) -> bool: if root==None: return False ...
59c7b8c8f612724da109d0ba9649ff23775dee81
Ashofphoenix67/FunMooc2
/vigenere.py
567
3.765625
4
import string import itertools def cesar(clear, key, encode=True): if clear not in string.ascii_letters: return clear offset = ord(key.lower())-ord('a') + 1 if not encode: offset *= -1 firstl = ord('a') letter = chr((firstl + (ord(clear.lower()) - firstl + offset) % 26)) if (cle...
156770ea952bb0861f674fe0ed38d18563daae83
ogrisel/euroscipy-2019-scikit-learn-tutorial
/python_scripts/16.Performance_metrics_and_Model_Evaluation.py
10,054
3.59375
4
# --- # jupyter: # jupytext: # formats: notebooks//ipynb,markdown_files//md,python_scripts//py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.2' # jupytext_version: 1.2.1 # kernelspec: # display_name: Python 3 # language: python # ...
a8370dc0cd9ff9e42fdbd45c36de6f8ad9a1b8ca
Frogenius/Swiat-zwierzet
/organizm.py
1,230
3.53125
4
from abc import ABC, abstractmethod class Organizm(ABC): def __init__(self, sila, inicjatywa, x, y, swiat): self._x = x self._y = y self._wiek = 0 self._inicjatywa = inicjatywa self._sila = sila self._swiat = swiat self._niesmiertelny = False self._...
466f8e1670973e129f27c36a9d61f2d83cabd6f5
havenshi/cc150
/Q4.1.py
677
3.84375
4
class Tree(object): def __init__(self, val): self.val = val self.left = None self.right = None def isBalance(root): if not root: return True if not root.left and not root.right: return True else: if abs(length(root.left) - length(root.right)) <= 1 and isB...
27806dea3a18ab0cfa6faad8790daf7cfadd1783
havenshi/cc150
/Q8.1.py
1,280
3.546875
4
# -*- coding:utf8 -*- def fib(n): if n == 1 or n ==2: return 1 return fib(n-1) + fib(n-2) def fib2(n): if n == 1 or n ==2: return 1 a, b = 1, 1 for i in range(3, n+1): tmp = a + b a = b b = tmp return b def fib3(n): # 运用[[1,1],[1,0]]矩阵 if n == 1 or...
745bc7cf8d2c88feba62054feaf46312150da03e
havenshi/cc150
/Q8.4.py
408
3.84375
4
def permutation(nums): result = [] for i in range(len(nums)): help([nums[i]], nums[:i] + nums[i+1:], len(nums), result) return result def help(before, after, target, result): if len(before) == target: result.append(before) else: for i in range(len(after)): help(b...
1ac0c3333b4858299b292f47dbe93d641908351f
havenshi/cc150
/Q4.7.py
421
3.859375
4
def subtree(T1, T2): if not T1 or not T2: return False if T1.val == T2.val: if judge(T1, T2): return True return subtree(T1.left, T2) or subtree(T1.right, T2) def judge(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False if t1...
0b49c9eb861bb1204ac55b256019cc46a6fea0f8
saleisha57/DesktopClean
/Heapsort.py
685
3.890625
4
#Heapsort (Referencing the book for makeHeap, and https://www.geeksforgeeks.org/heap-sort/ for heapsort) array = [1,2,3,4,5,6] def makeHeap(arr): n = len(arr) for x in range(n//2,1,-1): k = x v = arr[k] heap = False while (not heap) and ((2*k) <= n): j = (2*k) if j < n: if arr[j] < ar...
66a16d29f30d44d93ca5f219d6d51752633364e2
jDavidZapata/Algorithms
/AlgorithmsInPython/stack.py
329
4.125
4
# Stack implementation in Python stack = [] # Add elements into stack stack.append('a') stack.append('b') stack.append('c') print('Stack') print(stack) # Popping elements from stack print('\nAfter popping an element from the stack:') print(stack.pop()) print(stack) print('\nStack after elements are poped:') prin...
7a6282b6853cc994602c934406da09aa036787af
mattcwh/Hackathon2019_Problems
/problem-4/problem_4.py
621
3.625
4
#Given: Positive integers n<=40 and k<=5. #Return: The total number of rabbit pairs that will be present after n months, #if we begin with 1 pair and in each generation, every pair of reproduction-age #rabbits produces a litter of k rabbit pairs (instead of only 1 pair). #Sample 1 #Input: 5 3 #Output: 19 #Sample 2 #I...
40b59d22b13152532166e69e31b4168a177d53c3
fanya85/lesson2
/if-2.py
1,126
4.25
4
""" Домашнее задание №1 Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки * Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая стро...
c8f2fadd807b7c52d799927f0715e1ff367a7239
aogden41/Geometry-Calculator
/adapters.py
711
3.765625
4
class Adapter(object): def __init__(self, shape): self.shape = shape self.name = shape.name def get_shape_ui(self): return self.shape.ui def algorithm1(self): raise NotImplementedError("Subclass must implement abstract method.") def algorithm2(self): raise Not...
cddbcc7d73621e4189c01423a477f7d4ef3b05fe
ogrudko/leetcode_problems
/easy/search_insert_position.py
446
3.953125
4
''' Problem: Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. ''' # Solution import bisect class Solution: def search_insert...
06318c3fdab54428be783b4675eb85c775eda3b9
ogrudko/leetcode_problems
/easy/longest_common_prefix.py
1,318
3.8125
4
''' Problem: Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Constraints: 1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lower-case English letters. ''' # Solution class Solution: def longe...
b6a6ac69c4730e0f7ee4e2bf889271812d5f168d
ogrudko/leetcode_problems
/easy/count_prime.py
804
4.15625
4
''' Problem: Count the number of prime numbers less than a non-negative number, n. Example 1: Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. Example 2: Input: n = 0 Output: 0 Example 3: Input: n = 1 Output: 0 Constraints: 0 <= n <= 5000000 ''' # Solution class ...
bcf72397210a4e7256a456ab504dd4e2c6a68eb0
MouradMettioui/AdvancedPython2BA-Labo1
/valeur absolue.py
180
3.984375
4
def abs(a): if a<0: print(-a) elif a>0: print(a) else : print ("zéro n'a pas de valeur absolue") a =float(input("entrer un nombre: ")) abs(a)
d522033acd8f3a1f72db25b65e38b63fc7feb3e1
Lakedz/hhTasks
/radix.py
6,623
3.546875
4
# -*- coding: utf8 -*- import os # Словарь значений для систем счисления до 16-ричной dicta = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'] # Ситаем построчно из файла. Принимаем в расчёт большие объёмы def readFileByLine(fileName): with open(fileName, 'r') as f: for line in f: # Убираем симво...
628343c76e69d4306f3ee10e22f11847fcca1b6c
Diegod96/Scraper
/url.py
1,285
3.75
4
from dataclasses import dataclass @dataclass class UrlObj: def __init__(self): self.location = self.get_location() # Location(i.e. City) being searched self.postal_code = self.get_postal_code() # Postal code of location being searched self.query = self.get_query() # Search for the type ...
0dff71c554a4a39f50244819e11bea941b1378fe
harshiniravula/DSP_LAB
/lab8_prog2.py
243
3.765625
4
import numpy as np import matplotlib.pyplot as plt m=int(input("enter the value of m")) y=[] for n in range(0,m-1): x=0.5-0.5*np.cos(2*np.pi*n/(m-1)) y=np.append(y,x) n=np.arange(0,m-1,1) plt.stem(n,y) plt.title("hanning window") plt.show()
4e8b26487e265f09cb34df133fbc2e007caae335
santosclaudinei/uri
/uri_1040.py
2,035
3.90625
4
# Leia quatro números (N1, N2, N3, N4), cada um deles com uma casa decimal, # correspondente às quatro notas de um aluno. Calcule a média com pesos 2, 3, 4 e 1, # respectivamente, para cada uma destas notas e mostre esta média acompanhada pela mensagem # "Media: ". Se esta média for maior ou igual a 7.0, imprima a mens...
186edf1d87032967a4474390bbb0984681a5c3b0
santosclaudinei/uri
/uri_1029.py
1,229
4.03125
4
# Quase todo estudante de Ciência da Computação recebe em algum momento no início de seu curso de graduação # algum problema envolvendo a sequência de Fibonacci. Tal sequência tem como os dois primeiros valores 0 (zero) # e 1 (um) e cada próximo valor será sempre a soma dos dois valores imediatamente anteriores. # Por ...
ba21fa03af51a46f293f2f32d8ff3418128b9f0d
LiuWillow/leetCodePy
/Q22_generateParenthesis.py
2,084
3.84375
4
# 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 # 例如,给出 n = 3,生成结果为: # [ # "((()))", # "(()())", # "(())()", # "()(())", # "()()()" # ] # 回溯 # stack 已经放进去的左边的括号 # c 即将要放进去的括号 # resultList 返回的列表结果 # str 当前组装到一半的str # f(stack, c, resultList, str, n) # 返回条件:str.length == 2 * n || 不符合括号规则 # 要加入resultList的条件:st...
09f9b377bbbbea6e73af55806b8aba3d836e8c3b
francs1/leetcode_basic_60
/leetcode入门60题/13回溯/leetcode46_全排列.py
1,148
3.609375
4
import itertools #import itertools.combinations class Solution: def permute(self, nums: 'List[int]') -> 'List[List[int]]': n = len(nums) temp = itertools.permutations(nums,n) #print(temp) result = [] for i in temp: result.append(list(i)) return...
04c1344edea2e6504e2ae0c6d20ae8c0d2958e1f
francs1/leetcode_basic_60
/leetcode入门60题/02字符串/leetcode14_最长公共前缀.py
1,371
3.515625
4
#题目地址:https://leetcode-cn.com/problems/longest-common-prefix/ class Solution: def longestCommonPrefix(self, strs: 'List[str]') -> str: n = len(strs)#获取数组长度 if n == 0:#如果是空数组,则返回空串 return '' if n == 1:#如果数组中只有一个字符串 return strs[0]#则返回这个字符串 j = 0#定义索引j用于遍历每个字符串中...
59dafe2f00e2eaa8d87561490c43518f71520e33
francs1/leetcode_basic_60
/leetcode入门60题/07哈希/leetcode242_有效的字母异位词.py
593
3.546875
4
import collections class Solution: #方法一排序 def isAnagram(self, s: str, t: str) -> bool: return sorted(s) == sorted(t) #方法二:哈希 ''' def isAnagram(self, s: str, t: str) -> bool: c1 = collections.Counter(s) c2 = collections.Counter(t) if len(c1) != len(c2...
519a68954fca162a1b14097a99883365c39905a4
nicochunger/Percolacion
/graficos_ej3.py
955
3.59375
4
# Graficos del ejercicio 3 de la practica de Percolacion import numpy as np import matplotlib.pyplot as plt masa_percolante = np.loadtxt("tp1_3.txt") L = range(2,8) for i in range(6): L[i] = L[i]**2 #============================================================================== # rho = [] # for i in range(6): # ...
23968cd84ead47e9544171cdabba3075178ed002
sskt1969/python-4
/word.py
110
4.09375
4
string=int(input()) word=0 for i in string: word=word+1 print("No.of words in the string:") print(word)
b826e8949ed8975a898ad6bcc86c9cb5682293bb
BlackSatan/onedimentional-search
/fibonacci.py
542
4.0625
4
#searching for a function minimum interval with fibonacci method from math import sqrt def fibonacci(func, start, end, n): for i in range(n): l_i = start + (fibonacci_number(n - i - 1) / fibonacci_number(n - i + 1)) * (end - start) u_i = start + (fibonacci_number(n - i) / fibonacci_number(n - i + ...
424f1658a87bb38b9f03737536912a34e4628e9e
DinkDev/PolyglotSudoku
/SudokuPy/SudokuPy/solvers/NorvigPuzzleSolver.py
1,226
3.609375
4
from SudokuPy.solvers.PuzzleSolver import PuzzleSolver class NorvigPuzzleSolver(PuzzleSolver): def solve(self): """Solves the puzzle. Solves the puzzle by using Peter Norvig's depth first search technique. See: http://norvig.com/sudoku.html Returns: dict of str: str:...
bfbe1efb2b3a013ebfabcef5ce0068b5c462f02c
emschuch/dsp
/python/markov.py
1,910
3.75
4
#!/usr/bin/env python from sys import argv import string import random script, input_text, output_length = argv output_length = int(output_length) suf_map = {} pre = () list_words = [] text_block = [] def process_text(f): """Reads in text file, splits into words and pushes words to a list""" fin = open(...
80e0a1c292111a4b9287c9b7a359aee1e5252a7b
kcaashish/PythonJamProjects
/src/part3_q13.py
405
3.84375
4
import numpy as np import matplotlib.pyplot as plt def angle(): angles = np.arange(0, 2*np.pi + np.pi, np.pi/3) angles_offset = angles + np.pi/2 sin = np.sin(angles_offset) cos = np.cos(angles_offset) plt.plot(cos, sin, marker='.') plt.title("Question 13") plt.xlabel("X-axis") plt.yla...
423e0d24eabaeafd42e243728fa4c96adae6e14d
SMN-Hub/pyNN
/mlscanner/text_structure.py
626
3.640625
4
class Line: def __init__(self, top, height, data, chars, left_average): self.top = top self.height = height self.data = data self.chars = chars self.left_average = left_average class Char: def __init__(self, left, width, data): self.left = left self.wid...
ee5832641cc010cf4866cfd2e1595960c7d0f2f9
racingslab/python-kiwoom
/2주차/Pythagorean.py
277
3.921875
4
# 피타고라스 정리 a = int(input('a의 값: ')) b = int(input('b의 값: ')) c = int(input('c의 값: ')) if a ** 2 + b ** 2 == c ** 2: print('피타고라스의 정리가 성립합니다.') else: print('피타고라스의 정리가 성립하지 않습니다.')
deb65eb70525ae819971956e190bb8a7d3e02b15
racingslab/python-kiwoom
/5주차/review/recurrence_functionn.py
265
3.796875
4
import time def countDown(sec): print(sec) time.sleep(1) if sec == 0: return print('땡!') return countDown(sec - 1) sec = int(input('몇 초로 하실건가요?')) print(str(sec) + '초간 스탑워치 작동합니다.') countDown(sec)
8b4e7933e47470617884f70f6c26fbf5c5e59d94
racingslab/python-kiwoom
/2주차/RSP.py
647
3.75
4
# 가위바위보 게임 import random randValue = random.randrange(1, 4) userValue = input('가위, 바위, 보 중에 하나를 입력해주세요: ') if userValue in ['가위', '바위', '보']: if userValue == '가위': userValue = 1 elif userValue == '바위': userValue = 2 elif userValue == '보': userValue = 3 if randValue == userValue...
65564af667084491c45f644ce9729b0b9f7ad243
shubhamsahu02/Cspp1-practise
/M5/GuessMyNumber/guess_my_number.py
447
4
4
"""Activity 8""" print('Think of a number between 0 to 100') LOW = 0 HIGH = 100 """Guess the number""" while True: GUESS = (HIGH+LOW)//2 USER = input('Is your secret number ' + str(GUESS) + '\n') if USER == 'h': LOW = GUESS elif USER == 'l': HIGH = GUESS elif USER == 'c': pri...
c040a5f8e8f01a15aa14baa9be50634104532030
shubhamsahu02/Cspp1-practise
/fourth_power.py
538
3.890625
4
"""Exercise: fourth power # This function takes in one number and returns one number.""" def square(x_x): ''' x_x: int or float. ''' # Your code here return x_x*x_x def fourth_power(x_x): ''' x_x: int or float.''' return square(square(x_x)) def main(): """function""" data = in...
2b93a4fafb58e072460b3f986a753b26033b8f89
mjalas/ssddp
/measurements/measurement_time.py
1,655
3.625
4
from datetime import datetime import time from message.timestamp import Timestamp class MeasurementTimeGetter(object): """ """ def __init__(self): pass def now(self): """ Method for getting the current time. The method can either return get_datetime() or get_timestamp(). ...
252ff259a209bc28b6f05c9b16027766cbcc65b9
mjalas/ssddp
/message/timestamp.py
465
3.59375
4
from datetime import datetime import time class Timestamp(object): """ Helper class for handling timestamps. """ @staticmethod def create_timestamp(): return datetime.now().timestamp() @staticmethod def timestamp_to_string(timestamp): return datetime.fromtimestamp(timestam...
beb58e1d29f10c486ddfbf10b577c07d0cac7030
gauravjoshi1292/TestPrograms
/vertex.py
1,381
3.640625
4
# from cs1lib import * class Vertex: """ Vertex class that contains all the information for a vertex """ def __init__(self, name=None, x=0, y=0): self.name = name self.x = x self.y = y self.adjacent_vertices = [] def __str__(self): """ ...
7197837fda67ce7ec5afda1c7ff3cf922d105bd9
bri4nle/ai-text-completion-project
/user_interface.py
5,065
3.71875
4
class UserInterface: def __init__(self, text_gen): self.instructions() self.user_input = '' self.get_last_2_words(self.user_input) self.total_num_picked = 0 self.total_correct_pick = 0 self.text_gen = text_gen def runProgram(self): """ This funct...
1f44c9fad58a6e2f80f7bfbf556f4e9c2ff6ae7d
gulamd/python
/for_loop_string.py
137
3.9375
4
#name = "harshit" #for i in name: # print(i) num = input(" Enter a number :") total = 0 for i in num: total += int(i) print(total)
5f9352ba7df3c744e70d1bb1f276d29cf3128346
gulamd/python
/more_about_tupels.py
163
3.84375
4
mixed = (1,2,3,4.0) # for loop and tuple #for i in mixed: # print(i) # tuple with one element #nums = (1) # its not tuple it a int nums = (1,) print(type(nums))
236af6858b6798d48a5ba7f4c10eacf2e8c417e0
gulamd/python
/excersise-3.py
177
4
4
name, char = input("Enter the comma sepreted name and character :").split(",") print(f"Length of the your name is {len(name)}") print(f"count of the name : {name.count(char)}")
78c2aa51badb0b3c83112f60565305385223f025
gulamd/python
/int_func.py
144
3.828125
4
numb1 = int(input("Enter first number ")) numb2 = int(input("Ener secound number ")) total = numb1 + numb2 print("total is" +" " +str(total))
0355a8f3d34eb6b303a2ad15aa0e2e892037ce9a
ConnorTippets/stupidtext
/stupidtext/functions.py
244
3.75
4
def stupidText(text): text = list(text) x = 0 while x < len(text): text[x] = text[x].upper() text[x+1] = text[x+1].lower() x += 2 text = ''.join(text) return text stupidifier = stupidText
eeac134e1eed9fe4520fe4574c4eb76f55987949
byung-u/HackerRank
/Regex/Introduction/matching_specific_string.py
202
4
4
#!/usr/bin/env python3 import sys import re Regex_Pattern = r'hackerrank' Test_String = input() match = re.findall(Regex_Pattern, Test_String) print("Number of matches :", len(match)) print(match)
1ad8cba66efe482978b9789232a1dea6939a0af3
byung-u/HackerRank
/ProjectEuler_plus/euler_080.py
586
3.671875
4
#!/usr/bin/env python3 from decimal import getcontext, Decimal from math import sqrt def is_square(n): s = sqrt(n) return s.is_integer() N = int(input().strip()) P = int(input().strip()) if N > 1000: if P > 1000: P = 1000 elif N < 100: if P > 10000: P = 10000 getcontext().prec = P ...
e820ecd239f6d957777e35addea271d590ed5b3c
byung-u/HackerRank
/Algorithms/Implementation/bigger_is_greater.py
1,746
3.828125
4
#!/usr/bin/env python3 ''' https://www.nayuki.io/page/next-lexicographical-permutation-algorithm 0. Initial sequence [0, 1, 2, 5, 3, 3, 0] len=7 1. Find longest non-increasing suffix [0, 1, 2, 5, 3, 3, 0] 0 < 1 1 < 2 2 < 5 --- longest --- i = 7 - 1 - 3 = 3 2. Identif...
dfcaa6d3956edba4093127a5d89e3a185ae477b4
byung-u/HackerRank
/PYTHON/Numpy/shape.py
121
3.65625
4
#!/usr/bin/env python3 import numpy arr = list(map(int, input().strip().split(' '))) print(numpy.reshape(arr, (3, 3)))
b32e16042ffa688151be8c754d74f9bd74f1b285
byung-u/HackerRank
/Algorithms/Greedy/mark_and_toys.py
445
3.625
4
#!/usr/bin/env python3 import sys def maximumToys(prices, k): sorted_prices = sorted(prices) cnt, total = 0, 0 for p in sorted_prices: total += p if total > k: break cnt += 1 return cnt if __name__ == "__main__": n, k = input().strip().split(' ') n, k = [i...
d9049c18fc51ee96a4e436d08efccb2028a6e201
byung-u/HackerRank
/Cracking_the_Coding_Interview/stacks_balanced_brackets.py
1,317
3.875
4
#!/usr/bin/env python3 import sys # ['{', '[', '(', ')', ']', '}'] # [123, 91, 40, 41, 93, 125] def is_matched(expression): arr = list(expression) if arr[0] == '}' or arr[0] == ']' or arr[0] == ')': # It was a key. return False found = True while found == False: diff = abs(ord(arr[...
dec31e7fe522a1167c972df42b720dc206c64c57
byung-u/HackerRank
/Algorithms/Greedy/grid_challenge.py
449
3.5625
4
#!/usr/bin/env python3 import sys for _ in range(int(input().strip())): arr = [list(input()) for _ in range(int(input().strip()))] new_arr = [] for ar in arr: temp = ([ord(a) for a in ar]) new_arr.append(sorted(temp)) for i in range(0, len(new_arr) - 1): if new_arr[i + 1][0] <...
adc13e057f0c3cc3048bd705b58d9243bacd08b1
byung-u/HackerRank
/PYTHON/Strings/alphabet_rangoli.py
628
3.765625
4
#!/usr/bin/env python3 import sys from string import ascii_lowercase def print_rangoli(size): width = size * 4 - 3 alphabet = (ascii_lowercase[0:size])[::-1] res = [] for i in range(size): s = '' for a in alphabet[0:i+1]: s = '%s-%s' % (s, a) temp = s + s[::-1][1:] ...
a5f4abcf637bbb0c4abb5fb0c92de99d80a4c915
byung-u/HackerRank
/Cracking_the_Coding_Interview/sorting_comparator.py
771
3.6875
4
#!/usr/bin/env python3 import sys from functools import cmp_to_key class Player: def __init__(self, name, score): self.name = name self.score = score def __repr__(self): return repr(self.name) def comparator(a, b): if a.score < b.score: return 1 elif r...
b1657e50fef10210cc6cdc53c29007e6d6ce4be4
byung-u/HackerRank
/Cracking_the_Coding_Interview/arrays_left_rotation.py
486
3.625
4
#!/usr/bin/env python3 import sys def shift(input_list, n): n = n % len(input_list) return input_list[n:] + input_list[:n] def array_left_rotation_slow(a, n, k): ret = [] for i in range(0, k + 1): ret = shift(a, i) return ret def array_left_rotation(a, n, k): ret = a[k:] + a[0:k] ...
2a5c637b5c20fbc5b3a3e3a6d3fe7cbee75baeeb
byung-u/HackerRank
/ProjectEuler_plus/euler_032.py
510
3.625
4
#!/usr/bin/env python3 def is_pandigital(n, s=9): return len(n) == s and not '1234567890'[:s].strip(n) N = int(input().strip()) result = set() for i in range(1, 10000): for j in range(1, 10000): check_str = str(i) + str(j) + str(i * j) len_cs = len(check_str) if len_cs > N: ...
f58b97330da6fb0d39074f070e21f1b6f9852aab
byung-u/HackerRank
/PYTHON/Built_Ins/ginorts.py
1,091
4.03125
4
#!/usr/bin/env python3 import sys if __name__ == "__main__": S = input() print(*sorted(S, key=lambda c: (-ord(c) >> 5, c in '02468', c)), sep='') print(*sorted(S, key=lambda x:(x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower() , x)), sep='') # print(sorted(S, key=lambda c: (-ord(...
a93f216b08a7bd8579a12132cb1e1c7f237849a6
byung-u/HackerRank
/Algorithms/Strings/alternating_characters.py
376
3.96875
4
#!/usr/bin/env python3 import sys from itertools import groupby # Success def alternatingCharacters(s): CS = ([list(g) for k, g in groupby(s)]) cnt = 0 for C in CS: cnt += len(C) - 1 return cnt # Complete this function q = int(input().strip()) for a0 in range(q): s = input().strip() ...
dffe5e90d9be8ff4ee8b65d0607537364db97070
Dragnoid99/Travis
/test.py
494
3.640625
4
from functions import add from functions import subtract from functions import multiply from functions import divide def test_check_add(): assert add ( 5 , 2 ) == 7 def test_check_wrong_add(): assert add ( 9 , 4 ) == 7 def test_check_subtract(): assert subtract ( 5 , 2 ) == 3 def test_check_wrong_su...
b168bdcb4cce946f40baad63701e3228a83287fc
AspiringOliver/kkb
/1 基础语法/课后作业/19-基础总结 练习题参考答案.py
2,519
3.9375
4
# 创建年级类 class Grade(): # 定义初始化⽅法 def __init__(self, grades): # 创建实例化属性self.grades,self.grades_name self.grades = str(grades) self.grades_name = '年级' # 定义str魔法⽅法 def __str__(self): # str⽅法的返回值为实例属性self.grades return self.grades # 创建班级类 class Banji(): # 定义初始化...
06aab6ad1bc538a8dbc0435ee7bd2d1f25c6d143
AspiringOliver/kkb
/1 基础语法/课后作业/13-类与对象 练习题.py
2,325
4.34375
4
#self的作用:self会在类的实例化中接收传入的数据, 在代码中运行。 #类中的一个类方法需要调用另一个类方法或类属性,都需要使用self。 #总结:类方法中调用类内部属性或者是其他方法时,需要使用self来代表实例。 #1.1.0 # class Information(object): #object是所有类的父类 # def __init__(self, name): # #初试化方法无需调用,对象实例化时自动执行 # print(name) # self.n = name # #此时的self.n可以理解为Information这个类的‘全局变量’...
fb93c8fa565cb667c252d16407c82dd5456f31d1
AspiringOliver/kkb
/课外程序/Python定时任务调度库schedule.py
971
3.671875
4
# 导入模块 import schedule, time # 定义一个任务 def work(): print('我是定时的任务') def test(): print('我是定时的任务2') # 设置定时 # 每10秒执行一次 schedule.every(10).seconds.do(test) # 部署每10分钟执行一次test()函数的任务 schedule.every(10).minutes.do(test) #部署每×小时执行一次test()函数的任务 schedule.every().hour.do(test) # 部署在每天的08:00执行test()函数的任务 schedule.every()...
e2f6db98443f5357b98306f9cc14d41a4dd5a7f6
rawatsushil/datastructure
/code/sorting/merge.py
619
3.890625
4
class MergeSort(object): def __init__(self, arr): self.arr = arr def sort(self, arr): if len(arr) > 1: mid = len(arr)//2 L = arr[:mid] R = arr[mid:] self.sort(L) self.sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: ar...
393fe94266faade066b3ca0112a434622e2dff22
rawatsushil/datastructure
/code/DP/tushar/staircase.py
473
4.15625
4
# Given a staircase and give you can take 1 or 2 steps at a time, how many ways you can reach nth step. class StairCase: def __init__(self, steps): self.steps = steps self.step_arr = [] def find_steps(self): self.step_arr.append(1) self.step_arr.append(2) for i in range(2, self.steps): self.step_arr.ap...
90b74a8a3febd1dc60d9d1847d3f4f051932cdd0
haro-nl/doren
/test01.py
225
3.578125
4
import antigravity print ('hello Johan') a = [i for i in range(0, 100)] b = [j for j in range(100, 200)] print ('nogmaals gewijzigd om 1701uur!') a = 'hallo Hans, nog een wijziging om 1724 uur' b = 'ik heb honger ondertussen!'
9a58c2da04e84d0f2985a56463fcefafc19e1725
herisson31/Python-3-Exercicios-1-ao-104
/ex062 - Super Progressão Aritmética v3.0.py
634
4.09375
4
'''062: Melhore o DESAFIO 061, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos.''' print('Gerador de PA') print('-='*20) primeito = int(input('Primeiro Termo: ')) razao = int(input('Razão da PA: ')) termo = primeito cont = 1 total = ...
b93e6ff80e0e807a8da0739d03b8a04317532fc4
herisson31/Python-3-Exercicios-1-ao-104
/ex017 - Catetos e Hipotenusa.py
352
4.125
4
'''Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo. Calcule e mostre o comprimento da hipotenusa.''' import math co = float(input('Digite o cateto oposto: ')) ca = float(input('Digite o cateto adjacente: ')) h = co**2 + ca**2 hi= math.sqrt(h) print('O valor da H...
3a84047803b0ea369e1c74a7ed6e77b65548e3a1
herisson31/Python-3-Exercicios-1-ao-104
/ex031 - Custo da Viagem.py
606
4.0625
4
'''031: Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.''' viagem = float(input('Qual a distancia da viagem em Km: ')) if viagem < 200: valor = viagem *0.50 print('Sua vi...
78df095dfd73bcec8381cacbc09152e825233200
herisson31/Python-3-Exercicios-1-ao-104
/ex055 - Maior e menor da sequência.py
546
3.9375
4
'''055: Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos.''' Maiorpeso = 0 Menorpeso = 0 for pess in range(1,6): peso = float(input('Digite o pesso da {}ª pessoa: '.format(pess))) if pess == 1: Maiorpeso = peso Menorpeso = peso else: ...
965ad1a766be9f89266e37e53b1b559864004c64
herisson31/Python-3-Exercicios-1-ao-104
/ex022 - Analisador de Textos.py
533
4.25
4
'''022: Crie um programa que leia o nome completo de uma pessoa e mostre: - O nome com todas as letras maiúsculas e minúsculas. - Quantas letras ao todo (sem considerar espaços). - Quantas letras tem o primeiro nome''' nome = input('Digite seu nome completo: ') print('Seu nome com todas as letras Maiuscula: {}'.format...
dd1e80ca575a6d3eeb90b2c0f71f799ffa7a6da3
herisson31/Python-3-Exercicios-1-ao-104
/ex058 - Jogo da Adivinhação v2.0.py
847
4.09375
4
'''058: Melhore o jogo do DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.''' from random import randint from time import sleep computador = randint(1,10) print('Sou seu...
0958494baedd0b356df208926b34a4a0c9c0a961
herisson31/Python-3-Exercicios-1-ao-104
/ex063 - Sequência de Fibonacci v1.0.py
494
4.21875
4
'''063: Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci. Ex: 0 - 1 - 1 - 2 - 3 - 5 - 8''' print('-'*30) print('Sequencia de Fibonacci') print('-'*30) n = int(input('Digite o termo da sequencia: ')) t1 = 0 t2 = 1 print('~'*30) print('{...
e561bc9ce7aff73f0f6ee7ddb5730948836828ea
herisson31/Python-3-Exercicios-1-ao-104
/ex015 - Aluguel de Carros.py
637
4
4
'''Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.''' km = float(input('Digite os Km percorrido: ')) dia = int(input('Quantos dias de alugue...
08d5fbddca23fe78b01099f3fcf8672d4eb7984a
herisson31/Python-3-Exercicios-1-ao-104
/ex071 - Simulador de Caixa Eletrônico.py
1,005
4.09375
4
'''071: Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.''' print('='*3...
9b5a2bfaf9be058fd58a9cf60cb6be883d7683ac
julienbosse/JeuDeCreatures
/JeuDeCreatures.py
4,274
3.796875
4
from random import choice from time import sleep class Case: def __init__(self,x: int,y: int): self.x = x self.y = y def adjacentes(self,jeu) -> list: # Retourne les cases de la liste des cases dont la distance**2 est inférieure ou égale à 2 à la case courante return [c for c ...