blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a9da584e90dbf78b04b3e3ee762dcaca00a9ad08 | niki4/algorithms | /sort/merge_sort_top-down.py | 1,514 | 4.21875 | 4 | import random
from typing import List
class Solution:
"""
Merge Sort, Top-down approach:
1. In the first step, we divide the list into two sublists. (Divide)
2. Then in the next step, we recursively sort the sublists in the previous step. (Conquer)
3. Finally we merge the sorted sublists in the ... |
9aaddf425a33eca438c0b1de1f3ccc5a5df66653 | ytobi/daily_coding_problem | /2018-12/27/solver.py | 827 | 3.84375 | 4 | import argparse
def check_comand_line_args():
parser = argparse.ArgumentParser( description=
"Enter two to calculate their edit distance")
parser.add_argument("-s1", "--string1", dest="string1", required=True,
help="First string to compare" )
parser.add_argument("-s2", "--string2", dest="string2"... |
0e6de258ebe4851c70fd9a95ae48a6db2b13fdd8 | rwgk/rwgk_config | /bin/simplify_filenames.py | 879 | 3.5 | 4 | #! /usr/bin/env python3
"""Simplifies filenames to avoid special characters. Non-recursive."""
import os
import sys
def run(args):
"""."""
assert args, 'dirpaths...'
for dirpath in args:
assert os.path.isdir(dirpath), dirpath
num_renamed = 0
for dirpath in args:
for name in os.listdir(dirpath):
... |
f81067a903c407745de984331c22c532be75dde8 | taticorreia/backup_exercicios | /exerciciospython/novosalario.py | 280 | 3.546875 | 4 | fgts = float(input('Valor do fgts:'))
"""
Se o fgts for R$ 7000 o imposto sera de 10%
Se o fgts for R$ 15000 o imposto sera de 15%
"""
if fgts <= 7000:
print('Valor do fgts: {0}'.format(fgts - (fgts * 0.10)))
else:
print('Valor do fgts: {0}'.format(fgts - (fgts * 0.15)))
|
799d9444772eb8db0b35e8d69edbea27d1fe59ae | taticorreia/backup_exercicios | /exerciciospython/salario.py | 376 | 3.875 | 4 | salario = float(input('informe seu salario: '))
"""
Regras de negocio do programa:
1. Salario de ate 10 mil, o imposto calculado e 5%
2. Salario maior que 10 mil o imposto calclado e 10%
"""
if salario <= 10000:
print('Valor do salario: {0}'.format(salario - (salario * 0.05)))
else:
print('Valor do sa... |
edcd4d063c988cc675b5dc55569bbceb628248b6 | mrinalmanu/class_assignments | /Task_3.py | 1,307 | 3.703125 | 4 | import itertools
from functools import reduce
def squares(n):
for it in n:
yield int(it) ** 2
def repeatntimes(elems, n):
it = itertools.tee(elems, n)
for i in it:
yield from i
def evens(x):
if x % 2:
x += 1
while True:
yield x
x += 2
def digitsumdiv(n... |
eadd176daf8fe21a8e3c90112523c83b661bc6e5 | mrinalmanu/class_assignments | /Task_5.py | 2,019 | 3.765625 | 4 | def permutations(n, elements=[]):
def generate(n, elements=[]):
if len(elements) == n:
yield tuple(elements)
else:
s = set(elements)
for i in range(1, n + 1):
if i not in s:
yield from generate(n, elements + [i])
return list... |
5ad2c7a11948e79b31be6ecdfa526b6f84b6e20d | fedepacher/HackerRank | /30_days_of_code/day_20.py | 720 | 3.515625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def countSwaps(a):
firstElement = 0
lastElement = 0
numSwaps = 0
flag = True
for i in range(len(a)):
for j in range(len(a) - 1):
if a[j] > a[j+1]:
numSwaps += 1
lastElement =... |
53502703a405a25121913de35f7453a83fa232a1 | tganderson0/randomTools | /binaryToDecimal.py | 950 | 3.8125 | 4 | import sys
from math import pow
sum = 0
currPow = 0
debugMode = False
if (len(sys.argv) == 1):
print("Requires a binary number to convert: \n$python3 binaryToDecimal.py [binaryNumber]")
exit()
if (len(sys.argv) > 2):
if (sys.argv[2] == "-d"):
debugMode = True
if (sys.argv[1] == "-help"):
print... |
6e9575af099a39818fb5483a29fa612aa1041d61 | ankitfirebolt/leetcode | /876-middle-of-the-linked-list/876-middle-of-the-linked-list.py | 624 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head.next:
return head
elif not hea... |
2d6999ba96dac62f6730be48d8e2d74050f0309c | ankitfirebolt/leetcode | /200-number-of-islands/200-number-of-islands.py | 2,101 | 3.59375 | 4 | class Solution(object):
def numIslands(self, grid):
#boder conditions
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
count = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == ... |
f81324f90ea172de7b7c71a09ebe0da5aeffbbbc | ankitfirebolt/leetcode | /101-symmetric-tree/101-symmetric-tree.py | 737 | 3.96875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return Tr... |
5c59a3af80ba1f1ce57a207b0b4d77835bfb10a6 | njdevengine/python-the-hardway | /guesser.py | 710 | 4.0625 | 4 | import random
print('Hello... What is your name?')
name=input()
print('Good to meet you, '+name+'. I am thinking of a number between 1 and 20. Take a guess.')
secretnumber=random.randint(1,20)
for guessestaken in range(1,7):
print('Take a guess.')
guess=int(input())
if guess< secretnumber:
print... |
82540836f50d2836b08e2a048465f0009194e13e | cs25-bw1-team07/backend | /util/max_max_generator.py | 5,751 | 3.515625 | 4 | class World:
def __init__(self):
self.grid = None
self.width = 0
self.height = 0
def generate_rooms(self, size_x, size_y, num_rooms):
# random.seed('9Lambda1Thunder1D0me9!')
'''
Fill up the grid, bottom to top, in a zig-zag pattern
'''
# Initialize... |
2de5f3fa1597f8bcdbde139c1bd15113606fa7d5 | wenli135/Binance-volatility-trading-bot | /hb_quant/huobi/model/market/depth_entry.py | 667 | 3.515625 | 4 |
class DepthEntry:
"""
An depth entry consisting of price and amount.
:member
price: The price of the depth.
amount: The amount of the depth.
"""
def __init__(self):
self.price = 0.0
self.amount = 0.0
@staticmethod
def json_parse(data_array):
entry ... |
3c6ef556d01132daa90f8c6f14de39cdcaec8637 | ravishankarramakrishnan/JobBoard | /db/repository/users.py | 665 | 3.578125 | 4 | from sqlalchemy.orm import Session
# Session is used as Datatype Validator
from schemas.users import UserCreate
from db.models.users import User
from core.hashing import Hasher
# Define a function to Create new User
# user has datatype of UserCreate class and db has datatype of Session
def create_new_user(user: User... |
a48d822cc753304af1b8187605e9e6ad22519242 | zhilton076/Enumeration-Tool | /EnumerationTool/Scripts/serviceFinder.py | 775 | 4.09375 | 4 | #!/usr/bin/python3
"""
Author: Zack Hilton
Date: 5/30/19
The purpose of this program is to search through the
enumartion script's output for hosts running unauthorized services
pose of this program is to search through the\nenumartion script's output for hosts running unauthorized services"
"""
import re
# ... |
5c1e7fc5728b71f5ce5f1b19569685f6a4930382 | zdimon/python-course-4 | /doc/5-functions-webpy/code/rec-coctail/coc.py | 323 | 3.5625 | 4 | print("Making recousion coctail!!!")
def make(water,alcohol,cnt):
cnt = cnt + 1
mix = 0
mix = mix + (water*30)
mix = mix + (alcohol*20)
if cnt > 10:
return mix
mix = mix + (make(water,alcohol,cnt)*50)
print("process %s" % mix)
return mix
cnt = 0
print(make(3,4,cnt... |
82020622d0b652411862a024157e5b2c61bc54aa | zdimon/python-course-4 | /doc/1-console/code/home/q | 1,052 | 3.703125 | 4 | #!/usr/bin/env python
#coding: utf-8
questions = [
{
"question": "Оператор вывода на экран?",
"answers": [
{"text": "1 echo", "is_true": False},
{"text": "2 print", "is_true": True},
{"text": "3 output", "is_true": False}
]
... |
dfa7f53a5740ef962e6b97d252b7c990e46e1c17 | JLuebben/ComputingForumMieres | /Basics/07Serialization.py | 561 | 3.515625 | 4 | import pickle
class MyObject(object):
def __init__(self, value):
self.a = value
self.b = self.a ** 2
self.c = self.b ** 2
self.d = self.c ** 2
self.e = self.d ** 2
def __call__(self):
print(self.e)
def doSave():
myInstance = MyObject(2)
myInstance()
... |
e79b748dde3b15cfbed2f0285cc6ea7abb8ee76a | Making-with-Code/project_queue | /order.py | 684 | 3.5625 | 4 | # orders.py
# by Jacob Wolf
#
# Class implementation of the Order object, for use in the cs10 ADT challenge
class Order():
""" Object class representing an order to an online shopping platform.
Must be initialized with a unique order_id. Optional parameters for
buyer, shipping_address, and contents.
""... |
464eae02bde3ce742eed61caa0fab7a962eb278f | rjw57/bigjobbies | /bigjobbies/pin.py | 1,100 | 3.734375 | 4 | import hmac
import os
import re
def _generate_digit():
"""Return a string containing a single decimal digit chosen uniformly and at
random."""
# We use rejection sampling on the lower nibble of single byte values to
# ensure uniformity.
while True:
v = os.urandom(1)[0] & 0xF
if v < ... |
0a58dea256cedd3dfbcb72511ba738dc268bae6a | Furuka-Sep/PythonTraining | /day0202/stairs.py | 310 | 3.703125 | 4 | """
for i in range(1,10):
if i % 2==0:
continue
for j in range(1,10):
print(i*j,end=',')
if i*j >50:
break
print()
print()
"""
height=int(input('何段の階段を作る?>'))
for i in range(height):
for j in range(i+1):
print('*',end='')
print()
|
7a1813c32a42dbea4eaa0e344c36ba3cd1807e60 | Furuka-Sep/PythonTraining | /day0203/list1.py | 389 | 4.09375 | 4 | import pprint
#10個のインデックスを持つlistを10個格納したlistの生成
"""
data=list()
for i in range(10):
temp=list()
for j in range(10):
temp.append(0)
data.append(temp)
print(data)
"""
W=10
H=10
data=list()
for i in range(H):
temp=list()
for j in range(W):
temp.append(0)
data.append(temp)
pprint.ppr... |
9d0a96e73d99c7aad0e1b2d1efce636d393caa21 | Furuka-Sep/PythonTraining | /day0129/code1_20.py | 153 | 3.671875 | 4 | price=int(input('料金を入力:'))
number=int(input('人数を入力:'))
payment=int(price/number)
print('お支払いは{}円です'.format(payment))
|
31ecab4b512d2a971ab7a7aeaf22f9b791895801 | Furuka-Sep/PythonTraining | /day0210/sum.py | 296 | 3.75 | 4 | def sumdata(n):#手続型pg
s=[i+1 for i in range(n)]
return(sum(s))
def sumdata2(n): #最適解 関数型pg
return sum(range(1,n+1))
def sumdata3(n):#再起処理
if n=1:
return n
else:
return n+sumdata3(n-1)
n=int(input('正の整数>>'))
print(sumdata2(n))
|
4090f2fc0d5db8f13d591728aace75a684c47508 | Furuka-Sep/PythonTraining | /day0202/Fkame.py | 786 | 3.828125 | 4 | import turtle
import random
t1=turtle.Turtle()
t1.shape('turtle')
t1.color('blue')
t2=turtle.Turtle()
t2.shape('turtle')
t2.color('red')
t3=turtle.Turtle()
t3.shape('turtle')
t3.color('green')
def make_square(t1,t2,t3):
for i in range(4):
t1.forward(random.randint(20,70))
t1.right(random.randint(10,350))
t2.for... |
b5f8f10f37091a862d21893fbe1825244cfa32a5 | Furuka-Sep/PythonTraining | /day0202/code5_16_17.py | 675 | 3.828125 | 4 | #点数の入力
def input_scores(name):
print('{}さんの試験結果を入力してください'.format(name))
network=int(input('ネットワークの得点…'))
database=int(input('データベースの得点…'))
security=int(input('セキュリティの得点…'))
scores=[network,database,security]
return scores#戻り値
#平均点を計算
def calc_average(scores):
avg=sum(scores)/len(scores)
... |
645290c62209dca88e4389e88da0c69ca1a4e022 | Dosc2017/PythonExcercise | /FibTimeCompare .py | 615 | 3.9375 | 4 | import time
def fib1(n):
"""
fibonocci without dict
"""
if n == 0:
return 0
if n == 1:
return 1
else:
return fib1(n-1) + fib1(n-2)
known = {0: 0, 1: 1}
def fib2(n):
"""
fibonocci with dict
"""
if n in known:
return known[n]
res = fib2(n... |
980475943b5143a13235f33acc66d3b5d1861d03 | Dosc2017/PythonExcercise | /inheritanceAndattribute.py | 411 | 3.71875 | 4 | class A:
z = -1
def f(self, x):
return B(x - 1)
class B(A):
n = 4
def __init__(self, y):
print("EXE", y, self)
if y:
self.z = self.f(y)
else:
self.z = C(y + 1)
class C(B):
def f(self, x):
print("aaa")
return x
b = B(1)
p... |
b459cb5c1f3048382319b51755723d6fe9775206 | sophiesolomich/guessinggame | /test.py | 393 | 3.953125 | 4 | import random
randomNumber= random.randint(0,101)
correctGuess= False
while correctGuess==False:
str_guess= input("Guess a number 1-100: ")
guess=int(str_guess)
if guess==randomNumber:
correctGuess=True
print("Great guess! Correct guess")
elif guess>randomNumber:
print("Guess is ... |
c028be366a2026bfecfa3b66c95d602ca39f9fbd | NatashaKandakova/Structured-programming | /4.3(знак восклицания).py | 206 | 3.765625 | 4 | s=input('Введите строку с восклицательным знаком - ')
for i in range(len(s)):
if s[i]=='!':
s=s[0:i]+str(i)+s[i+1:]
print('Ваша строка ',s)
|
ec93203a17483388ada16b7f841937d6de7bbbb8 | NatashaKandakova/Structured-programming | /линбаз.py | 110 | 3.734375 | 4 | import math
a= float (input('a= '))
b= float (input('b= '))
H= float (input('H= '))
S=(1/2)*(a+b)*H
print(S)
|
13c3c6f1db2e30662ca0ae8dac0e5f3b88807db8 | Xyhlon/scrape | /dwnlderspecific.py | 358 | 3.765625 | 4 | # first it is necessary to import the downloader
# for that the urllib module is used
import urllib.request
# next a function is defined which downloads the givens URLs html page
# using the imported module
def download(url):
text = urllib.request.urlopen(url).read()
return text
# print(download('https://en.... |
20a3f5931fe768d45e373fb5ebdff19b1a383ee2 | aaronchu415/LeetCode | /completed/leetcode-NaryTreePostorderTraversal.py | 792 | 4 | 4 | # // _NAME: NarayTreePostOrderTraversal
# // _LINK: https://leetcode.com/problems/n-ary-tree-postorder-traversal/
# // _CATEGORY: Tree
# Given an n-ary tree, return the postorder traversal of its nodes' values.
# For example, given a 3-ary tree:
# Return its postorder traversal as: [5,6,3,2,4,1].
"""
# Definition f... |
50c3964b4e34a6c52effcd8d25dad0cd21f13696 | aaronchu415/LeetCode | /completed/leetcode-TwoCityScheduling.py | 1,110 | 3.71875 | 4 | # // _NAME: Two City Scheduling
# // _LINK: https://leetcode.com/problems/two-city-scheduling/
# // _CATEGORY: Array
# There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].
# Return the mini... |
604bdceb24c78db6cbbb028134efabff61892224 | aaronchu415/LeetCode | /completed/ctci-2:8.py | 979 | 3.609375 | 4 | # // _NAME: Loop Detection (2.8)
# // _LINK: http://www.crackingthecodinginterview.com/
# // _CATEGORY: CTCI
class Node:
def __init__(self, val):
self.val = val
self.next = None
def printLL(head):
curr = head
while curr:
print(curr.val)
curr = curr.next
def detectionL... |
f7dd347afec4cebd29082bdfe703a8005d63818d | xiyangxitian1/heima_learn | /leetcode/简单1/最后一个单词的长度.py | 339 | 3.5 | 4 | class Solution:
def lengthOfLastWord(self, s: str) -> int:
str1 = s.rstrip()
if not str1:
return 0
count = 0
for i in range(len(str1) - 1, 0, -1):
if str1[i] != ' ':
count += 1
else:
return count
else:
... |
dc6c0b938da1245a42db2fb5abd6c3609c760edc | xiyangxitian1/heima_learn | /leetcode/简单1/二进制求和.py | 1,392 | 3.5 | 4 | class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = ''
a = self.reversestr(a)
b = self.reversestr(b)
a_len = len(a)
b_len = len(b)
if b_len > a_len:
# 交换a与b
... |
9a32b8a7077341e179c995f4ba080c810eb01962 | xiyangxitian1/heima_learn | /web/day13最后的/01-property属性-01.py | 645 | 3.90625 | 4 | class Person(object):
def __init__(self):
self.__age = 0
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
self.__age = age
# class Person(object):
#
# def __init__(self):
# self.__age = 0
#
# def get_age(self):
# return se... |
e77fd2ecd574e2b677d088a5f825ba09a96fe8c0 | xiyangxitian1/heima_learn | /web/闭包和装饰器/带参数的类装饰器.py | 736 | 3.5625 | 4 | class logger(object):
# def __init__(self, level='INFO'):
# self.level = level
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, func):
def wrapper(*args, **kwargs):
# print("[{level}]: the function {func}() is running... |
95194bab4220ac94d183502cc08f6b0c61f8246e | xiyangxitian1/heima_learn | /leetcode/简单1/test1.py | 634 | 3.796875 | 4 | import keyword # 关键字
import dis # 程序执行
# print(keyword.kwlist)
#
# # 所以True为1 False为0
# a = True + True
# b = False + True
#
# # if 0: == if False:
# #
# print(int(True))
# print(int(False))
# 在python3以下的版本中 while True: 是要比while 1慢的 python3的时候True和False成了关键字,速度就一样了
# while a is True 没 没有 while a 快 while a 与 w... |
3f46d009e3d93f6143bc000483f4e9ca7c6d5fcd | xiyangxitian1/heima_learn | /leetcode/简单1/合并两个有序整数数组.py | 879 | 3.890625 | 4 | from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
nums11 = nums1
if not nums2:
return nums11[:m]
if not nums11:
... |
6e29c2cf4a259805ef3cfeaefc1322c0ac1bece2 | xiyangxitian1/heima_learn | /paixu/guibing.py | 1,116 | 3.921875 | 4 | from datetime import datetime
from random import randint
def mergingSort(arr):
"""归并排序"""
if arr == None or len(arr) < 2:
return arr
num = len(arr) >> 1
leftArr = arr[:num]
rightArr = arr[num:]
# print("split lef: " + str(leftArr) + " right: " + str(rightArr))
return mergingArr(mer... |
363d9f03aa954ff12e663fa0420f63c92c8e136f | xiyangxitian1/heima_learn | /leetcode/简单2/杨辉三角.py | 1,016 | 3.828125 | 4 | from typing import List
"""
杨辉三角
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
下面一行是由上面一行推导而来
每个数字是由上一行的两个数字。[row][col] = [row-1][col]+[row-1][col-1] 如果[row-1][col]没有就是0
"""
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0:
return None
if numRows == ... |
dfbf05a6af0037f3661bd0644088791b1ab48781 | xiyangxitian1/heima_learn | /leetcode/简单1/删除重复链表.py | 1,086 | 3.84375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
result = ''
result = str(self.val)
while True:
if not self.next:
break
result += result + str(self.next.va... |
2251187832e76c635be6a531f1f9c910f1602910 | suman-d/python_class_WPE | /Week0.1/Read_N_Lines.py | 446 | 3.84375 | 4 | import os
def read_n(filename, n):
''' The function takes filename
and no. of lines to read everytime is called.
It returns "n" of lines everytime it is called.'''
f = open(filename)
while True:
output = "".join((f.readline() for i in range(n)))
if not output:
break
... |
f24c86553e6c5b2dd7f9601f59aa1829f7b6f229 | Linnea-uden/Revers_word.py | /main.py | 166 | 3.9375 | 4 | n = 100
while n > 0:
n -= 1
user_word = input("Enter a word that you want to revers: ")
rev_word = ''.join(reversed(user_word))
print(rev_word)
|
29454ded3c2e1e0863d09edb07359683a2eccd5d | CamLab101/Flood-Warning-System | /Cam Files/floodsystem/flood.py | 998 | 3.9375 | 4 | #for Task 2B
#returns a list of tuples, where each tuple holds
#(1) a station at which the latest relative water level is over tol and
#(2) the relative water level at the station
def stations_level_over_threshold(stations, tol):
list_of_tuples=[]
for station in stations:
if station.relative_water_level()==None:... |
6b3140a8dff23769ea92c009891d4a1e19874082 | CamLab101/Flood-Warning-System | /Cam Files/floodsystem/plot.py | 1,536 | 3.53125 | 4 | 'This is a document for plotting level wrt time'
import matplotlib
import matplotlib.pyplot as plt
from floodsystem.analysis import polyfit
import matplotlib.dates
import datetime
import numpy as np
from floodsystem.stationdata import build_station_list
def plot_water_levels(station, dates, levels):
t = dates
level ... |
7359ba73569b23eecac981cc4fdf090757368914 | SilverBlaze109/VAMPY2017 | /projects/CanChickensFly2.py | 2,279 | 3.734375 | 4 | def tree(val):
return [None, val, None]
def data(node, val = None):
if node == None:
return None
elif val is None:
return node[1]
else:
return node[1]
def yes(node, child = None):
if node is None:
return None
elif child is None:
return node[0]
else:
node[0] = child
def no(node, child = None):
if ... |
824a694933d84945e849ac874f50b2b4c46a18b6 | SilverBlaze109/VAMPY2017 | /projects/Pictures.py | 2,002 | 3.890625 | 4 | grade = 8
last_name = "Smithfield"
if 0 <= grade and grade <= 2 and "A" <= last_name and last_name <= "F":
print("7:00 - 7:50 M")
if 0 <= grade and grade <= 2 and "G" <= last_name and last_name <= "M":
print("7:50 - 8:40 M")
if 0 <= grade and grade <= 2 and "N" <= last_name and last_name <= "Q":
print("8:40 - 9:... |
2725bcbb103dad1ec9bba4f0a67137d8fd2844d7 | Jviscenheski/fuzzy-and-neural-network- | /controle-KJunior-rede-neural/redeNeural.py | 692 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler
import pandas as pd
def redeNeural():
# Coleta os dados de um arquivo .csv
dados = pd.read_csv("dataset.csv")
# Separa em entrada e saída
entrada = dados[["s1", "s2", "s3", "s4",... |
11907c1f5c24d32aec7d37781a10710f50a4a1b0 | ParamDeshpande/oscar_buggy | /code/pilotdash/Polynomial.py | 3,382 | 4.125 | 4 | """
Author: Param Deshpande
Date created: Sun Jul 12 14:39:20 IST 2020
Description:
class polynomial for printing a spline from coeffs
copied from https://www.python-course.eu/polynomial_class_in_python.php
License :
------------------------------------------------------------
"THE BEERWARE LICENSE" (Revision... |
23037a7e4a6e00842a4124b0432541c724d8b7b4 | Eileencaraway/tools | /neighb_count_without_voro/statistics.py | 1,615 | 3.734375 | 4 | # this file is for doing statistic of any kind of data
# the output of this can be a deviation, mean, skew and kurtosis, etc
from scipy import *
from numpy import *
import scipy.stats
import sys
## read the file name and the col of the data(if > 2 column in the file)
if(len(sys.argv)<2):
sys.stderr.write('Usage : i... |
c88d33f1d46f1f55282e13126b874cbec70c3b15 | MCSDS-UIUC/MCSDS-CCA | /assignments/MP5/part_b_ml.py | 1,611 | 3.5 | 4 | from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.ml.clustering import KMeans
from pyspark.ml.linalg import Vectors
import pyspark.sql.functions as F
############################################
#### PLEASE USE THE GIVEN PARAMETERS ###
#### FOR TRAINING YOUR KMEANS CLUSTERING ###
###... |
beec8fcb70b214b0f5f811acb4f59c645c08d4bd | jonasrlg/Linear-Regression | /RandomLines.py | 663 | 3.640625 | 4 | from random import uniform
file_name = input("The name of the file is: ")
file = open(file_name+".txt","w")
n_lines = int(input("Type the number of lines: "))
file.write(str(n_lines) + "\n")
for i in range(n_lines):
n_points = int(input("How many random numbers do you want? "))
file.write(str(n_points) + "\n")
... |
f188034a3818b81d48c81e518ad3c192d7df510a | mosinal88/Zookeeper | /Problems/Half-life/main.py | 186 | 3.609375 | 4 | atom_one = int(input())
atom_two = int(input())
if atom_one >= 2 or atom_one <= 1000000:
i = 0
while atom_one >= atom_two:
atom_one /= 2
i += 1
print(i * 12)
|
ce37b4dab25d13522780ec337416b758872ed9fa | jaque456/IOT2 | /CalcAreaTrape.py | 336 | 3.78125 | 4 | #Calcular Area del Trapecio
import math
def CalculaTrape (altura,base1,base2):
print((altura * ((base1 + base2) / 2) ))
altura = int(input("Ingresa la altura del Trapecio: "))
base1 = int(input("Ingresa la base1 del Trapecio: "))
base2 = int(input("Ingresa la base2 del Trapecio: "))
CalculaTrape (altur... |
10a70f380f657d46a2c9e09aafe7f307bb84eca9 | BryanHoffmaster/learning-python | /Misc/System_Info_UI/chp19 - Adv Funcs.py | 801 | 3.84375 | 4 | # Recursive functions:
def mysum(mylist):
if not mylist:
return 0
else:
return mylist[0] + mysum(mylist[1:])
# recursive alternatives to previous function:
"""
def mysum(mylist):
return 0 if not mylist else mylist[0] + mysum(mylist[1:])
def mysum(mylist):
return mylist[0] if len(mylist) ==... |
1ad5a0e5bcbf710ff2806c2f8e9c246eddc111ab | vSharique/Python3 | /q7.py | 306 | 3.65625 | 4 | with open('/home/sharique/Python3/SampleTextFile.txt', 'r') as f:
s = f.read()
wc={}
for word in s.split():
if word not in wc:
wc[word]=1
else:
wc[word]+=1;
for key,value in wc.items():
print (key, value)
maximum = max(wc, key=wc.get)
print ("Highest Word count is",maximum, wc[maximum])
|
5b4feac01aa17001091ea353b67ea16232536606 | rabenkralle/Algorythms_and_data_sturctures | /lesson_1/les_1_task_8.py | 556 | 4.25 | 4 | # 8. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
print('Введите три числа')
a = int(input('\tВведите первое число: '))
b = int(input('\tВведите второе число: '))
c = int(input('\tВведите третье число: '))
if (b < a < c) or (c < a < b):
m = a
elif (a < b < c)... |
d604dc8ab694cd06fae0423138443a3f0b0428f1 | razyesh/razyesh.github.io | /iw/python-assignment-ques/q31.py | 330 | 4.5625 | 5 | """
31. Write a Python program to iterate over dictionaries using for loops.
"""
def iterate_dict(sample_dict):
"""function to iterate over dictionaries"""
for key, value in sample_dict.items():
print(key, value)
if __name__ == "__main__":
sample_dict = {1: 20, 2: 30, 4: 50}
iterate_dict(sam... |
2919ff3fa0dbe45880d4513177c0deda6fc14f41 | razyesh/razyesh.github.io | /iw/python-assignment-ques/q42.py | 305 | 4.40625 | 4 | """
42. Write a Python program to convert a list to a tuple.
"""
def convert_tuple(sample_list):
"""function to convert list to a tuple"""
return tuple(sample_list)
if __name__ == "__main__":
sample_list = [1, 2, 3, 4, 5, 6, 7, 8]
result = convert_tuple(sample_list)
print(result)
|
7d2fc0ecce5730fd7b286bac65895b3c23116fb4 | razyesh/razyesh.github.io | /iw/python-assignment-ques/q37.py | 541 | 4.53125 | 5 | """
37. Write a Python program to multiply all the items in a dictionary.
"""
from q33 import generate_dict
def multiply_dic_item(dic1):
"""function to multiply all the items in a dictionary"""
key_mul = 1
value_mul = 1
for key, value in dic1.items():
key_mul = key_mul * key
value_mul... |
15210fcd35677435a7a82c06a28d4265f072cb52 | razyesh/razyesh.github.io | /iw/python-assignment-ques/exchange_first_last_char-q9.py | 386 | 4.1875 | 4 | """
9. Write a Python program to change a given string to a new string where the first
and last chars have been exchanged.
"""
def exchange_char(input1):
"""function to swap last and first char"""
original_input = list(input1)
original_input[0], original_input[-1] = input1[-1], input1[0]
return "".joi... |
89b6188c008d1a123eff4cf8a97c9fcb3584a99b | razyesh/razyesh.github.io | /iw/python-assignment-ques/smallest-q19.py | 458 | 3.9375 | 4 | """
Write a Python program to get the smallest number from a list.
"""
sample_input = [11, 4, 2, 3, 6, 1, 0]
def find_smallest(input1):
"""
function to find the smmallest number from the list
:param input1:
:return:
"""
new_list = [input1[0]]
for i in range(len(input1)):
if new_li... |
ff8a45b76f5c740a7fcb827d8d667769e5c9c93c | razyesh/razyesh.github.io | /iw/python-assignment-ques/q39.py | 666 | 4.46875 | 4 | """
39. Write a Python program to unpack a tuple in several variables.
"""
import string
def upack_tuple_variable(input_tuple):
"""function to upack a tuple in several variables"""
variables = string.ascii_lowercase[:len(input_tuple)]
variable_list = list(variables)
result = {}
for i in range(len... |
3a0bbc27ba4a127675b9b30417baff9e38c86309 | razyesh/razyesh.github.io | /iw/python-assignment-ques/functions_ex/q1.py | 705 | 4.5625 | 5 | """
1. Write a Python function to find the Max of three numbers.
"""
from utils import get_integer
def find_max(num1, num2, num3):
"""
function to find the maximum number out of three input numbers
:param num1: first number
:param num2: second number
:param num3: third number
:return: Maximu... |
0a91827d12b7ef85443db5f1f349ac3597f1b950 | razyesh/razyesh.github.io | /iw/python-assignment-ques/functions_ex/q7.py | 765 | 4.4375 | 4 | """
7. Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.
"""
def count_upper_lower(sample_string):
"""
function to count number of upper and lower case letter in given string
:param sample_string:
:return: counted number
"""
co... |
a34a1b11158e3b577208308b25cbbec7d6566144 | razyesh/razyesh.github.io | /iw/python-assignment-ques/functions_ex/q8.py | 847 | 4.40625 | 4 | """
8. Write a Python function that takes a list and returns a new list with unique
elements of the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
"""
from utils import get_random_list
def get_unique(sample_list):
"""
to get the new list with unique elements
:param sample_list:... |
539be65f70820e15b756234da86cbe3cbe2ae704 | knuddj1/op_text | /op_text/processing.py | 4,216 | 3.984375 | 4 | import csv
from torch import tensor
from torch.utils.data import Dataset
class DataProcessor:
"""Processing class to convert text to model input parameters"""
def __init__(self, tokenizer, max_seq_len):
"""
Parameters:
- tokenizer : The correct tokenizer for the specific model type. Used to tokenizer input d... |
64596dc9c93d5aaa95c2a3ff29c19a51bc9a98da | nidhibhalla/python-practice | /NumberGuess.py | 663 | 4.0625 | 4 | import random
numberofguess = 0
number = random.randint(1, 10)
name = input("Please enter your name ")
print("Hello %s, guess a whole number between 1 to 10" % name)
while numberofguess <3:
guess= int(input("Take a guess "))
numberofguess+=1
guessleft = 3- numberofguess
if guess<number:
pri... |
f3d3d373784cc95221813363521d232761a34868 | errorterror6/Python-Training | /If_statements.py | 530 | 4.28125 | 4 | print("Welcome")
is_male = True #boolean
is_tall = False
if is_male == True or is_tall == True:
print("you are a male or tall or both") #everything in the indentation will be executed if true.
else:
print("you are neither male or tall.")
if is_male == True and is_tall == True:
print("you are... |
36e8e4903e74ea68625e0abdaecbd225c4c89d63 | erlichg/clew | /ConsumerService/consumer/utils.py | 4,390 | 3.765625 | 4 | ACTIONS=['start', 'cancel_start', 'stop', 'cancel_stop'] # order is important here. Events will be ordered by this!!!
def calculate_periods(records):
"""
This method is responsible for calculating the periods from the raw records list.
First, it sorts the list by medication_name and event_time and action.... |
1678bad6f8d812a3e779829b6199bc1e8c1f3991 | marshallreverb/Labyrinthe | /labyrinthe.py | 1,926 | 4 | 4 | # -*-coding:Utf-8 -*
"""Ce module contient la classe Labyrinthe."""
class Labyrinthe:
"""Classe représentant un labyrinthe."""
def __init__(self, robot, obstacles):
self.robot = robot
self.grille = obstacles
self._position = robot
self.door = door(obstacles)
def ... |
b064603c3919fc4f547081db8380ea90c9d8ec87 | RAMYAMURUGESH/ASSIGNMENT_PYTHON-PROGRAMMING | /netsalary_condition.py | 882 | 3.84375 | 4 | #to find the netsalary after the deduction of income tax based on the condition of gross salary
emp_id=1001
basic_salary=15000
allowances=6000
monthly_gross_salary=basic_salary+allowances
if(monthly_gross_salary<=5000):
income_tax=0
net_salary=monthly_gross_salary
elif(monthly_gross_salary>=5001 and monthly_gross_... |
92b413dd80fea52ca2c73ed65f9a0b0c8fb1c696 | NMCPLindsay/CIT228 | /Chapter3/listFun.py | 460 | 4.09375 | 4 | group=['Michigan', 'Kentucky', 'Texas', 'Kansas', 'Oklahoma']
print("---------------Exercise 3-10------------------")
print(f"Original List: {group}")
group.append('California')
print(f"List after add: {group}")
group.remove('Kentucky')
print(f"List after delete: {group}")
print(f"Temp sort list: {sorted(group)}")
grou... |
e6b8398f339e668194186ff5d9fe79599445f843 | NMCPLindsay/CIT228 | /Chapter10/gutenberg.py | 1,152 | 4.15625 | 4 | filenames=['Chapter10/gutenberg.txt','Chapter10/gutenberg2.txt','Chapter10/gutenberg3.txt']
# searchWord=input("What common word do you want to search for in these files?")
def find_words(filename, searchWord):
count=0
count2=0
try:
with open(filename, encoding="utf-8") as f:
contents= ... |
b0d6ab0d7354e401aa885f96cf3f28ba1009b77a | NMCPLindsay/CIT228 | /Lesson1/mathFun.py | 227 | 3.71875 | 4 | numx=20
stringx=str(20)
result1=numx*10
result2=stringx*10
print("result 1= ",result1)
print("result 2= ",result2)
value1=100
value2="100"
print("The type of value 1=", type(value1))
print("The type of value 2=", type(value2)) |
206d163662e67239c13b363f31539a3179f1abff | NMCPLindsay/CIT228 | /Chapter4/cube.py | 206 | 3.890625 | 4 | print("------------------4-8---------------")
numbers=list(range(10))
for n in numbers:
print((n+1)**3)
print("------------------4-9---------------")
cubes=[(n+1)**3 for n in numbers]
print(cubes)
|
6c4140083bbc6113f94294a49319c07c0ee99d46 | NMCPLindsay/CIT228 | /Chapter7/mathMagic.py | 546 | 3.875 | 4 | import random
probs=int(input("How many problems you want to run?"))
counter=0
numberCorrect=0
while counter<probs:
randNum1=random.randrange(1,1000)
randNum2=random.randrange(1,1000)
correctAns=int(randNum1+randNum2)
yourAns=int(input(f"what is the answer to {randNum1}+{randNum2}?"))
if correctAns=... |
e469547f0f5b429d761effd96d359776b7e0914d | NMCPLindsay/CIT228 | /Chapter7/mathMagicWithBreak.py | 683 | 3.84375 | 4 | import random
probs=10
counter=0
numberCorrect=0
while counter<probs:
randNum1=random.randrange(1,1000)
randNum2=random.randrange(1,1000)
correctAns=int(randNum1+randNum2)
yourAns=int(input(f"what is the answer to {randNum1}+{randNum2}?"))
if correctAns==yourAns:
print("Yay! you did it!")
... |
5af4bd84921b2d6543baa70801ed908c110a334b | LJunChina/python_space | /demo.py | 601 | 3.90625 | 4 | # coding=utf-8
print "hello world"
print "您好"
if True:
print("true")
else:
print("false")
'''
地方斯蒂芬几十块大数据分开了时代峻峰
第三方士大夫水电费水电费
'''
# 以下代码用来打印
print('a'),
print('b')
# 变量的定义
score = 100 # 定义了一个变量 里面存储了一个数值 为100
high = 180 # 单位是cm
applePrice = 3.5
weight = 7.5
print(applePrice * weight) # 如果出现第二次 变量 = ?表示赋值
#... |
ea5829bb704d53eaeed020990bb315a698dd2e9c | cz-fish/advent-of-code | /2019/25a.py | 7,057 | 3.75 | 4 | #!/usr/bin/env python3
import intcode
import sys
from collections import namedtuple
Room = namedtuple('Room', ['name', 'desc', 'directions', 'items', 'path'])
with open('input25.txt', 'rt') as f:
lines = f.readline().strip()
program = [int(i) for i in lines.split(',')]
plan = {}
path = ''
current = None
screen... |
1d32e20d7a592b25bd9d6ffc0f071f86a17541d5 | cz-fish/advent-of-code | /2018/wristwatch.py | 8,248 | 3.515625 | 4 | from typing import Dict, List, Tuple
"""
Addition:
addr (add register) stores into register C the result of adding register A and register B.
addi (add immediate) stores into register C the result of adding register A and value B.
Multiplication:
mulr (multiply register) stores into register C the result of multiply... |
7844dae1b272b97143c7cd68a412ef040a4af3c2 | cz-fish/advent-of-code | /2022/03.py | 1,510 | 3.5 | 4 | #!/usr/bin/python3.8
from aoc import Env
e = Env(3)
e.T("""vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw""", 157, 70)
def priority(item):
if item >= 'a' and item <= 'z':
return ord(item) - ord('a') + 1... |
269b117a77c93a764fd65c7a15158e34e5b93293 | cz-fish/advent-of-code | /2018/13.py | 4,400 | 3.546875 | 4 | #!/usr/bin/python3.8
from aoc import Env, Grid
e = Env(13, raw_lines=True)
e.T(r"""/->-\
| | /----\
| /-+--+-\ |
| | | | v |
\-+-/ \-+--/
\------/ """, "7,3", None)
e.T(r"""/>-<\
| |
| /<+-\
| | | v
\>+</ |
| ^
\<->/""", None, "6,4")
def find_carts(grid):
carts = []
symb = '<... |
13a1eed7db60904d4e66dacbfa0d3d742c4dad05 | cz-fish/advent-of-code | /2018/aoc/integers.py | 1,119 | 4.15625 | 4 | from typing import List
class Integers:
@classmethod
def prime_factors(cls, n: int) -> List[int]:
"""Returns a list of all prime factors of the given integer
'n' in ascending order. Returns and empty list for integers
lower than 2."""
if n < 2:
return []
... |
a53eda326b20b382bfef2a0c3bf699472bb87a19 | cz-fish/advent-of-code | /2022/20.py | 6,534 | 3.546875 | 4 | #!/usr/bin/python3.8
from aoc import Env
e = Env(20)
e.T("""1
2
-3
3
-2
0
4""", 3, 1623178306)
VAL = 0
PREV = 1
NEXT = 2
# Linked list kind of solution. Actually move each number N places
# in the list. Slow, but fast enough for part 1
def mix(numbers):
mixed = []
for i, num in enumerate(numbers):
... |
825afe67ae3bf550f62be615c261846f2fb47d01 | jasvinder1107/algorithms-and-practicecode | /drawing.py | 1,669 | 3.890625 | 4 | #!/usr/bin/env python
import os
import sys
def pageCount(n, p):
count=0
initialpage=1
lastpage=n
if n%2 == 0:
#number of pages are even
if (n//2) >= p:
#start from begining
if p == initialpage:
count=0
else:
while in... |
bf649019afa7801bee2a6e4774d6755dad1c167a | jameswillett/the-ultimate-pyg-latin-translator | /pyg.py | 1,422 | 3.875 | 4 | original = input('Enter a sentance to translate: ')
def is_all_caps(word):
if (word[0].isupper() or not word[0].isalpha()) and len(word[1:]) > 0:
return is_all_caps(word[1:])
if (word[0].isupper() or not word[0].isalpha()) and len(word[1:]) == 0:
return True
return False
def has_no_letters(word):
if n... |
9996c3abb548c4efd6ab7b6ab054a559220fee94 | pairing4good/python-intro | /app/functions_library.py | 433 | 3.5625 | 4 | def say_hi():
return "__"
def concatenate(string1, string2):
# Enter your code here
return None
def get_day_difference(day_one, day_two):
# Enter your code here
return None
def get_age_in_2050(age_now):
# Enter your code here
return None
def convert_to_celsius(fahrenheit):
# Ente... |
e91391585125ff9a4272a3bfaec34e7aba1eabe4 | corerd/pythes | /pythes-cli.py | 1,153 | 3.53125 | 4 | '''Search Hunspell thesaurus for words and related information
'''
import sys
from ntpath import basename
from pythes import PyThes
def display(word_meanings):
print('LOOK UP:', word_meanings.word)
print('{:8} | {:30} | {}'.format('POS', 'MEAN', 'SYNONYMS'))
for meaning in word_meanings.mean_tuple:
... |
9ede0f01c82a08993e3cdb3f1761da2dd643b5ba | Surya0705/Python_WebCam_Viewer | /Main.py | 606 | 3.890625 | 4 | import cv2 # Importing the OpenCV Python Module for this Program.
a = cv2.VideoCapture(0) # Taking Video from Default Camera.
while(True): # Putting a While loop.
b, c = a.read() # Making the Program read the Video Captured in 'a'.
cv2.imshow('Python WebCam Viewer', c) # Displaying the Video through a Pop-up Window.... |
2bc6ca72a2d551e44965f031392b6ce0b47fc1d9 | Annu-dev/Task-7 | /Task7_3.py | 611 | 3.65625 | 4 | class FindThreeElements:
def __init__(self,values):
self.values = values
def elements(self):
lt = len(self.values)
result_set = []
sol = 0
for first in range(0, lt):
for second in range(first+1, lt):
for third in range(second+1, lt):
... |
063a43892f8d41428f28b3ae4695766d7ab7fc56 | pqmach777/python_exercises | /pythonHWK.py | 3,059 | 4.3125 | 4 | # 1. Hello, you!
# name = input("What's your name? ")
# print("Hello, " + name + "!")
# 2. HELLO, YOU!
# name = input("WHAT IS YOUR NAME? ")
# print("HELLO, " + name.upper() + "!")
# print("YOUR NAME HAS " + str(len(name)) + "! AWESOME!")
#3 Madlib
# print("Please fill in the blanks below:")
# print("___(name)____'s... |
f7d99f831dd6bf374c03d2b0cd2158b9b9ebe2d3 | austin-hull09/Python | /Programs/Program 6/Untitled.py | 789 | 3.5 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
buildings = pd.read_csv('buildings.csv')
buildings = pd.DataFrame(buildings)
print(buildings)
occurrences = []
for i in range(len(buildings)):
occurrences.append(buildings.ix[i, "Year Built"])
frequency = []
for i in range(1896, 2018):
... |
f28089d301e45bd26965588874011e6effe55522 | Danya-Rogozov/DanyaR | /Bank.py | 827 | 3.5625 | 4 | import account
import evro
def main():
rate = int(input("Введите процентную ставку: "))
money = int(input("Введите сумму: "))
period = int(input("Введите период ведения счета в месяцах: "))
result = account.calculate_income(rate, money, period)
print("Параметры счета:\n", "Сумма: ", money, "\n", "... |
b16e788ac5d67a3addb21eed584be42c23a60d28 | rwehner/rl | /codingbat/python/Logic2.py | 543 | 3.625 | 4 | def make_bricks(small, big, goal):
if goal < (big * 5):
quotient, remainder = divmod(goal, 5)
if quotient <= big:
if goal - (quotient * 5) <= small:
return True
else:
return False
if goal - (big * 5) <= small:
return True
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.