blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2ee2bb41ea1d31f6a7f55c30e38d1355afc8f8ae | tranvanquan1999/k-thu-t-l-p-tr-nh | /th24.py | 235 | 3.578125 | 4 | # viết chương trình nhập số tự nhiên n>0, in ra màn hình các số tự nhiên giảm dần ừ n đến 0 mỗi kí tự in trên một hàng
n=int(input("nhap so tu nhien n>0:"))
while n>=0:
print(n);
n=n-1; |
dcde41bc5a615f0e5d5325c0d4a203bbd727de5f | Enigmamemory/submissions | /7/intro-proj1/Steven-Richard/BESTPOKEDEX.py | 2,899 | 3.546875 | 4 | def pokedexreader():
'''
reads the source code of a bulbapedia to extract data
'''
sourcecodedata=open("Pokedex").readlines()
codedata=[]
pokemondata=[]
pokedexnumber=0
pokedexname=""
onedigitcase=""
for x in sourcecodedata:
if '<span class="plainlinks"><a href="/wiki/' i... |
0601ecfe7c3c14feefb74c06374483d34302343d | Temitope-A/movietopics | /reviewmovies.py | 1,061 | 3.53125 | 4 | def review(movie):
from names import keys, current_dir
import os
title = movie.title
year = str(movie.year)
print('M > Insert an integer between -3 (value totally on the left)'
'and 3 (value totally on the right)')
att = {}
for key in keys:
flag = 0
while flag == 0:
... |
e7ce5c6822b45d062cc40acae49968e31c710e72 | summercake/Python_Jose | /12.For.py | 643 | 3.90625 | 4 | #
# for item in object:
# statements to do stuff
#
l = [1, 2, 3, 4, 5]
for v in l:
print(v)
for num in l:
if num % 2 == 0:
print(num)
else:
print('{x} is a odd number'.format(x=num))
print('%s is a odd number' % num)
list_num = 0
for num in l:
list_num += num
print(list_n... |
e443d0fe759f3929b7859def9d0db338f13021d1 | schlumpyj/Smart-Thermostat | /components/servoControl.py | 1,044 | 3.546875 | 4 | import RPi.GPIO as GPIO
from time import sleep
class ServoControl(object):
SERVO_UP_PIN = 3
SERVO_DOWN_PIN = 5
def __init__(self):
GPIO.setmode(GPIO.BOARD)
self.servoUp = self.addServo(self.SERVO_UP_PIN)
self.servoDown = self.addServo(self.SERVO_DOWN_PIN)
def addServo(self, ... |
67448215952d812af27886e23f0131fc486cb28a | yyotova/DungeonsAndPythons | /source_package/main_classes/potion.py | 283 | 3.65625 | 4 | class Potion:
def __init__(self, potion, points):
self.potion = potion
self.points = points
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __repr__(self):
return f'Hero has {self.points} points {self.potion} potion'
|
6870deebd6b1a8b49758791ed692a4ccbeea31a1 | gabreuvcr/curso-em-video | /mundo3/ex079.py | 478 | 4 | 4 | ## EX079 ##
numeros = []
while True:
num = int(input('Digite um valor: '))
if num in numeros:
print('Valor duplicado! Não irei adicionar.')
else:
numeros.append(num)
print('Valor adicionado com sucesso.')
while True:
r = str(input('Quer continuar [S/N]? ')).strip().upper... |
ddf04f0bcc05cdae71f6ec0ae04a9808ebf8d728 | bhanuprakashbalusu/Python-Fundamentals | /Dates&Times.py | 5,565 | 4.6875 | 5 | # In python we have date, time, datetime, timezone and timedelta. Let's explore all these.
# Main module to work with dates in python is datetime module
import datetime
import pytz
# before working with dates and times it is important to understand difference between naive and aware dates
# and times
# naive ... |
2eca5e85729872669ca4133b4d01125dd11c5c61 | Wenjie-Xu/Pandas-Learn | /21.transpose.py | 259 | 3.609375 | 4 | import pandas as pd
pd.options.display.max_columns = 999 # 设置展现的最大列数
students = pd.read_excel('/Users/Apple/Desktop/pandas/transpose.xlsx', index_col='name')
table = students.transpose() # 旋转数据后生成新的DataFrame
print(table) |
6e2ce815bfc96bd7b33ca07a0eff0c20de4a6d1a | kumbharswativ/Core2Web | /Python/DailyFlash/14mar2020/MySolutions/program4.py | 431 | 3.546875 | 4 | '''
write a program to print the following pattern
0
2 3 4
2 4 6 8 10
0 3 6 9 12 15 18
'''
for i in range(4):
a=0
b=1
for j in range(7):
if(i+j<=2 or j-i>=4):
print(" ",end=" ")
else:
if(i==0):
print("0",end=" ")
elif(i==1):
print(b+1,end=" ")
... |
ae1a0a6cbb2b0d2c800568d3aa2929f0d39b1644 | AmirYousofAbdi/ml_projects | /LinearR_attempt_1.py | 1,459 | 3.640625 | 4 | ##########
########## Notice that this code will return the average of accuracy of n times prediction and it would predict the last column!
##########
from sklearn import linear_model
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_sc... |
2048b396655f1f3e17cea71dd7290043295e0180 | tsmcalister/vsimcon | /vsimcon/controllers/fixed_controller.py | 737 | 3.53125 | 4 | from .abstract_controller import AbstractController
from typing import Callable
class FixedController(AbstractController):
def __init__(self, phi_t: Callable[[float], float]):
self.t = 0
self.phi_t = phi_t
@property
def output(self) -> float:
return self.phi_t(self.t)
def upd... |
cdf94c6238c9f18e1aad3a98d133f0bbd343622b | Ekeopara-Praise/python-challenge-solutions | /Ekeopara_Praise/Phase 2/TUPLE/Day 52 Tasks/Task8.py | 320 | 4.625 | 5 | '''8. Write a Python program to create the colon of a tuple.'''
from copy import deepcopy
#create a tuple
tuplex = ("HELLO", 5, [], True)
print(tuplex)
#make a copy of a tuple using deepcopy() function
tuplex_colon = deepcopy(tuplex)
tuplex_colon[2].append(50)
print(tuplex_colon)
print(tuplex)
#Reference: w3resource |
6d3a3deebf96a02caeaebd90731769df810cd1a8 | will-ing/data-structure-and-algorithms | /dsa-python/challenges/tree_intersection/tree_intersection.py | 317 | 3.640625 | 4 | def intersection(tree, tree_two):
while tree.root:
value = tree.root.val
duplicates(value, tree_two)
def duplicates(val, tree):
tree_list = []
while tree.root:
if val == tree.root.val:
tree_list.append(val)
else:
tree.root = tree.root.right_child
|
ec91b7f68906ca189ae77c79efc3487f54e1b2ee | wtomalves/exerciciopython | /ex033maior.py | 545 | 4.25 | 4 | um = int(input('Digite o primeiro número:'))
dois = int(input('Digite o segundo número:'))
tres = int(input('Digite o terceiro numeros:'))
if um > dois > tres:
print('Maior número é {}'.format(um))
if tres > dois > um:
print('Maior número é {}'.format(tres))
if dois > tres > um:
print('Maior número é {}'.fo... |
30eaab740d16cd0559a92e62ef67b4792dad2203 | IonutPopovici1992/Python | /LearnPython/basic_calculator.py | 135 | 3.921875 | 4 | number1 = input("Enter a number: ")
number2 = input("Enter another number: ")
result = float(number1) + float(number2)
print(result)
|
83d8cf95d0379f2c86bdbe93fbe3c6002904d41d | janraj00/AlgoStart | /zes2/prime.py | 292 | 3.546875 | 4 | def prime_test(n):
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 1
while 6 * i - 1 <= n ** 0.5:
if n % (6 * i - 1) == 0:
return False
if n % (6 * i + 1) == 0:
return False
i += 1
return True
|
a09c67a1c2a8936080a3dc0435770951e44053ff | justingolden21/synthetic-poe | /synthesizer.py | 3,071 | 4.0625 | 4 | import random
# input_text: the text used to generate our synthetic text
# size: number of characters we look back
# num_chars: the approx size of our output str
def synthesize(input_text, size, num_chars):
# create char dict
char_dict = {}
# for every char except the last (size) chars
for i in range(len(input_tex... |
7bf6a0ca936db2fc9ba8f8eec1389968398134f1 | aminbouraiss/flask-dashboard | /filterArray.py | 7,599 | 3.640625 | 4 | import numpy as np
import re
import csv
import json
import datetime as dt
from collections import namedtuple
def csvToTuple(filePath):
"""Convert a csv file to a list of tuples"""
with open(filePath, 'rb') as f:
reader = csv.reader(f)
converted = [tuple(row) for row in reader]
return c... |
a4ed9504c9668389f7796103efbe408d1a61942e | AnnHalii/Python_Hillel | /lk_11_hw/2_task.py | 443 | 3.984375 | 4 | class Person:
def __init__(self, age, name):
self.age = age
self.name = name
self.__friends = []
def know(self, other):
self.__friends.append(other)
def is_known(self, other):
return other in self.__friends
person1 = Person(18, 'Oleg')
person2 = Person(24, 'Dima')... |
3ae945229acf77acec03941cf128e213e574a546 | ashish-5209/TreeDataStructure | /sumTree.py | 713 | 3.875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def s1(root):
if root is None:
return 0
return s1(root.left) + root.data + s1(root.right)
def subTree(root):
ls = 0
rs = 0
if root is None or (root.left is ... |
f72fab6f02e1add20c4e595f7b433afc988fbee4 | danmackinlay/ipypublish | /nbconvert/latex_hide_input_output.py | 1,984 | 3.578125 | 4 | def remove_dollars(input, **kwargs):
"""remove dollars from start/end of file"""
while input.startswith('$'):
input = input[1:]
while input.endswith('$'):
input = input[0:-1]
return input
def first_para(input, **kwargs):
r"""get only ttext before a \n (i.e. the fist paragrap... |
e5e5d7397c8026abbf017a33cbf0eb3311f54600 | zhou-dong/python-study | /list-example.py | 1,327 | 4.25 | 4 | nums = [1, 3, 2, 15, 10]
print "len:", len(nums)
print "sum:", sum(nums)
print "min:", min(nums)
print "max:", max(nums)
for num in nums:
print num,
print
print "range:", range(len(nums))
# nums.sort()
print nums
for x in range(len(nums)):
print "index:", x, "; num:", nums[x]
print dir(nums)
print nums[... |
e82e9733a01b86a2d7f1b31025dfacf0386ba72d | soomark/Level_0_Chanllenges | /Task_0.1.py | 183 | 3.828125 | 4 | #Demonstrate the order of the program
#Output of x and y equals 0 and 1
x = 0
y = 1
print(x)
print(y)
#Output of x and y equals 3 and 4
x += 3
y += x
print(x)
print(y)
|
2e431cc4fa09c6d2eb339c4cfa0990eaf22f0647 | pavonvazquez/Proyecto | /pit.py | 107 | 3.96875 | 4 | n = int(input("Ingresa el numero: "))
print("El valor del numero es: %d"%n)
for i in range(n):
print(i) |
0016569aae8e3e1e60a417967232dd8a6b2f1217 | ssarrayya/python-deitel-exercises | /com/exercises/chapter_four/rounding_numbers.py | 450 | 3.890625 | 4 | # 4.8 (Rounding Numbers) Investigate built-in function round at
# https://docs.python.org/3/library/functions.html#round
# then use it to round the float value 13.56449 to the nearest integer,
# tenths, hundredths and thousandths positions.
# to the nearest integer
print(round(13.56449))
# to the nearest tenth
print... |
1357b9bab710207b0d3348a2ea0253e97a62482d | sumitkr4/DataStr | /Recursion/reverseString.py | 282 | 4.03125 | 4 | def reverse(string):
# # 1st Approach
# if len(string) == 0:
# return
# temp = string[0]
# reverse(string[1:])
# print(temp,end="")
if len(string)<=1:
return string
return reverse(string[1:]) + string[0]
print(reverse('I m a fan of fan')) |
944a60554bdab4d520e43c12a28f5387ce36b759 | abhisheknm99/APS-2020 | /39-Uppercase_to_lowercase.py | 212 | 4.21875 | 4 | #Converts the given string to lowercase
#Method1
def upper_lower(s):
res=[]
for i in s:
i=chr(ord(i)|32)
res.append(i)
return "".join(res)
s="ABcDE"
r=upper_lower(s)
print(r)
#Method 2
print(s.lower())
|
c67c71afe937e33419b115d1573cb32036c23376 | GustavoMarzullo/Livro-Guttag | /Integrais/Integral_MC.py | 995 | 3.796875 | 4 | #integral por monte carlo
#\int_{a}^{b}=(valor_médio)*(b-a)
import random
import scipy.stats as stats
import numpy as np
def ts(alpha,gl):
'''Retorna o valor de t-student para tal alpha e tal gis graus de liberdade.'''
return stats.t.ppf(1-(alpha/2), gl)
def siginificativos(n):
'''Retorna o... |
7242fb6a269570f2e6b55f4132eca4bcfd5001f3 | ikeshou/Kyoupuro_library_python | /src/mypkg/basic_data_structures/priority_queue.py | 2,686 | 4.25 | 4 | """
一番ベーシックな min priority queue, max priority queue の実装
- リスト上で min heap を構築するためのモジュール heapq は存在するが priority queue はサポートされていないので自前で用意する必要がある。
<メソッド早見表>
empty():
O(1)
PQueue が空か判定
add_task(task, priority):
O(lgn)
task を priority の優先度で PQueue に追加
pop_task():
O(lgn)
優先度が (最小: min-pqueue / 最大: m... |
d8dee13bb040d6dab1c1d2fa3a9a7c4197821634 | ivceh/Advent-of-Code-2019 | /Intcode_computer.py | 4,021 | 3.546875 | 4 | from collections import deque
def instruction_modes(instruction):
opcode = instruction % 100
instruction //= 100
mode1 = instruction % 10
instruction //= 10
return (opcode, mode1, instruction % 10, instruction // 10)
class program:
def __init__(self, A, in_func = None, out_func = None):
... |
662f493c535fb4797ef8a5a7782b0dce9960582a | Afrooz-mohamadipour/python-ex | /046.py | 181 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
num = 0
while num<5:
num = int(input("Please enter a number =>"))
print("The last number you enterd was ",num)
# In[ ]:
|
4ce9c91e5a4bec7a74a21727f5b9fe862570ac11 | catonis/Numerical-Methods | /sequences.py | 1,498 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 23 04:40:31 2019
@author: Chris Mitchell
"""
import requests
import re
def get_oeis_ref(sequence_ref):
"""This function accepts a sequence identification number as a string
for the OEIS and pulls the sequence, name, and comment from the
database in the... |
58a61eef7b111b286f767432dd5ef8efb33908a5 | pombredanne/n-tuple-plagiarism-detector | /ntuple.py | 6,193 | 4.34375 | 4 | import re
def read_string_to_word_list(line):
"""Takes in a string of text and returns a list of the words in the text."""
regex = r"[a-zA-Z]+"
words_in_text = []
# Finds all the words in the text
matches = re.findall(regex, line)
# Iterate through all the words in the line and add them to the ... |
687131e9e083cf4c2a6a9ce8fa60536539f2f3c2 | nkrishnappa/100DaysOfCode | /Python/Day-#24/1_types_of_paths.py | 492 | 3.890625 | 4 | """
1. Absolute File path - /root/filename.extension
2. Relative File path - filename.extension or ./filename.extension
# How to goto the parent folder - ../
"""
# Using Absolute file path
with open(r"C:\Users\nkrishnappa\Desktop\100DaysOfCode\Python\Day-#24\FindMeDude\my_file.txt") as file:
print(file.read())
... |
f344c246dde041f0f7e94ae02eb03e2ea6fdefa6 | nischalshrestha/automatic_wat_discovery | /Notebooks/py/shanxingg/titanic-ml-from-disaster/titanic-ml-from-disaster.py | 2,833 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[265]:
# import packages
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn import tree
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
# In[266]:
# Import data
train = pd.read_csv("../input/train.csv", index_... |
ccfd4d30c34ac74cdc34a217a7faeaad9dc06994 | flafick/project | /Arkanoid.py | 7,611 | 3.546875 | 4 | import pygame
import random
class Ball(pygame.sprite.Sprite):
def __init__(self, paddle):
pygame.sprite.Sprite.__init__(self)
self.paddle = paddle
self.size = 17
self.end_game_flag = False
self.image = pygame.Surface((self.size, self.size))
pygame.draw.circle(self.im... |
a79cbf35bcccc5ad1c9e8be2c9c65918ee592039 | DeanHe/Practice | /LeetCodePython/MaximumNumberOfVisiblePoints.py | 2,843 | 3.875 | 4 | """
You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.
Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and ... |
f9b91d7ecd3c963d83a15d143c74de08aa6b5985 | malavikasekhar/Malavika | /arm.py | 139 | 3.8125 | 4 | y=int(input())
sum=0
temp=y
while temp>0:
digit=temp%10
sum += digit**3
temp//=10
if y==sum:
print("yes")
else:
print("no")
|
fd9f267999c35582f19e7f662e4ac74f6fc86446 | hearsid/hackerrank | /__python/py-basic-data-types/nested-list.py | 561 | 3.546875 | 4 | names = []
scores = []
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
names.append(name)
scores.append(score)
scores = list(scores)
originalScores = scores[:]
scores = set(scores)
scores = sorted(scores)
secondMinScore = scores[1]
inde... |
a0bb8e3054f7dfbfa4eaae8f6ef700e2d0110224 | mlbudda/Checkio | /elementary/max_digit.py | 288 | 3.96875 | 4 | # Max Digit
def max_digit(number):
""" Returns which digit in this number is the biggest """
return int(max(str(number)))
# Running some tests..
print(max_digit(0) == 0)
print(max_digit(52) == 5)
print(max_digit(634) == 6)
print(max_digit(1) == 1)
print(max_digit(10000) == 1) |
7e8c6d54ed6f6ecd0ed2a9f49af77a711039d15e | harismuzaffer/python_core | /magic_square.py | 1,702 | 3.828125 | 4 | from numpy import *
n= int (input("Enter a positive odd integer"))
while n%2==0 or n < 1:
n = int (input("Enter a positive odd integer"))
a= zeros((n, n), dtype= int)
# print(a)
m= int (n/2)
row= 0
col= m
a[row, col]= 1
count= 2
while count<= n*n:
if (row-1 >= 0) and (col+1<= n-1) and (a[row-1, ... |
b5b68903dbe45ce962930adea6d4ae47522d7348 | Raihan-Sharif/CorePythonPractice | /listMethod.py | 1,210 | 4.125 | 4 | list1 = [1,2,3]
list2 = ['One','Two']
print('list1:',list1)
print('list2: ',list2)
print('\n')
list12 = list1 + list2
print('list1 + list2 :',list12)
list2x3 = list2 * 3
print('list2 * 3 ; ',list2x3)
hasThree = 'Three' in list2
print('"Three" in list2? : ',hasThree)
years = [1990,1991,1992,1993,1993,1993,1994]
pri... |
8db8a0435adaaa04915add6e8171919cab1eb048 | rpparada/udemy_complete-python-bootcamp | /Ejercicios Antiguos/Jugador.py | 2,505 | 3.5625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 17 22:53:03 2017
@author: Rodrigo Parada
"""
from Persona import Persona
class Jugador(Persona):
def __init__(self, nombre, monto_inicial):
Persona.__init__(self, nombre)
self.monto_inicial = monto_inicial
self.mon... |
03e4efc02def809edd9cfcaf2d41740f130f7b9b | MHibbard77/lab6 | /delete_account.py | 1,813 | 3.578125 | 4 |
import unittest
class deleteTests(unittest.TestCase):
def setup(self):
self.ui.command("create_user Admin AdminPassword")
self.ui.command("create_user Supervisor SupervisorPassword")
self.ui.commant("create_user TA TAPassword")
self.ui.command("create_user Instructor InstructorPass... |
e0b911c04c186edd4085ab1cad69b23749bd839b | zhaoyb950810/python_learn_private | /day02/varDesc.py | 1,214 | 4.03125 | 4 | """
使用变量保存数据病进行算术运算
a = 321
b = 123
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
"""
"""
使用input()函数获取键盘输入
使用int()进行类型转换
用占位符格式化输出的字符串
a = int(input('a = '))
b = int(input('b = '))
print('%d + %d = %d' % (a, b, a + b))
print('%d - %d = %d' % (a, b, ... |
90f20012d0d4e0ba295bb8c0b160d6e87ad0c838 | wiichog/Simulation | /Homework/MiniProyecto1/Shierpinski.py | 1,516 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Editor de Spyder
Este es un archivo temporal
"""
import matplotlib.pyplot as plt
import random
class Point:#Creamos una clase que maneje el punto
def __init__(self,x,y):#le mandamos los parametros x y y
self.x = x#damos valor al parametro
self.y = y#damos valor al parame... |
8fc7deeeb5aadc33f39e4077e51fb230f129e467 | XeroHero/Python | /src/program3.py | 103 | 3.765625 | 4 | def adder(x, y):
print (x + y)
x = input("enter a number")
y=input("Enter a number.")
adder(x, y) |
35d4569c10fe3a1f996068e7ebbc40008cd7b3b6 | shanirajkali/coding | /list/arry/matrix.py | 944 | 4.28125 | 4 | num = input("Enter the size of matrix : ")
mat=[]
mat1=[]
mul=[]
i=0
j=0
k=0
add=0
while(add<num):
mat.append([])
mat1.append([])
mul.append([])
add+=1
for i in range(0,num,1):
print "Enter elements Matrix:1 Row : "+`i+1`
for j in range(0,num,1):
mat[i].append(input("enter th elem... |
3b08171268dc4e81317f9d8ad7c4961fe9070f82 | kamojiro/Project-Euler | /027.py | 734 | 3.765625 | 4 | #import sys
#input = sys.stdin.readline
def is_prime(x):
x = abs(x)
y = x
if x == 0 or x == 1:
return False
for i in range(2, int(x**(1/2))+1):
while x%i == 0:
x //= i
if y > x:
return False
else:
return True
def consective_primes(a,b):
for i in ... |
b5a644355f16947758e6ff43dae0951e0cd3b9c2 | RZachLamberty/google_code_jam | /2020/r1b/prob2.py | 3,967 | 3.5625 | 4 | # run with interactive runner and testing tool via
# > python interactive_runner.py python testing_tool.py 0 -- python prob2.py
import math
import sys
CENTER = 'CENTER'
HIT = 'HIT'
MISS = 'MISS'
WRONG = 'WRONG'
def throw_dart(i, j):
print('{} {}'.format(i, j))
sys.stdout.flush()
return input()
def main(... |
50956f529320e551f07a71600677d930f51f66ab | rickyjreyes/Python_Tutorial | /1HelloWorld.py | 575 | 4.03125 | 4 | # HelloWorld.py
#
# First Program!
# This prints hello world
print("Hello World!")
# More Practice: Make 5 of your own prints
print("My name is Ricky!!!!")
print("My favorite color is blue!!!!")
print("Video games are cool!!!!")
print("I love to code!!!!")
print("This is Python :)")
# This is a... |
ef747ada6e37e32f8f40add6a7af83982b0754e5 | Leotiv-Vibs/GeekBrains | /lesson_7/task_2.py | 1,023 | 4.09375 | 4 | # Отсортируйте по возрастанию методом
# слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50).
# Выведите на экран исходный и отсортированный массивы.
import random
array = [random.randint(-100, 100) for i in range(200)]
print('Изначальный массив: ', array)
def merge(left, right... |
e38084a2d730cc69d69858f6044d8f5a65625c51 | prubach/Python_Winter_2020_2 | /bank.py | 3,308 | 4.09375 | 4 | class Customer:
last_id = 0
def __init__(self, first_name, last_name, email):
self.first_name = first_name
self.last_name = last_name
self.email = email
Customer.last_id += 1
self.customer_id = Customer.last_id
def __repr__(self):
return self.__class__.__name... |
c0ce1f60be2d343535802f8243709471287cbaf9 | fsym-fs/Python_AID | /month01/day13_oop/test/test01_extend.py | 2,564 | 4.0625 | 4 | """
一家公司有如下几种岗位:
程序员:底薪+项目分红
测试员:底薪+bug*5
.....
创建员工管理器
记录所有员工
提供计算总工资的功能
叙述:
三大特征:
封装:根据需求划分为员工管理器,程序员测试类
继承:创建员工类,隔离员工管理器和具体员工的变化
多态:员工管理器调用父类(员工)--->具体员工重写员工类的计算薪资方法--->添加具体员工对象方法
调父 重写 创建子对象
... |
2b2f27da7b2b65967765bdc9e071c968da0ec1ca | ParijatDhar97/Data-Structures-Python | /Doubly Linked Lists/InsertionFront.py | 1,974 | 4.6875 | 5 | #Insert a node at the front of the List
#Class for making nodes
class Node:
def __init__(self, data= None, next= None, prev= None):
self.next= next
self.prev= prev
self.data= data
#Class for making a Doubly Linked List
class DoublyLinkedList:
def __init__(self, head= None):
self.head= head
#Function to... |
0b649fc363adb0d813aa1745e69e7f09cf389437 | JulyKikuAkita/PythonPrac | /cs15211/PathSumII.py | 5,669 | 4.09375 | 4 | __source__ = 'https://leetcode.com/problems/path-sum-ii/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/path-sum-ii.py
# Time: O(n)
# Space: O(h), h is height of binary tree
# DFS
#
# Description: Leetcode # 113. Path Sum II
#
# Given a binary tree and a sum, find all root-to-leaf paths where each path's s... |
78e92173a248f88ca7faef1135c8722f86247ba0 | matttilton/coursework | /AdvDataStructures/intlistdelete.py | 231 | 3.578125 | 4 | # matthew tilton
# not sure how to do this recursively this is as good as i can get in the 3 minutes that i had
import intlist
def delete(x, y):
if x.first() == y:
return x.rest()
else:
return delete(x.rest(), y) |
30c615afe0c298ff40c453a3cea37d4c69f15c71 | subha996/Wine-Quality-is-BAD | /src/get_data.py | 1,017 | 3.890625 | 4 | # read the parameter
# process it
# reyturn the dataframe.
import os
import yaml
import pandas as pd
import argparse
# creating read param.yaml file
def read_params(config_path):
"""This functon will read the yaml file and
will return a dictionary."""
with open(config_path, 'r') as ymlfile:
... |
edc2e940fde5a5363b1085c21669b4426eeb202c | smiley16479/AI_bootcamp | /week_0/Day02/ex03/csvreader.py | 2,368 | 3.53125 | 4 | import csv
#Pas fini les check et les exceptions sont incompletes
class CsvReader(object):
def __init__(self, filename=None, sep=',', header=False, skip_top=0, skip_bottom=0):
if filename == None:
raise ValueError('filename not provided')
return None
self.filename = filename
self.sep = sep
self.header =... |
ae1bb5f589622d728c4704420825085bbdc25870 | vanya2143/ITEA-tasks | /hw-4/task_1.py | 3,155 | 4.09375 | 4 | """
К реализованному классу Matrix в Домашнем задании 3 добавить следующее:
1. __add__ принимающий второй экземпляр класса Matrix и возвращающий сумму матриц,
если передалась на вход матрица другого размера - поднимать исключение MatrixSizeError
(по желанию реализовать так, чтобы текст ошибки содержал размерность 1 и 2... |
736b7fe16db2111f8bf80a450972f04417292c78 | misan128/machine_learning | /100pagesbook/test_scikit.py | 463 | 3.765625 | 4 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from import_file import *
def train(x, y):
from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(x,y)
return model
X, Y = getdata_x_y("Advertising.csv")
print np.reshape(X, (-1, 1))
print np.reshape(Y, (-1, 1))... |
c3f9cbd07cf815ef9ddf431895461f5211bf18ee | depsir/university | /softcomputing/main.py | 1,282 | 3.609375 | 4 | #!/usr/bin/python
import csv
import geometric_transformation
START_POSITION_FILE = "data/start_position"
CAMERAS_DATA_FILE = "data/camera_rotations"
def main():
point = geometric_transformation.geometric_transformation(3,5,7)
with open(CAMERAS_DATA_FILE, 'rb') as csvfile:
data = csv.reader(csvfi... |
0f199da2d995d37b6ae6a499d4ffcb61a99712af | amourbrus/spiders_crawder | /concurrent/A_thread_share_source.py | 1,170 | 3.84375 | 4 | # 问题导入:共享资源导致资源竞争问题
import threading
import time
g_num = 0
def foo1(n, mutex):
# mutex.acquire()
global g_num
for i in range(n):
# time.sleep(0.001)
g_num += 1
# mutex.release()
print('foo1 ----->',g_num)
def foo2(n, mutex):
global g_num
# mutex.acqu... |
54adbc9f3e16d44527b459656d29718ceec5769f | mcatcruz/school_schedule | /school_schedule/student.py | 406 | 3.578125 | 4 | class Student():
def __init__(self, name, grade, classes):
self.name = name
self.grade = grade
self.classes = classes
def add_class(self, class_name):
self.classes.append(class_name)
def get_num_classes(self):
return len(self.classes)
def summary(self):
... |
df92c863b89e5790fac23983924c0fe23a2760de | GabrielSant0204/Python | /IMC.py | 820 | 3.9375 | 4 | print('================================')
print(' CALCULE SEU IMC ')
print('================================')
nome = input('Qual é seu nome?').capitalize()
altura = float(input('qual é sua altura?'))
peso = int(input('qual é seu peso?'))
imc = peso / (altura * altura)
print('o IMC de {} é {}'.fo... |
300fd0954738d2e3019772afed0cefc0774dfced | amit-mittal/Programming-Questions-Practice | /py/euler7.py | 240 | 3.84375 | 4 | import array
import math
n=3
counter=1
def isprime(n):
f=0
for i in range(int(math.sqrt(n)),2,-1):
if n%i==0:
f=1
return 0
if f==0:
#print n
return 1
while counter<10001:
if (isprime(n)):
counter+=1
print n
n+=2
|
a5d22871d82c3e3ce63db7e2e1fe52ebb1a84945 | BanarasiVaibhav/LearningPython | /RE.py | 479 | 3.796875 | 4 | import re #import regular expression module https://docs.python.org/3/library/re.html
message='''Hello my name is vaibhav i am vaibhav my real name is also vaibhav my friende call me vaibhav'''
print(re.finditer(r'vaibhav',message)) # finditer
print(re.search(r'vaibhav',message)) #searches all over ... |
21a882cd0b64abaa0f017620fea827a958e65b2e | mgh3326/programmers_algorithm | /KAKAO BLIND RECRUITMENT/2017/1차/셔틀버스/다시풀기.py | 1,362 | 3.546875 | 4 | import heapq
def solution(n, t, m, timetable):
answer = ''
time_list = []
for timetable_value in timetable:
hour, minute = map(int, timetable_value.split(":"))
minute += hour * 60
heapq.heappush(time_list, minute)
start_minute = 9 * 60
for bus_start_time_index in range(n):
... |
5a7811108cbf4d942390c2fff5101fa4f62d075c | Cammr94/Spring2019_Python1_Data119 | /Week4/reading_in_class_assignment_1a.py | 879 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Cameron Reading
Data 119
2/27/2019
In-Class Assignment
We are figuring out if a year is a leap year or not
and output how many days are in February
"""
#Asking User for a year, and assigning it to a variable
entered_year = int(input("Please enter a year to find out how many days February ha... |
58c1d9670f410755863f9df44ed441767d493d97 | PVyukov/python_lessons | /Lesson1/dz1_4.py | 261 | 3.78125 | 4 | #!/usr/bin/python3
var_number = int(input('Введите целое положительное число: '))
var_max = 0
while var_number>1:
var_let=var_number %10
var_number //= 10
if var_let > var_max:
var_max = var_let
print(var_max) |
7c493dab63c5dd0817c03dc2876534ebdaf47cb7 | milanshah/Python_assignements | /python_hw/ex3-1.py | 178 | 3.75 | 4 | def donuts(count):
if count < 10:
return count
else:
return 'manay'
print(donuts(5))
print(donuts(23))
"""
return 'no of donuts ' + str(count)
"""
|
8beb4ed0f4ca5d113ff6f165fc642464a1aa6f40 | defgsus/cthulhu2d | /src/util/timer.py | 1,048 | 3.734375 | 4 | import time
class Timer:
def __init__(self, count=None):
self.count = count
self.start_time = None
self.end_time = None
self.length = None
@property
def rate(self):
if not self.count or self.length is None:
return None
return self.count / self.l... |
90091e7c97234061dd319e92fd7f5d7544d7fa18 | iffy/eliot | /eliot/_py3json.py | 746 | 3.96875 | 4 | """
Python 3 JSON encoding/decoding, emulating Python 2's json module.
Python 3 json module doesn't support decoding bytes or encoding. Rather than
adding isinstance checks in main code path which would slow down Python 2,
instead we write our encoder that can support those.
"""
import json as pyjson
class JSONEnco... |
9555951dbcbfc8520338292bd29a188953e8326a | nicolageorge/play | /expanded_form.py | 354 | 3.671875 | 4 | def expanded_form(num):
# num = float(num)
str = "{}".format(num % 10)
num = num / 10
cnt = 10
while num / 10 > 0:
str = "{} + {}".format(num % 10 * cnt, str)
num = num / 10
cnt = cnt * 10
str = "{} + {}".format(num % 10 * cnt, str)
return str
print expanded_form(568... |
29d018d1e0686735d33c696903798cb4eb5d99fb | PMiskew/Year9Design_MISP | /Hello.py | 411 | 4.15625 | 4 | import math
#Information about program
print("This program calculates the volume of")
print("a cylinder given radius and height")
#Input
r = int(input("What is the radius: "))
h = int(input("What is the height: "))
#Process
v = math.pi*r*r*h
v = round(v,3)
#Output
print("The volume of a cylinder with")
print("r = ... |
c5dc77d32af67bd6d9ab32a6dd413dfd03e463fb | EricLiu750501/stanCode-projects | /stanCode projects/boggle/anagram.py | 3,573 | 4.09375 | 4 | """
File: anagram.py
Name: Eric Liu
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each w... |
4976bc621fb5644c098540dceef938726c6750cb | JamesGilsenan/Python-3 | /Linked Lists/Singly_Linked_List.py | 3,488 | 3.953125 | 4 | class Node:
def __init__(self, data, position=0):
self.data = data
self.next = None
self.position = position
def __repr__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
current_node = self.h... |
c09a861b648713f8339942dab836d7f005b47304 | VPanjeta/Wikipedia-Game | /src/get_links.py | 501 | 3.640625 | 4 | import urllib.request
main = 'http://en.wikipedia.org/wiki/Main_Page' #Main page url
def get_links(source_url, regex):
page = urllib.request.urlopen(source_url)
page_html = str(page.read())
links = set()
for link in regex.findall(page_html):
links.add("http://en.wikipedia.org" + link.split("... |
c3cae8dc33c6b0e13dbf2f51f524c9e38991493c | dennisasilva/PythonCourse | /Exercicios/11-20/ex011.py | 495 | 4 | 4 | # Desafio 11
# Faça um programa que leia a largura e altura de uma parede em metros, calcule a sua area e a quantidade de tinta
# necessária para pintá-la, sabendo que cada litro de tinta pinta uma area de 2m.
alt = int(input('Digite a altura da parede em metros: '))
larg = int(input('Digite a largura da parede em met... |
98975cd3e6bbe9433dd4b5ea838c2974f48e6706 | RobertHan96/English_Coding_Test | /HackerRank_staircase.py | 328 | 3.875 | 4 | sharp = 1
def staircase(n):
global sharp
for i in range(n):
for j in range(n+1):
if j == n:
print(end='\n')
sharp += 1
elif j < n and j + sharp < n:
print(' ', end='')
else:
print('#', end='')
stairca... |
ca39f812bd8271617cbd4ca3629ada41d2569c3d | blueclowd/leetCode | /python/0187-Repeated_dna_sequences.py | 623 | 3.640625 | 4 | '''
Description:
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA mo... |
84b090f3def06b79df70873c40e9fb0d44f59a6a | jhoancardona07/code_challenges | /validateBalancedParenthesis/JLH.py | 752 | 3.96875 | 4 | class Solution:
def isValid(self, string):
stack=[]
for character in string:
if(character == "(" or character=="[" or character=="{"):
stack.append(character)
if(character == ")"):
if(not(stack.pop()=="(")):
stack.append("(")
if(character == "]")... |
f19e08ccb6ba18c76d2409be174217cbcc2575be | jancyrusm/programming-logic-and-design | /L/10.py | 999 | 4.3125 | 4 | # Jan Cyrus M. Villar
# BS CoE 1-6
'''
Write a program that accepts three numbers and prints "All numbers are equal" if all three numbers are equal, "All numbers are different" if all three numbers are different. If only one is different, print that number.
Input first number: 256
Input second num... |
e31d97afebcc6af002d4f40cf6b2d51dcb22fb9d | nabilnabs1080/FIJ_Robotique | /00_algorithmique/01_python/Conditions.py | 289 | 3.8125 | 4 | # if > si
# elif > sinon si
# else > sinon
age = 15
if age < 10 :
print("trop jeune")
elif age < 20:
print("ok")
elif age >= 20:
print("trop vieux")
else:
print("egale a 20")
mots= "bonjour"
if "o" in mots:
print("in est dedans")
else :
print("pas dedans")
|
19c5316488b97967c3d1eed77654ecd33522cd7a | Brenda-M/Password-Locker | /main.py | 5,997 | 4.21875 | 4 | #!/usr/bin/env python
from user_credentials import User, Credentials
import pyperclip
import string
import random
def create_user(username, password):
'''
Creates a new user account
'''
new_user = User(username, password)
return new_user
def save_user(user):
'''
Saves a user account
'''
user.save_... |
7a8d3a175c8a0681558a01198c23eeb5c5d9cfdc | sng0616/practice | /digressions/book_search/ISBN_search.py | 1,328 | 3.609375 | 4 | import requests
from keys import google as GBooks_Key
pros_ISBN = raw_input("Please enter an ISBN. ")
# A function that takes an ISBN and finds the corresponding book if the ISBN is in use
def find_book_isbn(pros_ISBN):
GBooks_API = "https://www.googleapis.com/books/v1/volumes?q=isbn:"
fields = "items/volumeInfo(ti... |
215d981de996d7a3221de0d765dd4581a8bb4bba | balajisuresh1359/Sorting-Algorithm | /mergeSort.py | 585 | 3.96875 | 4 | def merge(arr,leftArray,rightArray):
i=j=k=0
while i < len(leftArray) and j < len(rightArray):
if leftArray[i] < rightArray[j]:
arr[k]=leftArray[i]
i+=1
else:
arr[k]=rightArray[j]
j+=1
k+=1
while i<len(leftArray):
arr[k]=leftArray[i]
i+=1
k+=1
while j<len(rightArray):
arr[k]=rightArray[j]
... |
24edb9f9fc4bb5846bd04c6f995b8cdd750faed0 | mychristopher/test | /Selenium练习/webdriver_api/2_browser_back.py | 583 | 3.75 | 4 | """
* back() 后退
* forward() 前进
* refresh() 刷新
"""
from selenium import webdriver
driver = webdriver.Chrome()
# 访问百度首页
first_url = 'http://www.baidu.com'
print("now access %s" %(first_url))
driver.get(first_url)
# 访问新闻页面
second_url = 'http://news.baidu.com'
print("now access %s" %(second_url))
driver.get(sec... |
ea11639f8bc09d8bfee35cc526987780bc20422d | Svensson17/python-project-lvl1 | /brain_games/games/brain_progression.py | 513 | 3.578125 | 4 | import random
RULE = "What number is missing in the progression?"
def get_question_and_answer():
result = []
score = random.randint(1, 15)
score2 = random.randint(1, 5)
score1 = score + (score2 * 9)
for num in range(score, score1, score2):
result.append(str(num))
right_answer = rando... |
a7ea3f851eb47b27aa2bb53268596fbad6a0e1d4 | AJPassDe/pandas | /05-data-types-and-missing-values.py | 2,665 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 11:37:09 2020
Info from:
https://www.kaggle.com/residentmario/data-types-and-missing-values
@author: AJ
"""
import pandas as pd
reviews = pd.read_csv("input/wine-reviews/winemag-data-130k-v2.csv", index_col=0)
# =====================================================... |
8bd1d69756c4352f9e2be105c5bbd4c9c9922b9e | Roberto09/Tutorials-Python | /Proyectos Personales/Numeros Primos/1o.py | 358 | 3.890625 | 4 | """numeros primos"""
print ("Elige el entre que numeros quieres encontrar los numeros primos")
ninicial= input("Numero inicial: ")
nfinal= input("Numero final: ")
def alg(p):
z=True
for n in range(2,(p/2)+1):
y=float(p)%float(n)
if y != 0:
continue
else:
z=False
break
return z
for x in range(ninicia... |
936663177a9d736ed36f4ee59ba0e1e6395039c8 | SurajB/Practice | /area.py | 1,064 | 4.3125 | 4 | #This program calculates the area of a circle or a triangle
from math import *
import time
from datetime import datetime
now=datetime.now()
print "The calculator is starting up"
print "%s-%s-%s %02d:%02d:%02d" % (now.year, now.month, now.day, now.hour, now.minute, now.second)
time.sleep(2)
option=raw_input("Wha... |
4809c12f23d4b01436c829eff24ead928e6d89fa | MaoningGuan/Python-100-Days | /Day01-15/06_exercise_2.py | 1,813 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
1、求最大公约数
2、求最小公倍数的函数
3、判断一个数是不是回文数的函数。
4、判断一个数是不是素数
5、求一个数的反向排列:1234 ——> 4321
"""
def gcd(x, y):
"""
求x和y的最大公约数
:param x:
:param y:
:return: x和y的最大公约数
"""
(x, y) = (y, x) if x > y else (x, y)
for factor in range(x, 0, -1):
if x ... |
9024fbdfb1e7e7ce19b619bd24f50155148ec57c | Rpratik13/Algorithm_Implementations | /probing.py | 427 | 3.609375 | 4 | c1 = 0
c2 = 1
m = 7
def hashing(key):
return key % m
def probing(array: list) -> list:
result = [None] * m
for elem in array:
hsh = hashing(elem)
i = 1
while result[hsh] != None:
hsh = (hashing(elem) + c1 * i + c2 * (i ** 2)) % m
i += 1
result[hsh] = elem
return result
if __name__ == '__main__':
... |
e56e018b5847dddd79506fe30ea4b530d06b0ee7 | novmar/python_learn | /pets_learn/1..7-animals.py | 2,549 | 4.09375 | 4 | ### 1. Make a list of pets. You will need it in later exercises. Known pets are: 'dog', 'cat', 'rabbit', 'snake'
pets = [ 'dog', 'cat', 'rabbit', 'snake',]
### 2. Write a functon that returns the name of pets (list given as the argument) that are shorter than 5 leters.
def fiveless (mypets):
pets5 = []
for ... |
7e195192c2a79a3d6200806acf69ee534ab7faae | JoeKabongo/Sorting-Project | /Python/insertion.py | 467 | 4.1875 | 4 | def insertion(array):
# Move elements of arr[0..i-1], that are
# greater than element, to one position ahead
# of their current position
length = len(array)
for i in range(1, length):
element = array[i]
sorted = i-1
while sorted >= 0 and array[sorted] > element:
a... |
09ea228d95f9d692d659dac1c9a2b797bcfbd480 | Jeanzw/LeetCode_Practice | /Python/Easy/575 Distribute Candies(set+数学思维).py | 1,439 | 3.75 | 4 | # 这一道题目的思路其实很简单:
# 题目的意思其实就是,糖果分一半,那么妹妹最多可以得到多少种类的糖果呢?
# 由于哥哥和妹妹是一人一半,所以妹妹最多也就分到一半的糖果,就算这些糖果都不是一个种类的,也就只能分到一半数量糖果种类的糖果
# 所以这就说明,总数/2 这是一个分界点,也是我们讨论的依据
class Solution:
def distributeCandies(self, candies: List[int]) -> int:
kind = set(candies)
print(kind)
if len(kind) >= len(candies)/2: #如... |
64ab864cd0b4ed96e0a0e1d8d5953d638765e028 | Youlow/py101 | /ex1/models.py | 941 | 3.609375 | 4 | # -*- coding: utf-8 -*-
class Field(object):
def __init__(self, rank=3):
self.empty = " "
self.rank = rank
self.field = [[self.empty, ] * rank for i in range(rank)]
def set_value(self, x, y, sign):
self.field[x][y] = sign.sym
def get_rank(self):
return self.rank
... |
d3151a45eb5a025a9970afd1aad30208b8a5c316 | KaylaBaum/astr-119-hw-1 | /python_arrays.py | 498 | 4.15625 | 4 | x = [0.0, 3.0, 5.0, 2.5, 3.7] #define an array
print(type(x))
#remove the third element
x.pop(2)
print(x)
#remove the element equal to 2.5
x.remove(2.5)
print(x)
#add an element at the end
x.append(1.2)
print(x)
#get a copy
y = x.copy()
print(y)
#how many elements are 0.0
print(y.count(0.0))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.