blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
0538cef9579b5ba8b1a4694f060bb639c7a12f7f | jaxhuan/python-demo | /base_practice/FunctionProgramSort.py | 408 | 3.640625 | 4 | a = sorted(['jax', 'haha', 'amazing', 'create'], key=str.lower, reverse=True)
print(a)
table_score = [('bob', 75), ('amada', 92), ('bart', 66), ('lisa', 88)]
print(table_score)
def by_name(t):
return t[0]
def by_score(t):
return t[1]
print('name:', sorted(table_score, key=by_name))
print('score:', sorte... |
108d1424e1ed7cbc16526bd7840279acce0f72d5 | moodymood536/python_lessons_level1 | /lesson02/home_work/hw02_normal.py | 4,874 | 3.859375 | 4 | # Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ... |
057f6dfd593fe2066ddb29a2bbff2fa2c846ca6c | Cubba2412/BacteriaDataAnalysis | /dataLoad.py | 1,510 | 4.25 | 4 | import numpy as np
def dataLoad(filename):
# DATALOAD Loads in a text data containing N x 3 data values and
# returns it as a float array
##
# Usage: data = dataLoad(filename)
##
# Input filename: filename of textfile (String of full path to file)
# Output data: N x 3 float array w... |
085b0c07feac8c391c0fd0a28727ebdde7f38dd1 | dmdsik/Algorithm | /BOJ/[10001~20000]/[10001~11000]/10871.py | 259 | 3.59375 | 4 | N, X = map(int, input().split())
A = list(map(int, input().split()))
#You must memorize the grammer of the map()
for i in range(N):
if A[i] < X:
print(A[i], end = " ") #Python automatically newline, u don't need to newline then use <end = " ">
|
cbbc857098cffcea81e34864b27c7aa2e2f8c177 | GrigorevEv/Hello-World | /Algorithms and data structures (Python)/F. Contest (using arrays)/B-Bank deposit !!!map.py | 828 | 3.65625 | 4 | # Вклад в банке составляет x рублей.
# Ежегодно он увеличивается на p процентов, после чего дробная часть копеек отбрасывается.
# Каждый год сумма вклада становится больше.
# Надо определить, через сколько лет вклад составит не менее y рублей.
# Формат входных данных
# Три натуральных числа: x, p, y.
# Формат выходных ... |
428df7944d8bde420ac12fff665bb6c376fbff74 | msulibrary/dataset-search | /docs/Metadata_Enhancement_Web_Crawling/metadata_enhancement.py | 17,126 | 3.71875 | 4 | '''
Kyle Hagerman
Montana State University Dataset Search
This code is based on scripts written by Jason Clark.
It is used to scrape the web for skills by MSU researchers.
Targeted websites are:
- Google Scholar
- ORCiD
- MS Academic
- ResearchGate
- LinkedIn
INPUT: This program will read a csv li... |
e1369e2118fcab1b6032c8adbf49feac51c0d79c | MrMebelMan/pyvat | /pyvat/xml_utils.py | 973 | 3.65625 | 4 | class NodeNotFoundError(Exception):
"""XML node was not found.
"""
pass
def get_first_child_element(node, tag_name):
"""Get the first child element node with a given tag name.
:param node: Parent node.
:type node: xml.dom.Node
:returns: the first child element node with the given tag nam... |
decc52582a744ad9a79695cb24e4b957a6274d92 | Anton-K-NN/simple-number | /simple numbers.py | 325 | 3.75 | 4 | from itertools import takewhile
import itertools
def primes():
a = 2
pr=[2]
yield a
while True: # просто пример
a+=1
for j in range(2,a):
if a%j==0:
break
else:
yield a
print(list(itertools.takewhile(lambda x : x <= 31, primes()))) |
7a5d9e1c206b2b01944edc165b8f6f6cf94fc6f7 | joseph-mutu/Codes-of-Algorithms-and-Data-Structure | /Leetcode/罗马字母转换.py | 998 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-16 07:55:19
# @Author : mutudeh (josephmathone@gmail.com)
# @Link : ${link}
# @Version : $Id$
import os
class Solution(object):
def __init__(self):
self.roman_dic = {"I":1,'V':5,'X':10,'L':50,'C':100,\
'D':500,'M':1000}
... |
1164ab49019378daeab10309d0c378f46f259af8 | terasakisatoshi/pythonCodes | /higherFunc/fil.py | 389 | 3.609375 | 4 | from functools import partial
def arg_abc(a,b,c):
return 1*a+2*b+3*c
arg_bc=partial(arg_abc,a=0)
arg_ac=partial(arg_abc,b=0)
arg_ab=partial(arg_abc,c=0)
arg_a=partial(arg_abc,b=0,c=0)
arg_b=partial(arg_abc,a=0,c=0)
arg_c=partial(arg_abc,0,0)
print(arg_bc(b=3,c=5))
print(arg_ac(a=3,c=5))
print(arg_ab(a=3,b=5))
p... |
955994771bbcb2afd1008f94233ba1e367319e60 | Aniyes/Rebel | /Guessing_GAme.py | 716 | 4.09375 | 4 | # This is a Guess the Number game.
import random
Guesses = 0
print('Hello! What is your name?')
Name = input()
Number = random.randint(1, 10)
print( Name + ', I am thinking of a number between 1 and 10. You have 7 tries!')
while Guesses < 6:
print('What am I thinking?')
Guess = input()
Gu... |
b24edc4253878f9ebc4a1f4d2bd5b95e79764ce4 | arnab-arnab/Python-Course | /12.Chapter 12/Question 1.py | 332 | 3.53125 | 4 | try:
with open("file1.txt") as f:
print(f.read())
with open("file2.txt") as g:
print(g.read())
with open("file3.txt") as h:
print(h.read())
except Exception as ex:
print(ex)
print("Error occured")
print("Some files are not present")
else:
print("It was successfully... |
edcb16639bd5f19e5ae516cb25ec1835a07e5051 | shubhamt7/ContactlessATMSystem | /authenticate.py | 912 | 4.03125 | 4 | """
Code for authenticating a user before
he is allowed to perform any other operations.
The user is asked to enter account number and pin
"""
import pandas as pd
from keyboardNumpad import getNumber
def authenticate(language):
try:
data = pd.read_csv('atmData.csv')
ac = getNumber(language, "ent... |
8607f7b8c1ebc2e8a13c8834038cb60e997663dc | coolkiran2006/pythonlearning | /basics/1.py | 244 | 4 | 4 | num=int(input("Enter a Number:"))
string=str(input("Enter a Name:"))
floa=float(input("Enter a Float a Value:"))
data=input("Enter the Data:")
print ("nums is:",num)
print ("string is:",string)
print ("float is:",floa)
print ("data is :",data)
|
5de3feca8cb7d2d1eb84460b86944a315bfef916 | G0PALAKRISHNAN/python | /untitled/class3.py | 344 | 3.609375 | 4 | class A:
a=10
b=20
def __init__(self,b,c):
self.b=b
self.c=c
def disp(self,name):
print("Name is ",name)
print("value stored in object",self)
print(self.a,self.b,self.c)
def add(self):
return self.a+self.b+self.c
obj=A(25,35)
A.disp(obj,'Kishan')
sum... |
efc1257c67e80edb69452ff5be5b6d57fa334556 | lokasan/algo_and_structures_python | /Lesson_3/2.py | 820 | 4.03125 | 4 | """
2. Во втором массиве сохранить индексы четных элементов первого массива.
Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, то во второй массив
надо заполнить значениями 1, 4, 5, 6
(или 0, 3, 4, 5 - если индексация начинается с нуля),
т.к. именно в этих позициях первого массива стоят четные числа.
"""
arr1 ... |
5d18404a64fd08af51ef0fe268e840dc7ef58a5d | AABoachie/Python_Exercises | /ex15.py | 118 | 4.1875 | 4 | string = input("Enter a string: ")
words = string.split(' ')
words.reverse()
string = ' '.join(words)
print(string)
|
b7caee663948cc01b5bb0ad31e4dec1c55c192be | zmh19941223/heimatest2021 | /04、 python编程/day05/3-code/07-课堂练习-字典操作.py | 115 | 3.734375 | 4 | dict1 = {"name":"周瑜", "age":32, "id":"001"}
dict1["sex"] = "男"
dict1.pop("id")
dict1["age"] = 26
print(dict1) |
d7ca1a38c1314ad823a215e8d51253df5983c263 | jiangjiane/Python | /pythonpy/test16_9.py | 765 | 4.0625 | 4 | #使用类的状态
class tester:
def __init__(self,start):
self.state=start
def nested(self,label):
print(label,self.state)
self.state+=1
F=tester(0)
F.nested('spam')
F.nested('ham')
G=tester(42)
G.nested('toast')
G.nested('bacon')
F.nested('eggs')
print(F.state)
print('\n')
class tester:
def... |
b466f7c4052b9eb702ebc27353a12bfca24ef9da | lucas1309/CineSys | /sessao_menu.py | 3,426 | 3.53125 | 4 | import sessao
import sala
import filme
def imprimir_sessao(sessoes):
print(sessoes)
print('Cod. Sessão: ',sessoes[0])
print('Cod. Filme: ', sessoes[1])
print('Cod sala: ',sessoes[2])
print('Horário: ',sessoes[3])
print('Capacidade: ',sessoes[4])
def menu_criar():
cod_ses... |
4165ca311f9d36c2226971f0da3e0084056603cb | ahmadalsajid/InovioCodeSession | /Q2.py | 201 | 3.65625 | 4 | '''
Input: 1, 4, 7, 2, 5
Output: 1, 2, 4, 5, 7
'''
lst = [int(x) for x in input().split(',')]
sorted_list = sorted(lst)
# print(sorted_list)
for x in sorted_list:
print(x,end= ', ')
|
21164fa9ac68fe4d2692c189826c8f9d70febda3 | pylangstudy/201708 | /02/01/translate.py | 394 | 3.6875 | 4 | x = str.maketrans('abc', '123')
print(x, type(x))
s = 'abcbaABC'; print(s, s.translate(x))
# 第 3 引数を指定する場合、文字列を指定する必要があり、それに含まれる文字が None に対応付けられます。
x = str.maketrans('abc', '123', '-')
print(x, type(x))
s = None; print(s, s.translate(x)) #AttributeError: 'NoneType' object has no attribute 'translate'
|
4036663c0cdba4b228a44664991e8dc78a12789b | rafaelaraujobsb/pontoeletronico | /app/back/vrf.py | 1,263 | 3.953125 | 4 | #!/bin/usr/python
#coding = utf-8
class Verificacao():
'''
Verificação dos dados.
Essa classe realiza a verificação dos dados informados e
seus metódos retornam uma mensagem de erro personalizada
* não possui atributos
'''
def nullSpace(self, error, **args):
'''
Metódo que verifica se os argumentos... |
b9339cdb82fae05cdb7ceb72d65126c6f7a9a93c | Jhancykrishna/luminarpythonprograms | /operators/inc-dec.py | 178 | 3.703125 | 4 | num=5
num+=2 #increment by 2
print(num) #num is 7 now
num-=3 #decrement by 3
print(num) #7-3=4
i=2 #2
i+=2*2 #2+4=6
print(i)
i*=2*2 #6*4=24
print(i) |
979abe06bba64dfbe7a152aefd87014f5589a0b8 | Kvazar78/Skillbox | /6.3_while_break/task_2.py | 823 | 4.28125 | 4 | # Нам нужно расшифровать определённый код в виде одного большого числа.
# Для этого нужно посчитать сумму цифр справа налево. Если мы встречаем
# в числе цифру 5, то выводим сообщение «Обнаружен разрыв» и заканчиваем
# считать сумму. В конце программы на экран выводится сумма тех цифр,
# которые мы взяли.
number = int(... |
9f65f4e84edee4e4f49ffcee298e13e8dda40145 | rookie-LeeMC/Data_Structure_and_Algorithm | /排序算法/归并排序/merge_sort.py | 2,375 | 3.96875 | 4 | # -*- coding:UTF-8 -*-
'''
归并:https://blog.csdn.net/qq_17621363/article/details/104312352
先分,后治,核心函数为合并两个有序数组
'''
# def merge(li, low, mid, high):
# i = low
# j = mid + 1
#
# ltmp = []
# while i <= mid and j <= high: # 只要左右两边都有数
# if li[i] < li[j]:
# ltmp.append(li[i])
# ... |
15abab9a0a56afc2109d24f6118ffa0767b1b249 | zack4114/Amazon-Questions | /FindElementsThatSumToGivenValue.py | 1,577 | 3.890625 | 4 | # Find four elements that sum to a given value | Set 1 (n^3 solution)
# Given an array of integers, find all combination of four elements in the array whose sum is equal to a given value X.
# For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23,
# then your function should print “3 5 7 8” (3 + 5 + ... |
18115523baba4ec48eca358cfb9cab180330fb2f | elazafran/ejercicios-python | /Listas y Diccionarios/ejercicio8.py | 883 | 4.0625 | 4 | '''
8.Introducir cadenas hasta que el usuario no desea insertar más en una lista.
Para cada cadena se imprimiera el siguiente mensaje dependiendo de su longitud .
Si la longitud es menor de 5 pondrá el nombre de la cadena y que es menor que 5
y en caso contrario pondrá que es mayor que 5 y la cadena
Juan menor que 5... |
82691f1ccae9b31fe8c446402f1e96ca8156828b | jocelinoFG017/IntroducaoAoPython | /01-Cursos/GeekUniversity/Seção06-Estruturas_Repetição/Ranges.py | 447 | 4.5625 | 5 | """
Ranges são utilizados para gerar sequencias numericas, não de forma aleatoria
mas sim de forma especificada.
Formas gerais:
Forma 01:
range(valor_de_parada)
Exemplo forma 01:
for numero in range(11):
print(numero)
Forma 02:
range(valor_de_inicio, valor_de_parada)
Exemplo forma 02
for numero in range(1,11):... |
023afcf9f6c04911bdf0087ca6ebbdc87adfc741 | raingang/python_beginner | /BattleShips.py | 1,424 | 3.578125 | 4 | def damaged_or_sunk(board, attacks):
'''
https://www.codewars.com/kata/battle-ships-sunk-damaged-or-not-touched/python
'''
not_touched = []
damaged = []
sunk = []
points = 0
unwrapped_board = []
for y in board:
for x in y:
unwrapped_board.append(x)
for strike ... |
3b7fc806911fe03a3fb7db7b0b63c97001f22658 | samuelcm/estrutura_sequencia | /salario.py | 433 | 4.03125 | 4 | #Faça um Programa que pergunte quanto você ganha por hora e o
#número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
salario_hora = float(input("Calculador de salário. \n Quanto voce ganha por hora?\n"))
horas_trabalho = int(input("quantas horas você trabalhou esse mês?\n"))
pri... |
2e5c3a3e9352be8e74800c5e7a86a82d65eb037a | ninepillars/trunk | /example/pythonexample/bookexample/lession_3/lession_3_9_10.py | 376 | 3.53125 | 4 | # coding: utf-8
'''
Created on 2011-12-8
@author: Lv9
'''
class DistanceFrom(object):
def __init__(self, origin):
print('!!!!')
self.origin = origin;
#类似回调函数
def __call__(self, x):
print(x);
return abs(x - self.origin);
nums = [1, 34, 33, 775, 55, 6, ... |
abc3656486c2ca074a26e9979a6abf9ac3ec121c | Heyho-letsgo/python03 | /continue.py | 366 | 3.75 | 4 | __author__ = 'andrew'
i = 1
nombre = input("Saississedez un nombre :")
nombre = int(nombre)
print(type(nombre))
while i < nombre:
if i % 3 == 0:
i += 4
print("On incrémente i de 4. i est a présent égal à", i)
continue
print("la... |
9162629c85375d5fd0ad1f035152a54da3f20b90 | 3453566/pythonbook | /10个编程技巧/列表解析式.py | 299 | 4.0625 | 4 |
# 都变成大写
fruit = ["apple",'orange',"banana","balabala"]
print(fruit)
fruit = [x.upper() for x in fruit]
print(fruit)
#挑选出以b开头的水果
b = []
for x in fruit:
if x.startswith("B"):
b.append(x)
print(b)
b = [x.lower() for x in fruit if x.startswith("B")]
print(b)
|
479a04dee3347017c1705cb88efd06965a4413d6 | phuuda/python-hw | /homework_1/task_2.py | 1,573 | 3.796875 | 4 | class Vehicle(object):
def __init__(self, manufacturer, model, year):
self.manufacturer = manufacturer
self.model = model
self.year = year
class Bike(Vehicle):
def __init__(self, manufacturer, model, year):
super().__init__(manufacturer, model, year)
class Bicycle(Bike)... |
dddf30e49f3c85f80f5d1e840d012ee1eba67b02 | britannio/Python-experiments | /Section-1-Fundamentals/main.py | 4,273 | 4.0625 | 4 |
'''
Notes
-----
in psuedo code variable assignment is shown with an arrow insead of an
'''
import math
i = 0 # int
name = "Britannio"
myFloat = 5.6 # also called a real (real number)
myChar = "h" # demo char
# int myInt = 4 explicit casting
number = myFloat * myFloat + myFloat - (2 * myFloat) ** 2 % 5
print(nu... |
031c4e4b335169fa8b3b9d56021d84fdb6e116ca | afridakarim/StatisticsCalculator | /Statistics/StandardDev.py | 467 | 3.703125 | 4 | import math
from Statistics.Mean import mean
from Calculator.Square import square
def StdDevSample(data):
Sum1 = 0
for i in data:
x = abs(i - mean(data))
Sum1 = square(x) + Sum1
n = len(data)
stdDev = math.sqrt(Sum1 / (n - 1))
return stdDev
def StdDevPop(data):
Sum2 = 0
f... |
a2e219f889d93ba3cb69f1628277d1f5ec60e6d6 | shinhaeran/Algorithm | /6603.py | 568 | 3.59375 | 4 | from itertools import permutations
def select_num(lotto,n,nums):
if len(nums) == len(lotto):
print(nums)
return
# range(n,len(lotto)-(6-n-1))
for e in lotto[n:-(6-n-2)]:
temp = nums[:]
temp.append(e)
select_num(lotto,n+1,temp)
while True:
l1 = input().split()
... |
bf23db2e7ddc04331280b365e6b5d1c308b27c94 | wenziyue1984/python_100_examples | /053按位异或^.py | 323 | 3.921875 | 4 | # -*- coding:utf-8 -*-
__author__ = 'wenziyue'
'''
学习使用按位异或 ^
'''
if __name__ == '__main__':
a = 2
b = a ^ 5
print('a ^ 5 = {}'.format(b))
b ^= 7
print('b ^ 7 = {}'.format(b))
'''
按位异或
对位相加,特别要注意的是不进位.
2 ^ 5 = 010 ^ 101 = 111 = 7
7 ^ 7 = 111 ^ 111 = 000 = 0
''' |
bb2309afbe4c233ca5d25934cc347b1065034f27 | rajivs15/set_6 | /printnearsteven.py | 75 | 3.65625 | 4 | n=int(input())
if n%2==0:
print(n+1-1)
else:
print(n-4+3)
#printing even
|
726fa01fac0531d38d99ea89cfe3b78c4cd002ba | teyden/llist | /LinkedList.py | 7,309 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LList:
"""
Linked list data structure. All methods implemented recursively
except insert and delete.
This is a linear singly linked list. Doubly linked lists have two pointers
in each node, one for prior, one for next. Circula... |
80fb6f68d90a2b412dcf8377c698da2a296954d2 | Fengyongming0311/TANUKI | /小程序/BaseKnowledge/classmethod如何使用.py | 1,835 | 4.1875 | 4 | class Data_test(object):
day=0
month=0
year=0
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year
def out_date(self):
print ("year :")
print (self.year)
print ("month :")
print (self.month)
print ("day :")
print (self.day)
#t=Data_test(2016,8,1)
#t.out_date()
"... |
3fe52ca811237c653fff627c0cf8af8c48909c73 | prasang-gupta/online-courses | /data-structures-and-algorithms-specialization/course-01-algorithmic-toolbox/assignment/week-04/points_and_segments.py | 1,667 | 3.953125 | 4 | # Uses python3
import sys
def binary_search_right(a, x):
left, right = 0, len(a) - 1
while left <= right:
mid = left + (right - left) // 2
if a[mid] > x:
right = mid - 1
else:
left = mid + 1
return left, mid, right
def binary_search_left(a, x):
left, rig... |
1504e06e6245b89175f60c5451b6c4f76a225d64 | PaulGuo5/Leetcode-notes | /notes/0246/0246.py | 293 | 3.734375 | 4 | class Solution:
def isStrobogrammatic(self, num: str) -> bool:
rotated = {"1":"1", "6":"9", "8":"8", "9":"6","0":"0"}
new = ""
for i in num:
if i not in rotated:
return False
new += rotated[i]
return new[::-1] == num
|
a8b67b5993b2bdb71df41f0dce016b1d6e175fb1 | rowlingz/Deepen-learning-Python | /online_programming/addTwoNumbers.py | 3,423 | 4.03125 | 4 | # -*- coding:utf-8 -*-
# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
#
# 示例:
# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
# 输出:7 -> 0 -> 8
# 原因:342 + 465 = 807
# Definition for singly-linked list.
class ListNode:
def __init__(self,... |
e6da7cd0d8ebcedc5e9e1ef31f169e121704f750 | NathanEngle/Python_BinarySearch | /Python_BinarySearch.py | 3,513 | 4.3125 | 4 | #Nathan Engle
#August 26, 2021
#Program Description: A Python-based implementation of a merge sort and binary search. A simple menu system gives the options of sorting/searching a list of numbers or words.
#Sample data provided consists of 2000 random integers and 2000 random words
from sys import exit as sys_exit
def... |
ea845040e5a23b9fb5c171ef6b39daa2447d9d6b | VIsh76/Projet_Departement | /select_var.py | 1,544 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
def find_var(key_word, filename):
with open(filename,'r') as f:
lis = [x.split(',') for x in f]
for x in zip(*lis):
print(y)
def selection_X(filename):
A= []
V=[]
f = open(filename, "r")
data = f.readlines()
f... |
56ee400b2a1d21b2326ea734a85598e6b8de4953 | return007/shater | /src/connection.py | 3,592 | 3.734375 | 4 | import sys
import json
import os
import socket
class Connection(object):
'''
The class helps create TCP connection using socket library.
Also provides some high level methods to send and receive Command objects.
'''
def __init__(self, sock=None, ip='', port=12345, sock_type='server_sock', **kwargs):
'''
Inti... |
feaaf6ef8671318a1afd5a6f4632c87833f957c8 | Sheep-coder/practice2 | /Python00/chap04list0411.py | 236 | 3.71875 | 4 | # for分による整数値のカウントアップ(ソート後のaからbまで)
a = int(input('整数a'))
b = int(input('整数b'))
a,b = sorted([a,b])
for counter in range(a,b+1):
print(counter,end=' ')
print()
|
6803f94e167688d71db9e4c529252305aac8474d | christiantriadataro/Multilingual-Online-Translator | /Stage 2/main.py | 8,709 | 3.90625 | 4 | # Stage 2/7: Over the internet
# Theory
# User-Agent field in a request
# When you use requests library, you can pass headers arguments to
# the function get(). Headers are text data you send over HTTP that
# might contain information about a web browser or application you use
# to surf the web. Your program doesn't... |
4d41d0f72440f648c6c908dffbcd68c30ef25351 | jz48/StatsCalculatorGroup_TeamDJ_IS601 | /src/StatsCalc.py | 2,156 | 3.578125 | 4 | from statistics import mode
from Calc import Calculator
class StatsCalculator(Calculator):
result = 0
def __init__(self):
super().__init__()
def mean(self, nums):
res = 0
counter = 0
for i in nums:
res = self.add(res, i)
counter = counter + 1
self.result = self.division(counter, res)
return se... |
acc8f586d41cd99d70b2be94b0e51fde530b31df | JuanUrena/X-Serv-13.6-Calculadora | /calculadora.py | 1,263 | 3.859375 | 4 | #!/usr/bin/python3
#Juan Ureña García-Gasco_Calculadora
import sys
# tomar datos desde la ejecucion del programa
from sys import argv
# importa una funcion concreta para no tener que llamarla de sys
# Obtengo los datos desde la linea de comandos
# Compruebo el valor de la operacion para llevarla acabo
def suma(op1,op... |
b298f445eb877b4363fc623311d9861706013163 | sabbycs50/pihat | /hat_random_pixels.py | 469 | 3.59375 | 4 | #!/usr/bin/env python
#this script will display letters with random colors on the Pi HAT
from sense_hat import SenseHat
import time
import random
sense = SenseHat()
blinks = input()
xcoord = random.randint(0,7)
ycoord = random.randint(0,7)
for x in range(blinks):
sense.set_pixel(xcoord, ycoord, (random.randint(0... |
470c4550442ac2be2632f699769812721bc7d1ea | davissandefur/Computational-Physics | /Chapter2/problem_thirteen.py | 666 | 3.90625 | 4 | # Davis Sandefur
# Completed 20/4/15
# Part A: Catalan numbers with recursion
def catalan(n):
"""
:param n: Whole number of whichever Catalan number you want to find (such as C10)
:return: Cn
"""
if n == 0:
return 1
else:
return ((4*n-2)/(n+1))*catalan(n-1)
# Part B, Euclid ... |
386a366951df2919b02246e3143cf17e60fd9dfd | dswe2022/Algorithms-reimagined | /19/19.9/19.9- Test the Collatz conjecture in Parallel.py | 1,028 | 3.984375 | 4 | # 19.9 Test the Collatz conjecture in parallel
# Design a multi-threaded program for checking the Collatz conjecture.
# Make full use of the cores available to you. To keep your program from overloading the system,
# you should not have more than n threads running at a time.
# hint: try using a multi-threaded checke... |
2009bbc54f504099d234db000105b7865ad4ee08 | catseye/Samovar | /src/samovar/database.py | 2,796 | 3.703125 | 4 | from samovar.ast import Assert, Retract
class Database(object):
"""A database is a set of things true at some point in time in a world."""
def __init__(self, propositions, sorted_search=True):
"""Create a new Database object with the given propositions.
While the construction and iteration o... |
4971b335ebf7f28b1bdb37c5710e780006c84816 | AgentT30/InfyTq-Foundation_Courses | /Object Oriented Programming Using Python/Day 4/fruit_farm.py | 2,146 | 3.546875 | 4 | class FruitInfo:
__fruit_name_list = ['Apple', 'Guava', 'Orange', 'Grape', 'Sweet Lime']
__fruit_price_list = [200, 80, 70, 110, 60]
@staticmethod
def get_fruit_price(fruit_name):
for i in range(len(FruitInfo.__fruit_name_list)):
if fruit_name == FruitInfo.__fruit_name_list[i]:
... |
f36c70bbe1037bcb9973a8dfd4426a732e8d7e4f | bikongyouran/python_practice | /BasicConception/set.py | 280 | 3.546875 | 4 | # a = ()
# print type(a)
# a = set()
# print type(a)
# a = set([1, 2, 3, 1])
# print a
# a = {1, 2, 3, 1}
# print a
# a = {1, 2, 3, 4}
# b = {3, 4, 5, 6}
# print a.union(b)
# print b.union(a)
# print a | b
# frozenset is immutable.
# s = frozenset([1, 2, 3, 'a', 1])
# print s
|
67004a0b5b6f5621fe066942a0b48344d59b00c0 | HoangHuuDien/hoanghuudien-fundamentals-c4e16 | /Session01/Bai-Tap/Draw/Draw-a-square.py | 146 | 3.6875 | 4 | from turtle import *
speed(-1)
color('red')
shape('turtle')
begin_fill()
for i in range(4):
forward(100)
left(90)
end_fill()
mainloop()
|
80755f8137ae76c15e6c48d2553a1c81290c1d2d | EderOBarreto/exercicios-python | /ex078.py | 551 | 3.859375 | 4 | numeros = list()
max = 0
min = 0
for i in range(0, 5):
numeros.append(int(input('Digite um número: ')))
if i == 0:
max = min = numeros[0]
elif numeros[i] > max:
max = numeros[i]
elif numeros[i] < min:
min = numeros[i]
print(f'\nO maior valor é {max},nas posições', end='')
for ... |
8d4bc8b3a095ff4392ba41b457491ae1df319b50 | clbmrls14/AdventofCode2020 | /day3/day3.py | 1,039 | 3.9375 | 4 | def findTrees(lines, right, down):
indent = 0
totalTrees = 0
skip = down
for line in lines:
if skip is not down:
skip += 1
else:
line = line.rstrip('\n')
if line[indent] == '#':
totalTrees += 1
indent += right
if... |
d76dc414b742a81df5cb67d353acd35df54a4af6 | GentFromPhoenix/CS101_Udacity | /unit2_endproblems.py | 4,224 | 4.28125 | 4 | # --- Find the Median
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
# --- My solution
def median(a,b,c):
if a == biggest(a,b,c):
a = 0
return biggest(a,b,c)
if b == biggest(a,b,c):
b = 0
return big... |
8e6135015ff839594b10b2e287e970d4bcaea646 | pollygee/pong | /pong.py | 4,538 | 3.8125 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
import math
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT ... |
2eeeaea110489d33f0a6267e35c202d8b2a2c5c5 | koboskom/python_projects | /some_basic_programs/cross_circle.py | 1,261 | 3.796875 | 4 | table = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
def rysuj():
print("- - - - - - -")
print("| {0} | {1} | {2} |".format(table[0], table[1], table[2]))
print("| {0} | {1} | {2} |".format(table[3], table[4], table[5]))
print("| {0} | {1} | {2} |".format(table[6], table[7], table[8]))
prin... |
95e9e453be84f10aa2a150a59eb04d0db553abe0 | alexbaltman/c-h-e-c-k-i-o | /elementary/days-diff/script.py | 253 | 3.90625 | 4 | def days_diff(date1, date2):
"""
Find absolute diff in days between dates
"""
from datetime import date
a = date(date1[0], date1[1], date1[2])
b = date(date2[0], date2[1], date2[2])
c = a - b
return abs((a - b).days)
|
8f95714830df79705ca787da6d36ef0991899c84 | jbrg/cursesMenu | /example.py | 534 | 3.75 | 4 | import curses
import cursesMenu
mainMenu = cursesMenu.MainMenu("Example menu")
exampleList = ["Example 1", "Example 2", "Example 3", "Example 4"]
for x in exampleList:
mainMenu.addItem(x)
while True:
c = mainMenu.getch()
if c == ord('q'):
mainMenu.destroy()
break
elif c == curses.KEY... |
03a54ba81aeb6dbbe2cd75c1e4ddbb5a60642137 | RENAN-KALIO/Dias_Menor_triangulo_Primo_python | /triangulo.py | 309 | 3.984375 | 4 | a = int(input("Digite um valor"))
b = int(input("Digite um valor"))
c = int(input("Digite um valor"))
if a + b > c & a + c > b & b + c > a:
Area = (a + b + c) / 2
print("A área do trinangulo é,".format(Area))
print("Forma um triangulo.")
else:
print("Não forma triângulo algum.") |
1b6ec814233a2f055326ed3838a0716e75abbbbc | 1067511899/tornado-learn | /codewars/level7/Simplestringreversal.py | 574 | 4.375 | 4 | '''
In this Kata, we are going to reverse a string while maintaining spaces.
For example:
solve("our code") = "edo cruo"
-- Normal reversal without spaces is "edocruo".
-- However, there is a space after the first three characters, hence "edo cruo"
solve("your code rocks") = "skco redo cruoy"
solve("codewars") = "s... |
f4b4fb2c038ffc25084e6bee0dfb590701df3578 | CodeHemP/CAREER-TRACK-Data-Scientist-with-Python | /27_Unsupervised Learning in Python/01_clustering-for-dataset-exploration/08_clustering-stocks-using-kmeans.py | 1,791 | 4.03125 | 4 | '''
08 - Clustering stocks using KMeans
In this exercise, you'll cluster companies using their daily stock price
movements (i.e. the dollar difference between the closing and opening prices
for each trading day). You are given a NumPy array movements of daily price
movements from 2010 to 2015 (obtained from Yahoo! F... |
3a2e859bee515e4f3b77d3b4753d29bd4b51b5b7 | SAATVICK2006/THE-LABYRINTH | /guessingGamec97.py | 794 | 4 | 4 | import random
number = random.randint(1,9)
life = 4
print("YOU GOT 4 CHANCES TO GUESS A NUMBER IN BETWEEN 1 AND 10.")
guess = int(input("Guess a number in between 1 and 10: "))
while life >= 1:
if guess == number:
print ("CORRECT!YOU ARE THE AKINATOR!")
break
if life == 1:
print("YOU... |
88f1d0cb3071c65d46cc9ba834464a3614a33092 | Santhilata/Python-scripts | /ShotestWordDistance.py | 547 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 23 11:23:40 2020
@author: santhilata
"""
"""
Given a list of words and two words word1 and word2, return the shortest distance
between these two words in the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1= “codi... |
d2c3bf0896683ea829141b2904f11d5c8c36c38a | kylin5207/MachineLearning | /numpy/roundNumber.py | 628 | 3.5 | 4 | # -- coding = 'utf-8' --
# Author Kylin
# Python Version 3.7.3
# OS macOS
"""
数据取整
np.ceil():向上取整
np.floor():向下取整
np.rint(): 四舍五入
"""
import numpy as np
def main():
data = np.array([1, 1.1, 1.5, 2.4])
print("Initial data:")
print(data)
# 使用rint()取整
data1 = np.rint(data)
print("四舍五入取整:")
... |
64becce3799e30436efab610e56c17f6d74ef1b6 | tfiers/unitlib | /src/unitlib/operations/power.py | 2,282 | 3.6875 | 4 | """
Exponentiation
--------------
Examples:
- mV ** 2
- (8 mV) ** 2
- ([3 8 1] mV) ** 2
- (8 mV) ** [[2]] (This becomes [[64]] mV²).
But not:
- mV ** (8 mV)
- mV ** [3, 8] (Would yield a list with different unit per element).
- mV ** (1/2)
"""
import numpy as np
from unitlib.core_objects i... |
3490785df178d53b62e1f47f27e10f219660babb | AdamZhouSE/pythonHomework | /Code/CodeRecords/2737/60638/281468.py | 286 | 3.578125 | 4 | numbers=list(map(int,input()[1:-1].split(",")))
numbers.sort()
res=[]
for i in range(0,len(numbers)):
count=1
k=numbers[i]
while i<len(numbers)-1 and numbers[i]==numbers[i+1]:
count=count+1
i=i+1
if count>len(numbers)//3:
res.append(k)
print(res) |
d84e0ea2c14430edd91ca212608fc1d67f0a536d | Zhoroev/Exam_2 | /task2.py | 1,321 | 4.34375 | 4 | text_1 = 'Advertising companies say advertising is necessary and important. It informs people about new products. Advertising hoardings in the street make our environment colorful. And adverts on TV are often funny. Sometimes they are mini-dramas and we wait for the next program in the mini-drama. Advertising can educa... |
0dc0d133d28cfb1aef2a3379d03ed6778a32ae3b | tzuyichao/python-basic | /basic/hand-7-1.py | 253 | 4.125 | 4 | data = {}
for i in range(0, 3):
name = raw_input("Name? ")
age = int(raw_input("Age? "))
data[name] = age
print(data)
lookup = raw_input("Lookup name?")
if lookup in data.keys():
print("Age: ", data[lookup])
else:
print("Not Found") |
efbf8ea69d5abec35387be603c6a1164a0640bc4 | abhishekhm/Basic-Python-Programs | /classlogicgates.py | 2,459 | 3.890625 | 4 | class LogicGate:
def __init__(self,n):
self.label = n
self.output = None
def getLabel(self):
self.label = input("What gate name would you like?")
return self.label
# we can delcare a function that is yet undefined
# and define its logic later
def getOutput(... |
cf5f4f944e184cefc62dd5896d2d29ee9d9b289a | Zpadger/Python | /100Days/Day13/coroutine_ex2.py | 946 | 3.609375 | 4 | # yield实现协程的例子
# 吃包子模型
#定义一个消费者,他有名字name
#因为里面有yield,本质上是一个生成器
import time
def consumer(name):
print(f'{name}准备吃包子啦!,呼吁店小二')
while True:
baozi = yield #接收send传的值,并将值赋值给变量baozi
print(f'包子 {baozi+1} 来了,被 {name} 吃了!')
#定义一个生产者,生产包子的店家,店家有一个名字name,并且有两个顾客c1 c2
def producer(name,c1,c2):
next(c... |
7ae88acfb75b8a54128fd3459e57683d7a5bc14a | afaf-tech/PythonOOP | /OopS/12 Pendahuluan Inheritance.py | 336 | 3.5625 | 4 | class Hero:
def __init__(self,name, health):
self.name = name
self.health = health
class Hero_iintelligent(Hero):
pass
class Hero_strength(Hero):
pass
lina = Hero('lina', 100)
techies = Hero_iintelligent('techies', 50)
axe= Hero_strength('axe', 200)
print(lina.name)
print(techies.name)
... |
583028578454bb751f3b0fde5d1f7a286fd17590 | DanielLimasP/automate-tbs | /organizing-files.py | 2,072 | 3.578125 | 4 | import os, shutil, zipfile
from pathlib import Path
import send2trash
if __name__ == "__main__":
p = Path.cwd()
# Folders that make up the destination must already exist,
# or else Python will throw an exception.
shutil.copy(p / 'files/spam.txt', p / 'test_folder')
shutil.copytree(p / 'files', p ... |
77f142778b8108dd1a21832e156bc8c23eb507c6 | jhiltonsantos/ADS-Algoritmos-IFPI | /AtividadeURI_3_Iterações/uri_1143_quadrado_ao_cubo.py | 332 | 3.78125 | 4 | def main():
valor = int(input())
cont = 1
calcule(valor,cont)
def calcule(valor, cont):
x = 0
y = 0
z = 0
while cont <= valor:
x += 1
y = x**2
z = x**3
print('{} {} {}'.format(x,y,z))
cont += 1
if __name__ == '__main__':... |
7ddf9f806a4e4f302a148056dbe817f91dd036c5 | hoshizorahikari/PythonExercise | /LintCode/LintCode-30:插入区间.py | 2,185 | 4.21875 | 4 | """
给出一个无重叠的按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
样例:插入区间[2, 5] 到 [[1,2], [5,9]],我们得到 [[1,9]]。
插入区间[3, 4] 到 [[1,2], [5,9]],我们得到 [[1,2], [3,4], [5,9]]。
标签:领英 基本实现 谷歌
"""
# Definition of Interval.
class Interval():
"""区间的定义"""
def __init__(self, start, end):
self.start = sta... |
4fc2f3d9156f218f45ab91dbe3ade09bce824143 | portnojek/my_notes_python | /zaawansowane_typy_danych.py | 5,471 | 3.78125 | 4 | '''Lista - pojemnik do przechowywania elementów, która jest numerowana od 0
Przykład listy :
imiona = [ “Arkadiusz”, “Wioletta”, “Karol”, “Kuba”, “Adrian” ]
0 1 2 3 4
imiona - nazwa listy
[ ] - klamra kwadratowa, która oznacza że tworzymy listę
“Arkadiusz”, “Wioletta”, ... |
8370e8d257bab5bfeedafbfe6307682dffd916f9 | hraf-eng/coding-challenge | /question03.py | 1,473 | 4.3125 | 4 | # 3. Check words with typos:
# There are three types of typos that can be performed on strings: insert a character,
# remove a character, or replace a character. Given two strings, write a function to
# check if they are one typo (or zero typos) away.
# Examples:
# pale, ple > true
# pales, pale > true
# pale, bale ... |
f0377f24bc7ccad3a7d26778cb32d26981c560fd | cukejianya/code-contest | /30DaysOfCode/day10.py | 256 | 3.765625 | 4 | def binaryConversion(dec):
new_dec = dec // 2
r = dec % 2
if new_dec == 0:
return str(r)
return binaryConversion(new_dec) + str(r)
T = int(raw_input())
for x in range(T):
dec = int(raw_input())
print binaryConversion(dec)
|
81eb233f80943036b7b8f77a10cd4ac737737f34 | bhavanakurra29/Assignment3 | /Assignment 3.py | 1,142 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Question 1
# In[1]:
# Write a python program to merge two files into a third file
# In[ ]:
import shutil
from pathlib import Path
firstfile = Path(r'C:\Users\Sohom\Desktop\GFG.txt')
secondfile = Path(r'C:\Users\Sohom\Desktop\CSE.txt')
newfile = input("... |
ad56c8a3462159907e738d4f6b0ae54cd95a616d | TGITS/programming-workouts | /exercism/python/armstrong-numbers/armstrong_numbers.py | 178 | 3.765625 | 4 | def is_armstrong_number(number):
number_as_string = str(number)
power = len(number_as_string)
return number == sum([int(digit)**power for digit in number_as_string])
|
31871fd58780b25202f13ccf2a1f044336c372e3 | Divyaansh313/100DaysofCode | /ThreeInARowExtension.py | 1,966 | 4.46875 | 4 | """
TODO: Three in a row extension
You should randomly generate addition, subtraction, multiplication and division problems until the user has gotten 3 problems correct in a row.
(Note: the number of problems the user needs to get correctly in a row to complete the program is just one example of a good place to specif... |
16f0df8fc12ee71620646480186c7a67987acec4 | samruddhibenkar/LetsUpgrade-Python-Essentials | /All Assignments/Assignment 5.py | 867 | 3.84375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Samruddhi Benkar - Assignment No 5
# ## Write a program to identify sub list [1,1,5] is there in the given list in the same order, if yes print “it’s a Match” if no then print “it’s Gone” in function.
# In[2]:
x = [1,5,6,4,1,2,3,5]
y = [1,1,5]
def check(a,b):
for i in... |
81351752f4e10b80e62e240342f94802137ad0a5 | thanhlct/alex | /alex/utils/database/python_database.py | 5,576 | 3.625 | 4 | import codecs
import os
import random
import pdb
class PythonDatabase(object):
'''In this project, this database class is also working as a ways of finding out the good interface, prototype of database for SDS apps'''
'''Python database helper - every data is saved in Python data structure, which can also load... |
eb303f1a0f9da4a5429336728811b86e19b95ca6 | RICSHUKL/Richa-PYTHONLearn | /s_slicing.py | 378 | 4.09375 | 4 | # this Program is to understand slicing of a string
string1 = 'This is practice session fo python programing'
print(string1[::3])
print(string1[1::1]) # Positive index left to right
print(string1[1::-1]) # Negative index right to left
print(string1[-4:])
print(string1[-4::-1])
# Repeating of string
print(string1*3,e... |
a7f08232d984b3f64365a740626e711cfbd7ea53 | andruraj/PythonTuts | /tuts/Serialization.py | 3,379 | 4.125 | 4 | #Serialization => json
#Python provides built-in JSON libraries to encode and decode JSON.
#Encoding
import json
json_string = json.dumps([1, 2, 3, "a", "b", "c"])
print(json_string)
#dumps() method converts dictionary object of python into JSON string data format.
x = {
"name": "Ken",
"age": 45,
"married": True... |
9a2d77750399dbf79911683e9e8bb7cbf261c536 | omkarkaptan/autoencoder | /utils/imageutils.py | 1,564 | 3.5625 | 4 | import os
import array
def read_pgm_image(pgmf):
"""Return a raster of integers from a PGM as a list of lists.
Number of lists within the raster = height of the image.
Number of elements within each list in the raster = width of the image """
image_header = pgmf.readline().split()
assert imag... |
35c5a56b4ad6b1c2d66307e29a487fad139b982f | Saiteja9112/phython | /q4.py | 120 | 4.0625 | 4 | #print elements of the list using for loop
listB = [1,3,2,4,5,6,7,8]
for x in range(len(listB)):
print (listB[x])
|
31c3a3895575e7d548260493fa1b422be2c5f700 | alekyahq/-AI-Driven-App-Batch1 | /Python/functions.py | 289 | 3.9375 | 4 | #1 function definition
def sayHello():
print("Hello, Welcome")
#2 function calling
#sayHello()
#3 function parameters
def add(num1, num2):
print(num1 + num2)
#add(2,4)
#4 function return statements
def mult(num1,num2):
return num1 * num2
total = mult(7,8)
print(total)
|
1db7b8565f9f25bc6f52867871d6216f06decbd8 | kinosal/predictor | /model/preprocessing.py | 3,915 | 3.625 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def data_pipeline(data, output):
"""
Preprocessing pipeline part 1: Transform full data frame
Arguments: Pandas dataframe, output column (dependent variable)
Returns: Modified dataf... |
867a4663eb1cfb3858da736e3284ccbe66b6a024 | GParolini/python_ab | /listcomprehension/cubesofnumbers.py | 262 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 22:19:51 2019
@author: giudittaparolini
"""
lst = []
for x in range (1,11):
lst.append(x**3)
print(lst)
print ("--------")
lst1 = []
lst1 = [x**3 for x in range (1,11)]
print(lst1) |
746cd7dbfd7f74914cd5d3698f125fd596703594 | hyejun18/daily-rosalind | /scripts/bioinformatics-textbook-track/BA8D.py | 923 | 4.21875 | 4 | ##################################################
# Implement the Soft k-Means Clustering Algorithm
#
# http://rosalind.info/problems/BA8D/
#
# Given: Integers k and m, followed by a stiffness
# parameter , followed by a set of points Data
# in m-dimensional space.
#
# Return: A set Centers consisting of k poi... |
f8f23abc85db34c06801277805aee35accb730a6 | TauqeerAhmad5201/Python-OOPS | /5_class_method as alternative constructor.py | 756 | 3.53125 | 4 | class Employee:
no_of_leaves = 10
def __init__(self,name,eno):
self.name = name
self.eno = eno
def printdetail(self):
return f"Employee name is {self.name} with e_no as {self.eno}"
@classmethod
def change_leave(cls,newleave):
cls.no_of_leaves = newl... |
31d835cb2d79e453ed92055eedef6b35d03f78c0 | Pushergene/grund-prozentwert-und-prozentsatz-rechner. | /simplecalc.py | 1,140 | 4.0625 | 4 | def ProzentwertRechnen():
Grundwert = float(input("Geben Sie Grundwert an: "))
Prozentsatz = float(input("Geben Sie Prozentsatz an: "))
Prozentwert = float(Prozentsatz * Grundwert / 100)
print("Prozentwert: ", Prozentwert)
print("Grundwert plus Prozentwert : ", Grundwert + Prozentwert)
print("Grundwert minus Proz... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.