blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9ffbfe4e1b57356f2580e02877faa3b7a8ae4f5b | pvictor222/ft_linear_regression | /model_training.py | 2,348 | 3.984375 | 4 | # import sources
from src.read_data import read_data
from src.gradient_descent import gradient_descent
from src.data_visualisation import data_visualisation
# import libraries
import random
import numpy as np
if __name__ == '__main__':
# initializing variables
theta_0 = 0
theta_1 = 0
alph... |
f4601e78704147051c24b398c4e7be88ce30d6e1 | mateszadam/Trapez_terulet_kerulet | /main.py | 642 | 3.9375 | 4 | def main() -> None:
print('Trapéz kerület és terüet számolás!')
A: float = float(input('a: '))
B: float = float(input('b: '))
C: float = float(input('c: '))
D: float = float(input('d: '))
M: float = float(input('m: '))
Terület: float = 0
Kerület: float = 0
if A <= 0 or B <= ... |
79ae50e42cf07d03df04a793b746a50618bde221 | jcherubino/magic_hat | /scripts/hat.py | 1,173 | 3.53125 | 4 | #!/usr/bin/env python
'''hat.py is a ROS node that publishes the output of a 'magic hat' that contains an infinite amount of turtles with an index and a quality.
Date Last Updated: 22/9/19 by Josh Cherubino
Purpose: Publish the output of the magic hat so that the corresponding subscriber node can determine whether t... |
f82e38bddd2070804cd996299722b9bbae6c1d6b | Jason-pro1/-Python- | /例3、检测2的幂次/checkPowerOf2.py | 730 | 3.921875 | 4 | # 例3、检测2的幂次
"""1、问题描述:检测一个整数n是否为2的幂次。
2、问题示例: n=4,返回True;n=5,返回False
"""
# 代码实现:
# 采用UTF-8编码格式
# 参数n是一个整数
# 返回True或者False
class Solution:
def checkPowerOf2(self, n):
ans = 1
for i in range(31):
if ans == n:
return True
ans <<= 1 # 位运算 ans = ans << 1
... |
ca2b34e1841ab838b5b74640bb1d6d843bec1710 | Kr1eg3/ShinyTrafficModel | /vehicle.py | 9,162 | 3.671875 | 4 | #!/usr/bin/python3
from abc import ABC, abstractmethod
from random import random, uniform
class Vehicle(ABC):
next_id = 1
def __init__(self, posx, posy, initial_speed, road_length, max_speed=3, vehicle_type='cooperator'):
self.posx = posx
self.posy = posy
self.initial_speed = initial_... |
ab1b47cc4898449827fa0076c888e5410c52e6a7 | Ebyy/python_projects | /Files/exercises_10_11.py | 219 | 3.625 | 4 | import json
favorite_number = input("What is your favorite number? ")
filename = 'favorite_number.json'
with open(filename,'w') as f_obj:
json.dump(favorite_number,f_obj)
print("Thanks! I'll remember that.")
|
12b59f10d966f8f1fdd4d769419d7018c8144ef3 | asan-itc/forkairat | /stroki/stroki25.py | 238 | 3.515625 | 4 | text = "У вас есть строка 'Запуск Ethereum 2.0 состоится 1 декабря. На депозитный контракт внесено более 524 288 ETH"
x = text.split()
for i in x:
print(i,type(i)) |
ac2a912ade4f32e815321fd60c958980949895ae | shruti-2522/PYTHON | /filter.py | 289 | 3.65625 | 4 | # filter_function
"""num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 45, 67]
def is_gretter_5(num):
return num > 5
val = list(filter(is_gretter_5, num))
print(val)"""
# REDUCE FUNCTION
from functools import reduce
num1 = [20, 30, 40, 59]
a = reduce(lambda x, y: x + y, num1)
print(a)
|
c2a4af0fd2733ce2a9dddb1ecc016095d91ba700 | Kunal352000/python_program | /basicFunction5.py | 110 | 3.75 | 4 | def show(x,y):
print("sum=",x+y)
a=int(input("Enter no.1: "))
b=int(input("Enter no.2: "))
show(a,b)
|
89c3b11aeceb826125ab2ad51867858e8575df89 | HuaMa001/python001 | /d06/dictDemo3.py | 304 | 3.515625 | 4 | users=[
{"name": "John", "h": 170, "w": 60},
{"name":"Mary","h":160, "w":48}
]
#請計算每一筆的bmi值=?
for user in users:
#print(user, type(user)) 判斷資料
h= user.get("h")
w= user.get("w")
bmi="%.2f"%(w/((h/100)**2))
print(user, type(user), bmi)
|
abab4fd984f6f893848170cc47a300c3c5281f8b | laysakura/relshell | /relshell/test/shellcmd/simplest | 452 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
word_count
~~~~~~~~~~
:synopsis: input: word, output: occurence count of the word
"""
import sys
if __name__ == '__main__':
sys.stderr.write('input any word (Ctrl-D to finish)\n')
while True:
word = sys.stdin.readline()
if word == ... |
0db25cb29558167cc8cdcded4bbb455b71cab2e9 | cyrillelamal/pogrom | /sem6/task1/primo.py | 677 | 3.90625 | 4 | # Разработка скрипта, вычисляющего статистические показатели (среднее
# значение, дисперсия, среднее квадратичное отклонение) для данных,
# считанных из CSV-файла.
import csv
import statistics
with open("./data.csv", "rt") as f:
reader = csv.reader(f)
costs = list(map(lambda r: r[2], reader))[1:]
mean =... |
be423fa367e812582862592c6e0f02ae6d182bc1 | shulp2211/SeeCiTe | /inst/python/datastructutils.py | 1,116 | 4.0625 | 4 | #!/usr/bin/env python3
'''
General utility functions concerning dictionaries, lists etc.
'''
def get_range(d, begin, end):
'''
Subset a dictionary, returning the elements in the given index range(treat dict as array)
Args:
d: python dictionary
begin: first key element
end: end key e... |
5f789799044027f4fd60faeb090e047c1b7615d8 | hyeseong-dev/2021-03-11-algorithms | /chap01/rectangle.py | 473 | 3.5 | 4 | # 가로, 세로 길이가 정수이고 넓이가 area인 직사각형에서 변의 길이 나열하기
area = int(input('직사각형의 넓이를 입력하세요.: '))
for i in range(1, area+1): # 1부터 사각형의 넓이를 계산
if i * i > area: break # 참이면 loop를 종료함. i가 가장 긴변의 길이가 되기 때문
if area % i : continue # i 가 area의 약수가 아닐 경우 실행, 나머지가 있는 경우
print(f'{i}*{area//i}') |
2c3399b400cb560762edaeb896079aaadf33af76 | python-elective-1-spring-2019/Lesson-12-Testing-Debugging-Exeptions | /code_from_today/if_bla.py | 198 | 3.59375 | 4 |
def check(x):
if x == 0:
x += 1
elif x > 0:
hksfhslkjafhlkafjdlkjdf
else:
adsjfhljakhlfkds
return x
print(check(0))
for i in range(20):
print (i)
|
835ea47666d277e9e49bf098963c5b7c98fb028a | munirmaricar/Textual-Analysis | /TextualAnalysisForSpecificRegulator.py | 22,408 | 3.5 | 4 | """
SPECIFIC CODE FOR EACH REGULATOR
Steps for Executing Code Specific For Regulator:
1. Import the data by uploading the CSV and XLSX files from the different regulators. Rename them as FDIC.csv, OCC.xlsx and FED.csv respectively.
2. Create a new empty folder called Pages. This will store all the converted pages of t... |
e5ee29542abf83dd889ca4da7ada595548d198e9 | Pat-Oz/basics | /createtext2.py | 418 | 3.734375 | 4 | # FILENAME INPUT
filename = raw_input("Enter filename: ")
target = open (filename, 'a')
# USER INPUT
print "Enter first two lines of text:"
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
# WRITE INPUT
print "Input text succesfully written to file."
target.write(line1)
target.write("n")
target.write(line2... |
c460ef27036773580ae0691a9cdc7a77f785140b | rithwik00/practice-problems | /memoization/howSum.py | 628 | 3.59375 | 4 | # takes targetSum and array of numbers as input
# return array of any combination of elements(repeated allowed) that add up to the targetsum
def howSum(targetSum, numbers):
if targetSum in visited:
return visited[targetSum]
if targetSum == 0:
return []
if targetSum < 0:
return Non... |
5f2cba92becf82d1034de60b288808b7fe7fc2ee | subash319/PythonDepth | /Practice21_OOP_StaticMethods_ClassMethods/Prac21_1_HCF_two_numbers.py | 1,202 | 4.03125 | 4 | # 1. This is a function to find the highest common factor of two numbers
# Make it a static method in the Fraction class that you had written in earlier exercise.
class Fraction:
def __init__(self, nr, dr=1):
self.nr = nr
# making the denominator postive if it is negative
self.dr = dr if ... |
35cdb6c79aa583a3b99d1da33de822bc20b04eeb | HarshaaArunachalam/guvi | /code/42.py | 105 | 3.6875 | 4 | x,y=input().split()
if(len(x)>len(y)):
print(x)
elif(len(y)>len(x)):
print(y)
else:
print(x)
|
9992b8dba03bd0a71ad709cb80ddf435517793ef | DierSolGuy/Python-Programs | /list_merge.py | 132 | 3.765625 | 4 | L1 = input("Enter the 1st list of numbers: ")
L2 = input("Enter the 2nd list of numbers: ")
L3 = L1 + L2
print(L3,sep='',end=' ') |
059759cf158017763e93924b6a1afb06eb6c61cc | Balajikrishnan00/Python | /Operator,input,if else.py | 2,075 | 4.03125 | 4 | '''
n=100
n1=n+10
print(n1)
# eval()
#1p
total=eval('10+20+30+40+50+60+70+80+90+100')
print(total)
#2p
total=eval(input("Enter total"))
print(total)
import math
print(math.pow(3,2))
# end= ,sep=
# formatted String
# %i - integer
# %d - integer
# %s string
# %f -float
name='siva'
age=24
weight=50.6
height=23
print(... |
3929ca35a89f25dd309e93a9c7b6ac8dbd189d7a | cIvanrc/problems | /ruby_and_python/4_string/ceasar_encryption.py | 1,189 | 4.625 | 5 | # Write a Python program to create a Caesar encryption
# Note : In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques.
# It is a type of substitution cipher in which each letter in the plaintex... |
9c519052b0517ab15c895b4243d9fe68b1e3a2ce | ykzzyk/Networking | /P1/MultithreadServer/Method_1/server.py | 2,108 | 3.59375 | 4 | from socket import *
import threading
def tcp_server(TCP_IP, TCP_PORT, BUFFER_SIZE):
# Prepare a server socket
serverSocket = socket(AF_INET, SOCK_STREAM)
try:
# Bind TCP_IP address and TCP_PORT
serverSocket.bind((TCP_IP, TCP_PORT))
except Exception:
print("\n")
threa... |
c35e7249c22ad1c1f2734e133f2564d0bb377b8c | DenisLamalis/cours-python | /lpp101-work/index_34.py | 592 | 4.0625 | 4 | # For loop - exercise
names = ['john ClEEse','Eric IDLE','michael']
names1 = ['graHam chapman', 'TERRY', 'terry jones']
all_names = set(names + names1)
for name in all_names:
print(f'{name.lower().title()}!, you are invited to the party saturday.')
# Solution
names = ['john ClEEse','Eric IDLE','michael']
name... |
f631c5f8c8a9a0bc0e92528200d542d7fe159550 | marciof2/PYTHON- | /desafio06.py | 190 | 3.8125 | 4 | n= int(input('Digite um valor: '))
dobro= n*2
triplo= n*3
rq= n**(1/2)
print('Você digitou {} \nO dobro é {} \nO triplo é {} \nA raiz quadrada é {:.2f}'.format(n, dobro, triplo, rq)) |
45bb91f30af902baf2a3bc6704f23982bf436973 | hoobear15/secretmessages | /cipher.py | 1,608 | 4.1875 | 4 | class Cipher:
"""creates a new Cipher object; stores original user message as encrypted or decrypted message and
creates a one time PAD to be used if user requests a decrypted message"""
def __init__(self, text, status):
self.message = str(text).upper().replace(" ", "")
if status == "encry... |
e962526e7bd974684c706c1ab083552b1b7afc37 | timwisbauer/adventofcode2020 | /1-2/repair.py | 1,123 | 3.796875 | 4 | # Advent of Code Day 1: Report Repair
# Find the two entries that sum to 2020 and multiply them together.
def find_match(expenses):
# Sort the elements in the list first.
expenses.sort(reverse=True)
for a_index, a in enumerate(expenses):
# Starting with a_index + 1, loop through rest of l... |
b59536efdf599c97a32d0e9e335615194efaccb5 | shinjl/xcity-finder | /convert_data.py | 2,261 | 3.65625 | 4 | # Data preparation utility for runtime
# Split large world city file into small chunks to save runtime memory
# ==============================================================================
import time
import os
import csv
countries = {}
cities = {}
def read_country_code():
print('loading country code')
wi... |
caa078c65f99fcfe30088b1a5906e2cf751bc3f1 | LucasFerreiraB/Teste | /guppe/Seção 7/Ordered_Dict.py | 908 | 4.09375 | 4 | """
Modulo Collections - OrderedDict
# Ordem nao garantida em um dicionario
dicio = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(dicio)
for chave, valor in dicio.items():
print(f'chave={chave}: valor={valor}')
OrderedDict -> É um dicionario, que nos garante a ordem da inserção dos elementos.
# Fazendo import
from col... |
2433d96edb23d91661267f894851b2d5ebf4fa05 | ant0nm/d13_assignment4_oop | /vampire.py | 1,259 | 3.921875 | 4 | class Vampire:
""" A class representing a vampire. """
# class variables
coven = []
# class methods
@classmethod
def create(cls, name, age):
new_vampire = Vampire(name, age)
cls.coven.append(new_vampire)
return new_vampire
@classmethod
def sunrise(cls):
... |
cfb3ab1044508afae6b84b559eacd6018db1f667 | shuiblue/INTRUDE | /util/timeUtil.py | 360 | 3.703125 | 4 | from datetime import datetime
def days_between_noTZ(d1, d2):
d1 = datetime.strptime(d1, "%Y-%m-%d %H:%M:%S")
d2 = datetime.strptime(d2, "%Y-%m-%d %H:%M:%S")
return (d2 - d1).days
def days_between(d1, d2):
d1 = datetime.strptime(d1, "%Y-%m-%dT%H:%M:%SZ")
d2 = datetime.strptime(d2, "%Y-%m-%dT%H... |
a2324c47605cceb1a02ab3edaec4f1ef4f00a73c | ThePro22/LearnPygame | /Python Challenges/Challenge 06 - Extention.py | 499 | 4 | 4 | #Challenge 6 - Extention
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
totalMoney = float(input("How much money did you have at the start of the week? £"))
for day in range(5):
cost = float(input("How much money did you spend on school dinner on " + week[day] +"? £"))
totalMoney = totalMoney - cost
... |
e1d4bca2e0c4884234c27f71c04782144408abf4 | windy1/rdt-simulation | /rdt.py | 9,697 | 3.5625 | 4 | """
CS 265 programming assignment 2.
Name: Walker J. Crouse
Date: December 2018
In this assigment, you will implement a reliable data transfer protocol over an unreliable channel. Your solution should
protect against packet loss and packet reorder. Corruption protection is not required. The protocol you implement sho... |
f6a2c252f465db37cc009a26549c0daa1f31e2a5 | TaineC/python_adv | /tkinter_gui.py | 1,521 | 3.640625 | 4 | import tkinter as tk
import string
import random
#future improvements that I can do once I've gained more skills -- better syntax that I can only partially understand logically for now
#function -- the print function for each password type could be integrted within the password generator function
#a loop could be wri... |
be45c33bada9c2c0dce0d3963f5045cfabdc7b61 | mini-ray/python | /ProjectStem/code3.2.1.py | 90 | 3.9375 | 4 | num = input("Enter a number: ")
if float(num) > float(45.6):
print ("Greater than 45.6")
|
60312668c58be539b17446d07b8fdbe6b5396412 | ishantk/KnowledgeHutHMS2020 | /Session4Q.py | 2,344 | 3.640625 | 4 | """
Multi Threading in Python :)
"""
import time
import requests
import json
import threading
"""
class PrintingTask:
def print_documents(self):
for i in range(1, 11):
print("[JOHN] Printing Document #{}".format(i))
time.sleep(1)
class FetchNewsTask:
def fetch_news(s... |
5956b248b369fb4d1b01a08b6b4a0d3e21982ab1 | kepengsen/study | /python/01/03.py | 323 | 4.0625 | 4 | #!/usr/local/bin/python3
num1,num2=-1,7
print('猜数字游戏!')
while num1!=num2:
num1=int(input('请输入一个数字'))
if num1<num2:
print('猜的数字小了。。。')
elif num1>num2:
print('猜的数字大了。。。')
elif num1==num2:
print('恭喜您!猜对了。')
|
ff332afd09bb1eef4115d1bfd332ac8a900af3d0 | antondelchev/Advanced---Exams | /Numbers Search.py | 532 | 3.65625 | 4 | def numbers_searching(*args, info=None):
if info is None:
info = []
full_sequence = [int(el) for el in range(min(args), max(args) + 1)]
info.append(*[el for el in full_sequence if el not in args])
duplicates = sorted(set([el for el in args if args.count(el) > 1]))
info.append(dupli... |
ccf34a70760195bfb5eef86930cfa2c438c7bd54 | skshabeera/question-bank | /month.py | 273 | 4.125 | 4 | m=int(input("enter the number"))
if m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12:
print(m," month number of days 31")
elif m==4 or m==6 or m==9 or m==11:
print(m,"month number of days 30")
elif m==2:
print(m,"month number if days 28")
else:
pass |
200d496eacbc4be8c0229bcccd937ec7687e17f1 | aahnik/mendi | /mendi/mendi.py | 1,547 | 4.0625 | 4 | """Simple wrapper that helps you write a menu-driven program easily.
> A menu-driven program is one, in which the user is provided a list of choices.
> A particular action is done when the user chooses a valid option.
> There is also an exit option, to break out of the loop.
> Error message is shown on selecting a wro... |
8a4535b44dce243b0ab23ffeac877c64cc4580e6 | tisage/cs50 | /pset6/sentiments/smile | 1,133 | 3.515625 | 4 | #!/usr/bin/env python3
import os
import sys
from analyzer import Analyzer
from termcolor import colored
def main():
# ensure proper usage of command line argument
if len(sys.argv) != 2:
sys.exit("Usage: ./smile word")
# absolute paths to lists
positives = os.path.join(sys.path[0], "positive... |
07162239aad2a996a080f5e7b8ba2120d485a2d1 | m4tti1/foundations-sample-website | /color_check/controllers/get_color_code.py | 1,299 | 3.65625 | 4 | # This file should contain a function called get_color_code().
# This function should take one argument, a color name,
# and it should return one argument, the hex code of the color,
# if that color exists in our data. If it does not exist, you should
# raise and handle an error that helps both you as a developer,
# fo... |
0da86d28be945035e82d7b7ec83c0dce0c0d6b62 | mrmaxguns/Misc-Python | /old/password-gen-v3.0.1.py | 2,575 | 3.859375 | 4 | '''
Password Generator
V3.0.l
Maxim Rebguns
'''
import random
from proofread import *
err = "Please select a natural number!"
def run():
def generate(c, cap, numb, x):
first = random.randint(1,2)
if first == 1:
vowel = True
if first == 2:
vowel = F... |
a2f92a85fe6b25d5ba95f249c0b6d4c62c3a7e7c | aksampath123/Python_Development_Projects | /python_beginner/function_list.py | 667 | 4.0625 | 4 | shopping_list = []
def show_help():
print("Enter the items/amount for your shopping list")
print("Enter DONE once you have completed the list, Enter Help if you require assistance")
def add_to_list(item):
shopping_list.append(item)
print("Added! List has {} items.".format(len(shopping_list)))
def show_li... |
266663e673999577bb0cfb876dc5dafcb32eb910 | sarahmaeve/lpthw | /guess1.py | 965 | 4.0625 | 4 | # inspired by https://www.youtube.com/watch?v=O17TzRU0Pss
# but with a function.
# this can be improved a lot.
import random
def analyze_guess(guess, target):
guess = int(guess)
if not type(guess) == 'int':
msg = "I don't understand that."
if guess < target:
msg = "Too low!"
elif guess... |
2118f35dcad1d385af9cd0b13c273662f7c846eb | Cgalvispadilla/reto_sofka | /Juego.py | 3,232 | 3.5 | 4 | from Jugador import *
from Conductor import *
from Carro import *
from Carril import *
from Pista import *
import random
class Juego():
def __init__(self) -> None:
self.__id=(random.randint(1, 100000))
def get_id(self):
return self.__id
def min_jugadores(self,num:int):
if num>=3:
... |
d00d24585038e7d6788e9c4d630bb6048802750f | jacksarick/My-Code | /Python/python challenges/euler/021_amicable_nums.py | 595 | 3.5625 | 4 | # Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
# If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110... |
1488f63b2f8723658ecc4758f6230294b1dec5e6 | tnaswin/PythonPractice | /Aug21/file_io.py | 791 | 4.09375 | 4 | with open('app.log', 'w') as f:
#first line
f.write('my first file\n')
#second line
f.write('This file\n')
#third line
f.write('contains three lines\n')
with open('app.log', 'r') as f:
content = f.readlines()
for line in content:
print line
#Read From A File In Python
print "Read From A File ... |
9db93618766ecfda89102ac1839716e457b7f167 | alaminbhuyan/Python-solve | /problem/Finding the percentage.py | 652 | 3.953125 | 4 | Finding the percentage
Dict = {}
# num = int(input('enter num of elements: '))
# for i in range(num):
# keys = input('Enter your keys: ')
# values = list(map(float,input('enter your values: ').split()))
# Dict.update({keys:values})
# #print(Dict)
# for a in Dict.values():
# total = sum(a)/3
# Dict.u... |
3b3151a5e585a475b6880590b0d2a15b0d877fcc | Osheah/hospfcs2021 | /semester1/week06/readsNumber.py | 356 | 4.21875 | 4 | # program read in a text file from an existing text
# helen oshea
# 20210224
fileName = 'count.txt' # location of the file
def read_number(): # function to read in the text
with open(fileName) as f:
num = int(f.read()) # convert the number string to an integer
return num # return the integer
print(read_nu... |
1a33a3181f104759dc583e408c5405286aab0e19 | Bhagyashri1811/practised | /quick sort.py | 596 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 26 19:39:41 2021
@author: Bhagyashri
"""
def partition(arr,low,high):
pivot=arr[high]
pindex=low
for j in range(low,high):
if(arr[j]<pivot):
arr[j],arr[pindex]=arr[j],arr[pindex]
pindex=pindex+1
arr[pindex],ar... |
06d8f2b680bccb7906a9648ec841d096f6c95f8e | ostrowto/python | /Py_Math_Examples/is_Prime/prime_2_range.py | 503 | 3.609375 | 4 | # prime_2_range.py
import sys
list_of_primes = []
input_to_parameter = int(input('End parameter: '))
end_parameter = input_to_parameter
p = 2
while p <= end_parameter:
is_prime = True
for i in range(2, p):
if p % i == 0:
is_prime = False
break
if is_prime == True:
li... |
6e1352d79ea1e6af0b8b451621ded2a2bdb3febe | RobertNguyen125/Datacamp---manipulatingDataFrame | /1_extractingTransformingData/6_filteringPractise.py | 930 | 3.703125 | 4 | import pandas as pd
import numpy as np
election = pd.read_csv('/Users/apple/desktop/manipulatingDataFrames/dataset/pennsylvania2012_turnout.csv', index_col='county')
# create boolean array: high_turnout where the turnout rate is > 70
high_turnout = election['turnout'] > 70
# filter the df
high_turnout_df = election[h... |
2947913b5b0d96742c91a7a11169b446c639fd72 | antonpigeon/Inf_2021_python | /Lab1 python/Exercize 14/Exercize 14/Exercize_14.py | 130 | 3.671875 | 4 | import turtle
turtle.shape('turtle')
n = 11
for i in range(n):
turtle.forward(100)
turtle.left(180 - 180 / n)
|
ad6ffb9bc71fc4743f8fddb54f6d60b63d218da9 | xiaolinz1987/Algorithm | /Python/utils/priorityqueue.py | 1,483 | 3.75 | 4 | class MyPriorityQueue:
def __init__(self):
self.array = []
self.size = 0
def __up_adjust(self):
child_index = self.size - 1
parent_index = (child_index - 1) // 2
temp = self.array[child_index]
while child_index > 0 and temp > self.array[parent_index... |
fcc7e0aa11a92b2b03492ff61a44fc309713b786 | pchauha7/Hand-Classification-and-Search-System | /Phase-3/Code/decisiontreeclassifier.py | 5,075 | 3.65625 | 4 | import numpy as np
class DecisionTreeClassifier:
#Initialization
def __init__(self, max_depth=None):
self.max_depth = max_depth
#fit transform
def fit(self, X, y):
"""Build decision tree classifier."""
self.n_classes_ = len(set(y)) # classes are assumed to go from 0 to n-1
... |
886ad0dc409c7ed8ad80381a96e763e32eb9f127 | yddong/Py3L | /src/Week2/for-test1.py | 310 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
mytext = "Hello you world how are you"
mycounts = {}
for character in mytext:
print(character)
print("----")
if character in mycounts:
mycounts[character] = mycounts[character] + 1
else:
mycounts[character] = 1
print(mycounts)
|
61a49f9d7960a550f6b7ac938a942fd46a6491e9 | n8jhj/Parakletos | /Game.py | 2,995 | 3.515625 | 4 | import Player
import Board
import Charactor
import pdb
class Game(object):
def __init__(self, DISPSURF):
self.surf = DISPSURF # display surface game will be drawing on
self.board = Board.Board(self) # Board on which Game is played
self.plyrs = [] # Players list
self.state ... |
89c048b5908d0fd6c471f66ff58e58eecc17bd71 | karthi031000/Freshworks | /freshworks/code.py | 1,693 | 3.9375 | 4 | import threading
from threading import*
import time
d={} # d is a dictionary used to store key-value datastore
# Create operation
def create(key,value,timeout=0):
if key in d:
print("error: Key already exist")
else:
if(key.isalpha()):
if len(d)<(1024*1024*1024) and val... |
885780e5663418b8db7a814e5396cde21c295258 | Rachel-99/Lab6-Seguridad | /elgamal.py | 946 | 3.640625 | 4 | import random
from math import pow
a=random.randint(2,10)
#To fing gcd of two numbers
def gcd(a,b):
if a<b:
return gcd(b,a)
elif a%b==0:
return b
else:
return gcd(b,a%b)
#For key generation i.e. large random number
def gen_key(q):
key= random.randint(pow(10,20),q)
while... |
d3ddae3ac90d709f6e340b363be93bb9ef8f6b83 | vitorsv1/CamadaFisica | /PARTE 1/Projeto_6/exemplo.py | 1,066 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 14:57:54 2018
@author: rcararrto
"""
#exemplos de manipulacao de bits
def main():
q= 0b10011
data = 0b101101010000
shifitado = data >> 7
XorResultado = shifitado ^ q
for b in range(1):
print(" resultado em binario {}" .format(bin(XorRes... |
45c81b8bb2b509061fb79a4d15caf8a4daa0b4b1 | kajrud/begin-to-code-python | /simple-stuff/EG3-02 Głęboki namysł.py | 203 | 3.640625 | 4 | import time
print("Pobawmy się w dodawanie")
num1 = int(input("Podaj liczbę: "))
num2 = int(input("Podaj drugą liczbę: "))
suma = num1 + num2
print("Myślę, myślę... ")
time.sleep(10)
print(suma)
|
ad2c1017ab88a2cceec3ae7cfc012cec490db61f | transducens/gourmet-ua | /jw/filter-cld3.py | 2,115 | 3.65625 | 4 | import sys
import cld3
import argparse
oparser = argparse.ArgumentParser(description="Tool that reads a list of pairs of segments from the standard input in TSV "
"format, this is: a pair of segments per line, segments separated by tabs. The script will discard any pair for "
"which the langauge detect... |
443447b46851e4b2434eeef0dd3e04d613998514 | kschlough/interview-prep | /valid_palindrome.py | 1,040 | 4.09375 | 4 | # Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
# Example 1:
# Input: s = "A man, a plan, a canal: Panama"
# Output: true
# Explanation: "amanaplanacanalpanama" is a palindrome.
# Example 2:
# Input: s = "race a car"
# Output: false
# Explanation: ... |
51281bf0e03da216ab1b53d58008a7b0d2315b95 | Azim-Islam/CSE208-Algorithm-Lab | /5/problem_1.py | 1,814 | 4 | 4 | import random
#merging 3 of the sub-array
def merge(arr, low, mid1, mid2, high):
left_array = arr[low - 1 : mid1]
mid_array = arr[mid1: mid2 + 1]
right_array = arr[mid2 + 1 : high]
left_array.append(float('inf')) #Inserting these because the array may not be properly divisible by 3
mid_array.appen... |
313db8557bd7633bbcbe1398245ecd017ec47252 | artheadsweden/New_Courses_2020 | /Python_Fundamentals/04_Variables_And_Data_Types/05 Strings Bytes and ByeArrays/03 Strings and Unicode.py | 824 | 3.875 | 4 | import sys
def main():
# Since Python 3.0 all strings are stored in Unicode
# Default Python will use UTF-8
message = "This is a Unicode string. See here: 你好."
print(message)
# Also identifiers can be in Unicode
你好 = 'Hello'
print(你好)
msg1 = 'AB'
msg2 = 'ÅÄ'
msg3 = '你好'
pr... |
90e9beefe021c308dc8d1517f75e1bdd4aa0b1f5 | jeongukjae/terminal-palette | /example.py | 2,170 | 3.515625 | 4 | from terminal_palette import Palette
palette = Palette()
print(
palette.black('Hello, World!') + palette.red('Hello, World!') +
palette.green('Hello, World!') + palette.yellow('Hello, World!') +
palette.blue('Hello, World!') + palette.magenta('Hello, World!') +
palette.cyan('Hello, World!') + palette.... |
a43f41f281284a7d4a89ea197ba342d719a8943a | haeke/datastructure | /find-a-string.py | 466 | 3.734375 | 4 |
#
def count_substring(string, sub_string):
#make sure string isn't smaller than one but not greater than 200
total = 0
#make sure it is in lower case
string = string.lower()
if( 1 <= len(string) <= 200):
for i in range(0, len(string) - len(sub_string) + 1):
if string[i:i+len(su... |
2f694c787cbf0a2efd60b3afbae1c6bc89468d07 | Ninosauleo/Python | /Cryptology/Vault/RSAdecr.py | 2,628 | 3.703125 | 4 | from Crypto.Hash import SHA512
from Crypto.PublicKey import RSA
from Crypto import Random
from collections import Counter
from Tkinter import Tk
from tkFileDialog import askopenfilename
import ast
import os
import tkMessageBox
import Tkinter
import tkSimpleDialog
import tkMessageBox
fileDir = os.path.dirname(os.path.... |
e7d0e8a52d432acc383f63aa79680c0830289a37 | transeos/hackerrank | /python/easy/list_comprehensions.py | 717 | 3.625 | 4 | #!/usr/bin/python3
# -*- Python -*-
#
#*****************************************************************
#
# hackerrank: https://www.hackerrank.com/challenges/list-comprehensions/problem
#
# WARRANTY:
# Use all material in this file at your own risk.
#
# Created by Hiranmoy Basak on 18/05/18.
#
#********************... |
ba09804c435b584a397342f0f2745d434ec2166c | roflmaostc/Euler-Problems | /052.py | 525 | 3.96875 | 4 | #!/usr/bin/env python
"""
It can be seen that the number, 125874, and its double, 251748,
contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x,
4x, 5x, and 6x, contain the same digits.
"""
def solve_problem():
"""solves problem"""
num = 0
while... |
db0c54e4a8183292139ce4b18244f48b323d58e0 | Cookieric/cs50 | /pset6/hello.py | 212 | 3.59375 | 4 | import cs50
f=cs50.get_float()
c=(5/9)*(f-32)
print("{:.5f}".format(c))
char=cs50.get_char()
if char == "Y" or char=="y":
print("Yes")
elif char == "N" or char=="n":
print("No")
else:
print("error") |
f7000c9b3b965f29e8853d29555e36bbc1a408cf | szhmery/leetcode | /Backtracking/17-LetterCombination.py | 1,689 | 3.5625 | 4 | from typing import List
class Solution:
# DFS, 递归
# 时间复杂度:O(2 ^ n)
# 空间复杂度:O(n)
def letterCombinations(self, digits: str) -> List[str]:
number_mapping = [' ', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
result = []
if digits == '':
return result
... |
aacec0437d15b8f3ea5db34fe14dcb89afe5e01e | lavalio/ChamplainVRSpecialist-PythonAlgorithms | /Week3/class2/upper_letter.py | 252 | 4.1875 | 4 | name = "champlain"
#name_capital = name.upper()
name_capital = name.capitalize()
print(name_capital)
print("I am taking this course at {}".format(name_capital))
# version 2
name = "champlain"
print("V2: I am taking this course at " + name.title()) |
145745974607b80a59bea50ac0452eff9e85aca0 | vincentinttsh/ncnu-program-class-python | /1/1-1.py | 274 | 3.515625 | 4 | import cmath
import math
a = float(input())
b = float(input())
c = float(input())
if b*b-4.0*a*c < 0:
d=(-b+cmath.sqrt(b*b-4*a*c))/(2*a)
e=(-b-cmath.sqrt(b*b-4*a*c))/(2*a)
else :
d=(-b+math.sqrt(b*b-4*a*c))/(2*a)
e=(-b-math.sqrt(b*b-4*a*c))/(2*a)
print(d,e)
|
d263b3f1e930ed6773ddd0d3c28c417038f3d560 | CommitHooks/Python-Excercises | /Page77Proj.py | 441 | 4.28125 | 4 |
def collatz(number):
val = 0
if number % 2 == 0:
val = number // 2
elif number % 2 == 1:
val = 3 * number + 1
print(val)
return val
def enterInt():
print('Please enter an integer:')
try:
num = int(input())
return num
except ValueError:
p... |
2b6eb38dfe0c3dba148c6a3cf810015e1dbcd0c1 | ws2823147532/algorithm008-class01 | /Week_02/[589]N叉树的前序遍历.py | 1,625 | 3.65625 | 4 | # 给定一个 N 叉树,返回其节点值的前序遍历。
#
# 例如,给定一个 3叉树 :
#
#
#
#
#
#
#
# 返回其前序遍历: [1,3,5,6,2,4]。
#
#
#
# 说明: 递归法很简单,你可以使用迭代法完成此题吗? Related Topics 树
# leetcode submit region begin(Prohibit modification and deletion)
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
... |
4c90476603b12fcb5d68629ff4a18f704b6217cc | ugobachi/AtCoder | /BootCampforBiginners_Easy/パナソニックプログラミングコンテスト2020_B.py | 173 | 3.5 | 4 | n,m = (int(x) for x in input().split())
mul = int(n*m)
if n == 1 or m == 1:
print(1)
elif mul % 2 == 1:
print(mul // 2 + 1)
elif mul % 2 == 0:
print(mul //2) |
f297902536572945deebf8cb55e76c72ce33ad38 | graccse/program-assignments | /dictionary_practice.py | 301 | 3.765625 | 4 | groceries = {"chicken": 1.59 , "beef": 1.99, "cheese": 1.00, "milk": 2.50 }
chicken_price= groceries["chicken"]
print(chicken_price)
beef_price = groceries["beef"]
print(beef_price)
cheese_price = groceries["cheese"]
print(cheese_price)
milk_price = groceries["milk"]
print(milk_price) |
b0f0bcfb5739d46de54cbe46614e82bf5a2d13fb | Kajol7052/Updated-Stage1-Fellowship | /Basic_Programs/PowersOf2.py | 492 | 4.25 | 4 | """
* author - kajol
* date - 12/24/2020
* time - 1:24 PM
* package - com.bridgelabz.basicprograms
* Title - Print a table of the powers of 2 that are less than or equal to 2^N
"""
try:
number = int(input("Enter number: "))
#print power of 2 within given range
if number < 31:
for num... |
815634df44131b4468d3c9c5029dc9908a5e9b24 | anikpuranik/Machine-Learning | /Advanced House Prediction/exploratory_data_analysis.py | 5,014 | 4 | 4 | '''1. Exploratory Data Analysis'''
# importing libraries
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# loading dataset
DIRECTORY = '/Users/aayushpuranik/.spyder-py3/dataset/house-prices-advanced-regression-techniques'
train_data = pd.read_csv(os.path.join(DIRECTORY, 'train.csv'))
t... |
406c0dea4724248a638ae18a8feaad4aa8e4da3c | plependu/RCHI | /aggregation_scripts/HUDPointTemplate/ParentingYouth.py | 21,891 | 3.515625 | 4 | '''
My Assumptions:
1) How my code works is that the helperfunction gets every ParentGlobalID (removing any duplicates) from a parenting Youth. How I do this is from creating a set with every youth
and filter out any youth that is classified as a child status (Set 1). Create a new set (Set 2 ) of adults in order to do... |
a22bd52dd74ff4aa38685125774dc7b9fe25c3f7 | mayk93/All---Unorganized | /Old/FunnzyIntervalSorting.py | 2,144 | 3.640625 | 4 | import random
'''
This code needs bug fixing.
'''
class Interval:
def __init__(self,left,right):
self.left=left
self.right=right
def __str__(self):
return "< Start: "+str(self.left)+" End: "+str(self.right)+" >"
def Intersects(interval,otherInterval):
return interval.left <= other... |
94b8b227b5553da3eaba932a5687ef2c5aa1c76b | MiyaJ/py-study | /basic/demo_list.py | 1,326 | 4.15625 | 4 | # author : Caixiaowei-zy
# date : 2020/12/18 14:55
# 列表
# 1. 列表申明
list1 = [1, 2, 'hello', 'python', '天天', 'study', 3, 99]
list2 = list(list1)
print(list1)
print(list2)
size = len(list1)
print('list1 的大小为:', size)
list_0 = list1[0]
print('list1 索引0 的元素为:', list_0)
list1.append('小哥哥')
print(list1)
list1.appen... |
bb8daf1b6257cd6b2efca5b66c84b6011a91a4f1 | JavaRod/SP_Python220B_2019 | /students/brian_minsk/lesson10/assignment/csv_files/csv_data_duplicator.py | 1,341 | 3.578125 | 4 | import csv
import os
def read_data(csv_file_name):
""" Read each each row into a dict and return a list of all the dicts.
"""
with open(csv_file_name, newline='', encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file)
return [row for row in reader]
def get_fields(csv... |
8f1a79140e76324ed9524d62b9339810aa09c067 | JoaoErick/aula-python | /aula006.py | 1,500 | 3.828125 | 4 | # conjunto = {1, 2, 3, 4}
# print(conjunto)
#
# conjunto = {1, 2, 3, 4, 4} #Não existem elementos duplicados
# print(conjunto)
#
# conjunto = {1, 2, 3, 4, 2}
# conjunto.add(5)
# print(conjunto)
# conjunto = {1, 2, 3, 4, 2}
# conjunto.discard(2)
# print(conjunto)
# conjunto = {1, 2, 3, 4, 5}
# conjunto2 = {5, 6, 7, 8}... |
79c9a5c7ff158e257659097711e0ab7c1033d9ab | gbt1988/PythonToWork | /project/5.6.1displayInventory.py | 1,844 | 3.765625 | 4 | def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k,v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print('Total number of items + str(item_total)')#循环内,循环完打印
def addToInventory(inventory,addedItems):
count={}
for a in addedItems:
... |
67993ba0812d04ddebf78dde67a37a07821cdf76 | mtourj/Intro-Python-II | /src/player.py | 1,410 | 3.65625 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, current_room):
self.current_room = current_room
self.inventory = []
def travel(self, direction):
'''Move player in a direction toward a room.
Returns True on... |
9437f85c20151d6ef7aa0f264c882c8802822dd4 | gontse00/quant_finance | /frame/market_enviroment.py | 2,837 | 3.828125 | 4 | ### Market Enviroments
"""
Market enviroments is just a name for a collection of other data and python objects.
This abstraction simplifies a number of operations and also allows for a consistant modeling of recuring aspects.
A market enviroment consists of three dicts to store the following types of data and python o... |
8138d75dd5ed8c476fe00fdc230a17923a20e429 | lusineduryan/ACA_Python | /Basics/Homeworks/Homework_6/Exercise_4_binary exponent.py | 196 | 3.6875 | 4 | def bin_exp(x, n):
res = 1
power = 2 ** n
while power >= 2:
power = power / 2
x = x * x
return x
def bin_exp_2(x, n):
return (x ** n) ** 2
print(bin_exp(2,3)) |
dd68af568652bc274dcf99a3cc14480c686ef1f9 | daniel-reich/turbo-robot | /quMt6typruySiNSAJ_4.py | 1,498 | 4.0625 | 4 | """
An out-shuffle, also known as an out Faro shuffle or a perfect shuffle, is a
controlled method for shuffling playing cards. It is performed by splitting
the deck into two equal halves and interleaving them together perfectly, with
the condition that the top card of the deck remains in place.
Using a list to rep... |
a582ab8d81a7672b7375352a230faf846f499479 | bignamehyp/interview | /python/leetcode/BinaryTreeZigzagLevelOrderTraversal.py | 882 | 3.796875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def zigzagLevelOrder(self, root):
if root is None:
... |
745a32da9c3f8ebaf02d4ddd70655c13d1e791fe | RubyBerumen/1roISC | /POO/Sesion23.2_EjemploEncapsulamiento/src/Ejemplo_Encapsulamiento.py | 687 | 3.5 | 4 | '''
Created on 28 may. 2020
@author: Ruby
'''
class Auto:
'''clase para crear objetos de tipo auto'''
def __init__(self, marca="ND", precio=0.0):
self.marca=marca
#para simular el encapsulamiento se aade guioes bajos a los
self.__precio=precio
#getters y setter
de... |
ecc9180df7c8d4544fe7326ec28e84dab6790d21 | astraknots/ncis | /src/pattern/checker/patternChecker.py | 7,994 | 3.578125 | 4 | #!/usr/bin/python
import getopt
import logging
import sys
import re
import json
SEPARATORS = [',', '.']
REPEAT_START = ['(', '[', '*']
REPEAT_END = [')', ']', '*']
REPEAT_WORDS = {'ONCE': 1, 'TWICE': 2}
OPERATION_CNT = {'K': 1, 'P': 1, 'SM': 0, 'YO': 1, '2TOG': 1}
def get_rep_end_for_start(rep_start_str):
if re... |
945b659e16d8f4d6a073e61a9a8178325f8d5349 | 4ndrewJ/CP1404_Practicals | /prac_05/hex_colours.py | 685 | 4.15625 | 4 | """
CP1404/CP5632 Practical
Hex codes for colours in a dictionary
"""
COLOUR_NAME_TO_HEX = {'aliceblue': '#f0f8ff', 'blueviolet': '#8a2be2', 'cadetblue': '#5f9ea0',
'chocolate': '#d2691e', 'coral': '#ff7f50', 'darkgreen': '#006400',
'darkorange': '#ff8c00', 'darkorchid': '#9... |
9b6d55c3cb3b0735dfdfbf109d57f8be65b0f3db | gagangaur/guvi | /player/set6/8.py | 200 | 3.625 | 4 | def countOccurance(s,k):
print(s)
count = 0
for i in s:
if i==k:
count+=1
return count
sentense = input()
word = input()
print(countOccurance(sentense,word))
#abcc |
e0b00d123c2e52493347796fc0c383c2b01f61ed | ArtemDavletov/EPAM_python_course | /homework2/hw4.py | 669 | 3.9375 | 4 | """
Write a function that accepts another function as an argument. Then it
should return such a function, so the every call to initial one
should be cached.
def func(a, b):
return (a ** b) ** 2
cache_func = cache(func)
some = 100, 200
val_1 = cache_func(*some)
val_2 = cache_func(*some)
assert val_1 is val_2
... |
54dc370daa23f09a1701bba42c337e2c830ed796 | AnoopKumarJangir/Python_Course | /Day 1/heartrate_cal.py | 438 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 7 22:41:36 2019
@author: Anoop K. Jangir
"""
#Assume my age 21
my_age = 21
print (my_age)
#Calculate maximum heart rate
max_hr = 220 - my_age
print (max_hr)
#calculate target heart rate
low_hr = max_hr * 0.70
print (low_hr)
high_hr = max_hr * 0.85
print (high_hr)
#ca... |
080a7e6d3dc586c298a91effe3a34ecdfde98f96 | signalwolf/Algorithm | /sort/merge_sort.py | 3,153 | 3.765625 | 4 | # coding=utf-8
from random import randint
def quick_sort(array, start, end):
def partition():
base = array[start]
left, right = start + 1, end
while left <= right:
while left <= right and array[left] <= base:
left += 1
while right >= left and array... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.