blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
56ba48cf0244dd48af12d3d2c0d12f88b522ed89 | nrshrivatsan/vatsanspiral | /go/primes.py | 695 | 3.546875 | 4 | #Thanks to http://users.softlab.ece.ntua.gr/~ttsiod/primes.html
import math
import itertools
#Thanks to http://users.softlab.ece.ntua.gr/~ttsiod/primes.html
#Generates Primes
def _primes():
yield 2
primesSoFar = [2]
for candidate in itertools.count(3, 2):
for prime in (i for i in primesSoFar if i <... |
eeedc1b6f423c40eeea03cf26eb19a36393ca24e | pavitrawalia/CodeChef_Solutions | /https:/www.codechef.com/problems/TWOSTR.py | 286 | 3.59375 | 4 | # cook your dish here
t=int(input())
for tc in range(t):
str1=input()
str2=input()
count=0
for i in range(len(str1)):
if str1[i]!=str2[i] and str1[i]!="?" and str2[i]!="?":
count+=1
if count==0:
print("Yes")
else:
print("No")
|
6cefb06721eeb73b5ef54882e6a083360072d7c1 | tylerkf/hashcode18 | /simulation.py | 2,911 | 3.5 | 4 |
class Simulator:
# Problem Parameters
R = 0 # Number of rows in Grid
C = 0 # Number of columns in Grid
F = 0 # Number of vehicles in fleet
N = 0 # Number of rides
B = 0 # Per ride bonus for starting the ride on time
T = 0 # Number of steps in simulation
# Array storing rides
rides ... |
977cebe39d0ccdbddedf445b49df79410e1ce2e5 | daniel-reich/ubiquitous-fiesta | /fJaZYmdovhzHa7ri3_24.py | 174 | 3.859375 | 4 |
def max_collatz(num):
results = [num]
while num != 1:
if num % 2:
num = (num * 3) + 1
else:
num /= 2
results.append(num)
return max(results)
|
108f13080d0ff9a0666f1ece1d6b32de0de96fb6 | shillerben/EncryptedText | /send_text_by_email.py | 979 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on Jul 10, 2012
Send text message via email
@author: user352472
'''
from smtplib import SMTP_SSL as SMTP
from email.mime.text import MIMEText
def send_text(text, phone, smtp, email, password):
numFail = 0
msg = MIMEText(text, 'plain')
me = phone
... |
a3657a79f8ddf4af25725878a661439f2a2e0dd2 | Tubomi/python3 | /廖雪峰python教程习题.py | 2,535 | 3.6875 | 4 | #yield 知识点
def fib(max):
n,a,b=0,0,1
while n <max:
yield b
a,b=b,a+b
n=n+1
for i in fib(6):
print(i)
#map 练习
def normal(n):
return n.capitalize()
list(map(tiger,['adam','LISA','barT']))#没明白为什么map需要加list才显示,reduce不用)
#reduce
from functools import reduce
def multip(... |
ecf85c1268905e465c630c7051dd5ee3ed82f4e4 | perrutbruno/change-aws-instancetype | /removequebra.py | 254 | 3.515625 | 4 | # Open the file with read only permit
f = open('lista.txt', "r")
# use readlines to read all lines in the file
# The variable "lines" is a list containing all lines in the file
lines = f.readlines()
# close the file after reading the lines.
f.close()
|
cd7bf209adac2eabc09dc10e0325844758008719 | marimatos/curso-em-video | /tuplas/maior_menor_em tupla.py | 433 | 4.21875 | 4 | ''' Programa que gere 5 numeros aleatórios e coloque em uma tupla
Depois, mostre a listagem de numeros gerados e tbm indique o menor e maior valor que estão na tupla'''
from random import randint
numeros = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10))
print(f'Os números sorteado... |
89c6b08d39402907c4964318076843927f2ff4f6 | ytatus94/Leetcode | /lintcode/lintcode_0515_Paint_House.py | 3,308 | 3.625 | 4 | # 序列型 DP, 最值型 DP
# 轉移方程:
# f[i][0] = min( f[i-1][1]+cost[i-1][0], f[i-1][2]+cost[i-1][0] )
# f[i][0] = 油漆前 i 棟房子,最後一棟房子 (i-1) 顏色是 0 的最小花費
# 房子的編號是從 0 開始,所以油漆前 i 棟房子,那最後一棟房子的編號是 i-1
# f[i-1][1] = 油漆前 i-1 棟房子,最後一棟房子 (i-2) 顏色是 1 的最小花費
# cost[i-1][0] = 當前房子 i-1 漆成顏色 0 的費用
# 需要把各種顏色分開討論
# 初始條件:
# f[0][0] = f[0... |
73cd43f3c2091d1eec866e77778f3568bf2ee00b | kamalvhm/PySparkBasics | /venv/pySpark/Concepts/DateTime.py | 3,254 | 3.828125 | 4 | from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.functions import col
# Create SparkSession
spark = SparkSession.builder \
.appName('DateTime') \
.getOrCreate()
data=[["1","2020-02-01"],["2","2019-03-01"],["3","2021-03-01"]]
df=spark.createDataFrame(data... |
99954e55b1e28b688c0e0254a134fbe12d878883 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_75/64.py | 2,424 | 3.96875 | 4 | #!/usr/bin/env python3
"""Google Code Jam Submission
Problem: 2011 Qualification Round B
Author: Matt Giuca
"""
import sys
import collections
def parse_input(infile):
"""Consume input for a single case from infile.
Return (combiners, destructors, invocation), where:
- combiners is a dict mapping two-e... |
6c60746c3f399ffb87e60c10a6bea0ddff484343 | joserequenaidv/my-eoi | /pysp/11-videogames/arkanoid/igame.py | 1,456 | 3.546875 | 4 | import pygame
from settings import *
class Game:
# __INIT__
def __init__(self):
pygame.init()
pygame.display.set_caption(GAME_TITLE)
self.screen = pygame.display.set_mode([WIDTH, HEIGHT])
self.clock = pygame.time.Clock()
# START GAME
def start_game(self):
self.a... |
a5c139bdb82bf4080299f9d8e9a89469cd2cacf7 | Vaibhav3M/Coding-challenges | /SortingAlgos/InsertionSort.py | 473 | 4.03125 | 4 | class InsertionSort(object):
def sort(self, arr):
for firstUnsortedIndex in range(1, len(arr)):
currElement = arr[firstUnsortedIndex]
i = firstUnsortedIndex
while (i > 0 and arr[i-1] > currElement):
arr[i] = arr[i-1]
i-=1
... |
031c44d38cd34a12c0ea0d442b04dd0a1aba5531 | subashhumagain/testgithub | /class.py | 1,550 | 3.53125 | 4 | class Employee:
raise_amount=1.04
def __init__(self, first, last, pay):
self.first= first
self.last = last
self.pay = pay
self.email = first+ '.'+ last+ '@company'
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
... |
f3cc5d754dbbbf84801dbf5979253b32d3b1a660 | RombosK/GB_1824 | /Kopanev_Roman_DZ_9/dz_9_2.py | 1,267 | 4.3125 | 4 | # Реализовать класс Road (дорога).
# определить атрибуты: length (длина), width (ширина);
# значения атрибутов должны передаваться при создании экземпляра класса;
# атрибуты сделать защищёнными;
# определить метод расчёта массы асфальта, необходимого для покрытия всей дороги;
# использовать формулу: длина * ширина * ма... |
b9fe5932a2cbf8bdc21a088ab4c5ee1590e7102e | brinel/AdventOfCode | /day1/day1_2.py | 471 | 3.59375 | 4 | import csv
# Original code to calculate fuel needed for just the modules
def fuel_calc(input):
x = open(input)
input = csv.reader(x)
totalFuel = 0
for mass in input:
fuel = 0
modMass = int(mass[0])
while modMass > 8:
fuel = fuel + (modMass // 3 - 2)
modMass = (modMass // 3 - 2)
... |
8da31fc6f1905447b54e91f3672ffa0515c4cfad | TaurusOlson/Infiniworld | /src/config.py | 4,766 | 3.71875 | 4 | #!/usr/bin/python
"""Key bindings configuration"""
# For now this 'configuration manager' only deals with keys defined by the
# user.
import pygame
def read_config(fname):
"""Read the configuration file and return a dictionary.
Parameters:
`fname`: the name of the configuration file
Returns:
... |
13008e21be4368f4ed3b327777cf70e187eb4a83 | pkss123/python2 | /print_ex01.py | 1,000 | 3.765625 | 4 | # 파이썬의 표준 출력함수는 print()이며
# 괄호 안에 출력하고 싶은 변수, 상수, 수식 등을 적습니다
# value = 1234;
#코드 실행 단축키는 Ctrl + F11 입니다
# print("value")
# print(value * 2)
# print("3+4")
#
# 4 * 5 #print()로 감싸지 않으면 계산을 하지만 결과를 출력하지않음
# 변수와 문자열을 함께 출력하려면 + 기호로 연결하면됩니다
#혹은 ,로 나열해도 됩니다
# a="10"
# print("a에 저장된 값은" + a + "입니다")
# p... |
82b7f26d03d77f4eb2e54a00ffbda2bbbdc76e1b | benbendaisy/CommunicationCodes | /python_module/examples/248_Strobogrammatic_Number_III.py | 3,101 | 3.515625 | 4 | from typing import List
class Solution:
def compareTwoStrs(self, str1: str, str2: str):
return int(str1) >= int(str2)
def strobogrammaticInRange(self, low: str, high: str) -> int:
n1, n2 = len(low), len(high)
res = []
oddArray = ["0", "1", "8"]
evenArray = [""]
... |
f6d6e2eaafb2d5428134063134c1f9b095b28e41 | hhlp/Number-Systems | /Main.py | 5,203 | 3.65625 | 4 | import os
import sys
import time
import keyboard
from BinaryToDecimal import BinaryToDecimal
from DecimalToBinary import DecimalToBinary
from DecimalToHex import DecimalToHex
from HexToDecimal import HexToDecimal
base_menu = str("""
[ Number System Converter ]
[0] Exit
[1] Binary
[2] Hexadecimal
""")
def base_s... |
5d756474142bc98db0106d40e9228a7b26572062 | takat0m0/MIP_formalism_examples | /lot_sizing/other_formalism/demands.py | 493 | 3.640625 | 4 | # -*- coding:utf-8 -*-
import os
import sys
import numpy as np
from days import Days
MAX_DEMAND = 30
class Demands(object):
def __init__(self, days):
self.__data = [0 for _ in days.get_all_days_list()]
for day in days.get_target_days_list():
self.__data[day] = np.random.randint(0, M... |
a59ae8c6d2c7e7ea826fcde5d075f938147300a9 | shen-huang/selfteaching-python-camp | /19100201/wiltonwung/d3_exercise_calculator.py | 1,354 | 4.09375 | 4 | #自学训练营第一个程序,献给非常喜欢计算器的王有梧。
#1.定义四则运算
def plus(a ,b): #定义加法
return a + b #输出结果
def minus(a , b): #定义减法
return a - b #得出结果
def by(a ,b ):#定义乘法
return a*b
def div(a ,b):#定义除法
return a/b
#2.给出运算选项
print("可进行的运算行:")
print("1.加")
print("2.减")
print("3.乘")
print("4.除")
#给出四则运算选项
choice = input("请选择要进行的运算(1... |
0d5679e034771d07a4787cddc863de0974810746 | behrouzmadahian/python | /python-Interview/12-graphs/9-find-kCores.py | 3,542 | 3.59375 | 4 | '''
Given an Undirected graph G and an integer K, K-cores of the graph are connected components that are
left after all vertices of degree less than k have been removed.
The standard algorithm to find a k-core graph is to remove all the vertices that have degree less than- ‘K’
from the input graph. We must be caref... |
dc1c538124a113ff4941972b0b0d9416beba2d6a | IP-Algorithmics/Udacity | /Course/Data structures and algorithms/3.Basic algorithm/1.Basic algorithms/6.trie_introduction.py | 7,422 | 4.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Trie
# You've learned about Trees and Binary Search Trees. In this notebook, you'll learn about a new type of Tree called Trie. Before we dive into the details, let's talk about the kind of problem Trie can help with.
#
# Let's say you want to build software that provides spe... |
2c59840ac0e1da14d058442465933b46e93bc5b2 | HelenaJanda/pyladies-7 | /soubory/domaci-ukoly/08_kostky.py | 1,612 | 3.75 | 4 | # -*- coding: UTF-8 -*-
# Napiš program, který simuluje tuto hru:
# První hráč hází kostkou (t.j. vybírají se náhodná čísla od 1 do 6), dokud nepadne šestka. Potom hází další hráč,
# dokud nepadne šestka i jemu. Potom hází hráč třetí, a nakonec čtvrtý. Vyhrává ten, kdo na hození šestky
# potřeboval nejvíc hodů. (V příp... |
2678d6dbf56499f48d5780852a40446057c43457 | SamuelNarciso/Analizador_Sintactico | /AnalizadorSintactico/Logic.py | 7,473 | 3.828125 | 4 | import Search
import alphabet
class Logic:
def CheckSintax(self, string, var, errores):
if self.SintaxLogic(string):
simbol = self.CheckTypes(string)
# now we have de simbol and split the string
aux = string.split(simbol)
# search the vars
result,... |
1464c22dd956d5b0960710759981df37cb2e073a | zjxpirate/Daily-Upload-Python | /Linked_Lists/Linked_Lists_singly_linked_list_basic_1.py | 3,243 | 4 | 4 |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def listLength(self):
currentNode = self.head
length = 0
while currentNode is not None:
length += 1
... |
89b65bd9103b6465e5f70b3cfeb4a4f444de6cb1 | AmRiyaz-py/Python-Arsenal | /All about Looping in python/problem2A3CO.py | 185 | 4.46875 | 4 | '''
Program :- print the half pyramid of A using for loop
Author :- AmRiyaz
Last Modified :- April 2021
'''
n = 5
a = ""
for i in range(1,n+1):
a = a + "A"
print(a) |
fdc28b2b0f7060a57015043997de6fcc4d3403c4 | lholliger/ShiftPass | /shiftpass.py | 2,867 | 3.734375 | 4 | import string
import sys
current_arg_pos = 0
import binascii
current_version = "01" # THIS CHANGES WITH EVERY ENCODING UPDATE TO PREVENT ERRORS
askpass = True
askstr = True
asktype = True
force = False
for x in sys.argv:
if (x == "-e" or x == "--encrypt"):
fc = "-e"
asktype = False;
if (x == "... |
80d043074d8f403a1b2c27682accd8d58eb416ad | agnesliszka/Python-for-Web---infoShare-Academy | /my_own_projects/theday06/3.allegro_parsel_css_&_xpath/beautiful_soup_example.py | 1,047 | 3.609375 | 4 |
import os
import requests
from bs4 import BeautifulSoup
# Function to get page from url if file does not exist, if file exists open the file
def get_page(url, filename):
if os.path.isfile(filename):
with open(filename, 'r', encoding='utf-8') as input_data:
content = input_data.read()
else... |
50bba9bc900810afef9f531c664bb52f93cb7192 | roguishmountain/dailyprogrammer | /miniChallenge24Ramp.py | 517 | 4 | 4 | __author__ = 'srs'
'''
Ramp Numbers - A ramp number is a number whose digits from left to right either only rise or stay the same. 1234 is a ramp number as is 1124. 1032 is not.
Given: A positive integer, n.
Output: The number of ramp numbers less than n.
'''
import sys
n = sys.argv[1]
def ramp(n):
count = 0
... |
ecc5ae4c24b61bcc5084932639b6ca6129e3559d | dlwnstjd/python | /pythonex/0811/conprehensionex1.py | 859 | 4 | 4 | '''
Created on 2020. 8. 11.
@author: GDJ24
컴프리헨션 예제
패턴이 있는 list, dictionary, set을 간편하게 작성할 수 있는 기능
'''
numbers = []
for n in range(1,11):
numbers.append(n)
print(numbers)
#컴프리헨션 표현
print([x for x in range(1,11)])
clist = [x for x in range(1,11)]
print(clist)
#1~10까지의 짝수 리스트 생성
evenlist = []
for n in range(1,... |
51da6a0b75d83fd09872fb423cca06f7a7b4ceb3 | Stanford-ILIAD/Learn-Imperfect-Varying-Dynamics | /imperfect_envs/driving/agents.py | 1,986 | 3.546875 | 4 | from driving.entities import RectangleEntity, CircleEntity
from driving.geometry import Point
# For colors, we use tkinter colors. See http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter
class Car(RectangleEntity):
def __init__(
self,
center: Point,
heading: float,
... |
aeb8036f667b8d579939bc394da2545c727b32f2 | anton-dovnar/LeetCode | /String/Easy/657.py | 453 | 3.703125 | 4 | """
Robot Return to Origin
"""
class Solution:
def judgeCircle(self, moves: str) -> bool:
x_axis = 0
y_axis = 0
table_moves = {
"U": 1,
"D": -1,
"L": -1,
"R": 1
}
for move in moves:
if move in "LR":
... |
eb5a2e547e9a993dd5e7452bf8fc42791323ff72 | djreiss/pynkey | /plot.py | 7,900 | 3.609375 | 4 | import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
print 'importing plot'
import globals
import params
def setup_text_plots(fontsize=8, usetex=True):
"""
This function adjusts matplotlib settings so that all figures in the
textbook have a uniform format and look.
"""
impo... |
21303aaa45fe0d86146faad076187e4bc5429222 | bmontambault/LDA | /models.py | 8,177 | 3.53125 | 4 | import numpy as np
"""
This file defines the Model class, which defines utilities for evaluating error
rate and generating learning curves, and class for Bayesian logistic regression
"""
class Model(object):
"""
Parent class for models. Defines evaluation utilities
"""
def test(self, X, y, add_di... |
9c7672eedc378ed61d7c9c7cf0add503c7c36cfa | DanielPascualSenties/pythonw3 | /w3resource/Pandas/DataSeries/DataSeries08.py | 276 | 3.859375 | 4 | import pandas
s = {'Name': ['Dani', 'Juancho', 'Carol'], 'Age': [30, 33, 31],
'Position': ['Data Engineer', 'DevOps', 'Data Analyst']}
print(s)
df = pandas.DataFrame(s)
print(df)
gender = ['M','M', 'F']
df['Gender'] = gender
print(df)
names = df['Name']
print(names) |
ad479feeec683f4791da3daa54f1aefbfc850e96 | yash2708/Text-Summarization-ML | /Text_Summarization_final.py | 3,720 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 11:12:21 2020
@author: yashj
"""
#TEXT SUMMARIZATION
#!pip install beautifulsoup4
#Needed to extract the data from website which is in html and xml format
#!pip install lxml
#Fetching article from wikipedia
#Import Libraries
#
import bs4 as bs #beautif... |
609aced9aa165cf110e6cc9236986443404be1e8 | yuyanf/skolePython | /utskriftsfunksjon.py | 710 | 3.5 | 4 | #Programmet skal stille samme spørsmål 3 ganger og skriver ut det brukere har svart til terminalen
def utskrift(): #først lager jeg en vanlig input-funksjon kode og gir kode navn som utskrift. siden det brukere skriver inn er tekst, så jeg kan bare legger til utropstegn og punktum ved slutten av input
navn = inpu... |
c137216419d3cce08061f01962a5177319f33bf9 | lsh971108/myedu-1904 | /day03/for_demo.py | 824 | 3.96875 | 4 | def for_demo():
for dome in range(6,10):
print('3.1415926')
print(dome)
def for_demo1():
for dome in range(6,10,1):
print(dome)
def for_demo1():
for dome in range(100,10,-10):
print(dome)
def for_list():
x =[1,2,3,4,5,6,7,8,9]
# for p in x:
# print(p)
... |
00effa8cc2b727cf77bad51ead0712c61306a468 | jb3/aoc-2019 | /day-1/python/main.py | 626 | 3.9375 | 4 | """Solution for AoC 2019 day 1."""
part1_fuel = 0
part2_fuel = 0
def calculate_fuel(mass: int) -> int:
"""Calculate required fuel given mass."""
mass //= 3
mass -= 2
return mass
with open("../input") as f:
for mass in f:
fuel = calculate_fuel(int(mass))
part1_fuel += fuel
... |
c9e0bcb997df6f9d09f70238db49315d010ae7c9 | karbekk/Python_Data_Structures | /Interview/Python_Excercises/Generators/Generator_Object.py | 697 | 4.1875 | 4 | # Generator object can be used only once. SO no reuse
# If called again its not gonna return anything, it has been already exhausted. Note
# it doesnt throw any exception
# If next method is called on generator object that has no value, stopiteration expection will
# be raised
# we can create new generator object to y... |
2852c66ab269d3b2513efedb6cf8dabf403145f5 | PriceHardman/ProjectEuler | /16_power_digit_sum/problem_16.py | 585 | 3.8125 | 4 | # Problem 16: Power Digit Sum
# 2^15 = 32768, and the sum of its digits is 3+2+7+6+8=26
# What is the sum of the digits of 2^1000?
################################################################################
def digits_of_power(base,power):
digits = [1]
while power > 0:
carry,keep = 0,0
... |
381eac5d581c5392e467024ab13f1e4f3a2b6723 | Gaming32/Python-AlgoAnim | /algoanim/sorts/insertion.py | 413 | 3.578125 | 4 | from algoanim.array import Array
from algoanim.sort import Sort
class InsertionSort(Sort):
name = 'Insertion Sort'
def run(self, array: Array) -> None:
for i in range(1, len(array)):
v = array[i]
j = i - 1
while j > -1 and array[j] > v:
array[j + 1]... |
94ff2cce5f161f45c8f7698ca0cfe744eb8155ec | pqrst/MachineLearningPractice | /Part 1 - Data Preprocessing/dataProcessing.py | 2,270 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np #any math
import matplotlib.pyplot as plt
import pandas as pd
# variable explorer
dataset = pd.read_csv('C:\c\Rawls\online_courses\Machine Learning A-Z Template Folder\Part 1 - Data Preprocessing\Data.csv')
... |
04af8752884223d06051e78229247c39550aeb8d | Soulor0725/PycharmProjects | /python3/南京大学/第二周/lazying_example.py | 115 | 3.75 | 4 | # 列表解析
list1 = [i for i in range(10)]
print(list1)
list2 = [i+1 for i in range(10) if i%2==0]
print(list2) |
0e2855ec17e80856b11d94b24cde6b9962807ed2 | codewithmojo/social_spider | /spider.py | 1,192 | 3.59375 | 4 | import requests
import json
def read_username():
username = input("Please insert the username that you want to search: ")
if username is None or len(username) == 0:
print("The username can't be blank")
read_username()
else:
return username
def read_json(filename):
with open(fi... |
f0367f3df4f0d2a04fe1c8f7a4f75673628378ba | fffk3045167/desktop_WSL | /python/binarySearch.py | 807 | 3.703125 | 4 | # 二分搜索是一种在有序数组中查找某一特定元素的搜索算法。
# 返回x在arr中的索引,如果不存在返回-1
def binarySearch(arr, l, arrlen, x):
if arrlen >= l:
mid = int(l + (arrlen - l) / 2)
# 元素正好在中间位置
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
... |
53bc7e154c68665b590468dd9a78b2bc31d024b0 | ckidckidckid/leetcode | /LeetCodeSolutions/739.daily-temperatures.python3.py | 1,214 | 4 | 4 | #
# [739] Daily Temperatures
#
# https://leetcode.com/problems/daily-temperatures/description/
#
# algorithms
# Medium (52.96%)
# Total Accepted: 15K
# Total Submissions: 28.3K
# Testcase Example: '[73,74,75,71,69,72,76,73]'
#
#
# Given a list of daily temperatures, produce a list that, for each day in the
# input,... |
c7f69ed355eee737c19b6baabf2f32a1c1d6eae6 | GCatSword/m02_boot_0 | /funciones1nivel.py | 411 | 3.65625 | 4 | def normal(x):
return x
def cuadrado(y):
return y * y
def cubo(x):
return x**3
#Admite funciones como parametros de entrada
def sumaTodos(limitTo, f):
resultado = 0
for i in range(limitTo +1):
resultado += f(i)
return resultado
if __name__ == '__main__':
print(su... |
9bbb2c57d5042a7f24b718416d11aea47f038053 | driverevil/serpento | /hello_2/hello.py | 169 | 3.734375 | 4 | import sys
if len(sys.argv) > 1:
name = sys.argv[1]
else:
name = input("Bonvolu diru min vian nomo")
if name == '': name = 'Gogeta tiam'
print("Saluton", name)
|
4bc36dc3bc080922ccc14fc4b174976e41a6055d | snaveen1856/Python_Revised_notes | /Core_python/_09_Data_Structures/_03_Sets/_00_Set_methods.py | 1,542 | 4.0625 | 4 | """
Python has a set of built-in methods that you can use on sets.
Method Description
------------------------------------------------------------------------------------------------------------
1.add()=================> Adds an element to the set
2.clear()===============> Removes all the eleme... |
62d7634f8e687ad03074cdf464359e8de9e63258 | jaegyeongkim/Today-I-Learn | /알고리즘 문제풀이/프로그래머스/Level 2/124 나라의 숫자.py | 236 | 3.5625 | 4 | def solution(n):
answer = ''
while n > 0:
rest = n%3
n = n//3
if rest == 0:
n -= 1
rest = 4
print(rest)
answer = str(rest) + answer
return answer
|
a88487d219b819247cce6f701b48ff4640d5a5c7 | Williamcassimiro/Programas_Basicos_Para_Logica | /Desafio 50.py | 220 | 3.828125 | 4 | soma = 0
cont = 0
for c in range(1 , 7):
num = int(input("Informe uma numero:"))
if num % 2 == 0:
soma = soma + num
cont = cont + 1
print("Voce informou só {} numero pares, Soma {}".format(cont, soma)) |
44f24d749e07871cf8730bb58e12241b31d25667 | joomab/python-basics | /adivina_el_numero.py | 455 | 3.9375 | 4 | import random
def run():
random_number = random.randint(1,100)
number = int(input("Elige un número del 1 al 100: "))
while number != random_number:
if number < random_number:
print("Pon un número más grande")
else:
print("Es un número más pequeño")
... |
056095b8933c21e0523e044b422d5f98ba2febb2 | aserran/Python-Game-Portfolio | /Python Othello/OthelloLogic.py | 11,609 | 4.21875 | 4 | # Othello Logic and Console Interface
class Game:
""" An Othello game.
"""
color_dict = {'black': 'B', 'white': 'W', 'none': ' '}
def __init__(self, rows: int=8, cols: int=8, win_option: str='most',
starting_player: str='black', corner_color: str='white'):
self.... |
a4193b6dfb6f55d8b1142fc442fd84a9191ab182 | Kavinelavu/codekata | /alphabet1.py | 115 | 3.96875 | 4 | de=raw_input()
if(de>=('a' and de<='Z') or (de>='A' and de<='Z')):
print("Alphabet")
else:
print("No")
|
c3a179979429225c5721c69c03afaa02bce75130 | mturke/StringCalculator | /StringCalculatorTest.py | 1,480 | 3.609375 | 4 | ##### Test
import unittest
from StringCalculator import StringCalculator
class Test_StringCalculator(unittest.TestCase):
def testAdd_EmptyString_Returns0(self):
calc = StringCalculator()
result = calc.add("")
self.assertEqual(0, result)
def testAdd_Zer... |
5aa70c9f56759ff49c692a63748b9b4e8b1440fb | Nischal47/Python_Exercise | /#21.py | 1,086 | 4.46875 | 4 | '''
Question:
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT
with a given steps. The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps.
Please write a program to compute the dista... |
bad357e547032486bc7e5b04b7b92351148a2b19 | 21milushcalvin/grades | /Grades.py | 1,649 | 4.25 | 4 | #--By Calvin Milush, Tyler Milush
#--12 December, 2018
#--This program determines a test's letter grade, given a percentage score.
#--Calvin Milush
#-Initializes variables:
score = 0
scoreList = []
counter = 0
total = 0
#--Calvin Milush
#-Looped input for test scores:
while (score != -1):
score = in... |
ae854aed8339a36f06c151b68a9965f54134439e | ngladkoff/2019FDI | /SimulacroAmbulancia.py | 717 | 3.671875 | 4 | def CalcularTiempo (var1,var2):
if var2 == 1:
## print("Ambulancia llega en 15m,")
return "Ambulancia llega en 15m"
elif var2 == 2:
#print("Ambulancia llega en 30m.")
return "Ambulancia llega en 30m."
elif var1 >= 59 and var2 == 3:
#print("Ambulancia llega en 2 horas.... |
813910455e4c059e5c72404204dc0a5d0adde5ee | nicholas1026/PythonStudy | /chapter08/e8-12.py | 197 | 3.5625 | 4 | def show_stuff(*stuffs):
for stuff in stuffs:
print("There are "+stuff+" in the sandwichs")
show_stuff("apple")
show_stuff("banana","orange")
show_stuff("berry","watermelon","lemon")
|
0da375dfb55ff8ba9e5f3347ca56eb0de8715ece | psukhomlyn/HillelEducation-Python | /Lesson3/HW-3-4.py | 781 | 3.84375 | 4 | """
Task 4
"""
first_value_str: str = input('Input first value: ')
second_value_str: str = input('Input second value: ')
my_list: list = []
try:
first_value_int: int = int(first_value_str)
second_value_int: int = int(second_value_str)
except ValueError as ex:
print(f'Both values should be a digits')
... |
22c8aed1804b9605a8e9a724e60dab541622c9dd | jithendaraa/RoboTutor-Analysis | /helper.py | 8,153 | 3.859375 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
import os
def remove_spaces(elements):
"""
Given
A list elements = ["Orienting to Print", "Listening Comprehension"]
Returns
elements = ["OrientingtoPrint", "ListeningComprehension"]
"""
for i in range(l... |
eea2a0419976deca35211da9d35c9178d66ee01a | 19sblanco/cs1-projects | /blanco-steven-assn15/assn15-task1.py | 278 | 3.78125 | 4 | def main():
baseList = list(range(1, 101))
list1 = [x for x in baseList if x % 2 == 0]
print(list1)
list2 = [x for x in baseList if x % 3 == 0 and x < 50]
print(list2)
list3 = [x * 10 for x in baseList if x % 5 == 0 and x > 50]
print(list3)
main()
|
d6ee95d6fd19549bb499042714d5225c9bc2d5cf | randaghaith/Python-Course | /Week 1/practise1-a.py | 484 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
name=input("enter your name = ")
x=float(input("enter the first number : "))
y=float(input("enter the second number : "))
print(f"hi mr/mrs , {name}" )
print(f"the sum of {x} and {y} is : {x+y} ")
print(f"the sub of {x} and {y} is : {x-y} ")
print(f"the mul of {x} and {... |
aa3b3b8513736803577a3c47d4635386cd48e51a | kaiopomini/PythonExercisesCursoEmVideo | /ex066.py | 555 | 4.03125 | 4 | '''Exercício Python 066: Crie um programa que leia números inteiros pelo teclado. O programa só vai parar quando o
usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a
soma entre elas (desconsiderando o flag).'''
contador = soma = 0
while True:
... |
998d6989b04880e01448158c998e6702f9809910 | bglynch/code_scratchpad | /python/general/regex/regex.py | 7,152 | 3.96875 | 4 | import re
# will be searching this multiline string
text_to_search = '''
abcdefghijklmnopqurtuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1234567890
Ha HaHa
MetaCharacters (Need to be escaped):
. ^ $ * + ? { } [ ] \ | ( )
coreyms.com
321-555-4321
123.555.1234
123*555*1234
800-555-1234
900-555-1234
Mr. Schafer
Mr Smith
Ms Dav... |
262e86fc8156eed6e203e20d3352e5b3950dee29 | erin-koen/Data-Structures | /classNotes.py | 4,410 | 4.28125 | 4 | # linked lists
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
... |
abcbaeee18f81efea2309abb4d6615a795e7b36b | AlexanderIvanofff/Python-OOP | /DataStructures/hash_table.py | 2,438 | 4.0625 | 4 | # Liner approach implementation of hashing
class HashTable:
"""
Hashable representation a custom dictionary implementation
where we use two private lists to achieve storing and hashing of
key-value pairs functionality
"""
def __init__(self):
self.max_capacity = 8
self.__keys =... |
611cdfaf0c866be3aaaded54d067894c4d840ce1 | EKrzych/codecool_projects_python | /Python/2018_02_05_SI/Algorithms_flowchart/erp_by_myself_hr.py | 2,035 | 3.921875 | 4 | # the question: Who is the oldest person ?
# return type: list of strings (name or names if there are two more with the same value)
def get_table():
with open ("persons.csv", "r") as f:
table = []
for line in f:
table.append(line.strip("\n").split(";"))
return table
def find_max(tab... |
fc58be5e9f980fb047220a57acca709e9001de6b | Win-Htet-Aung/kattis-solutions | /crackingRSA.py | 397 | 3.65625 | 4 | def is_prime(num):
if num > 1:
for i in range(2, int((num ** 0.5) + 1)):
if num % i == 0:
return i
break
# return True, 0
else:
return False, 2
t = int(input())
for i in range(t):
st = input()
n = int(st.split()[0])
e = int(st.split()[1])
p = is_prime(n)
# print(p, n)
q = n // p
pq = (p-1) * ... |
7c75f0d406fb326ecdd253100d72f04bb014d651 | dfidalg0/ces22python2 | /wordtools.py | 2,479 | 3.953125 | 4 | # Exercício 3
def cleanword (string):
s = ''
for char in string:
if char.isalpha():
s += char
return s
def has_dashdash (string):
return '--' in string
def extract_words (string):
s = ''
for char in string:
if char.isalpha():
s += char.lower()
... |
0a55036095f5f10473496bb67d5970d32dacb632 | 3l-d1abl0/DS-Algo | /py/oops/inner_class.py | 408 | 3.53125 | 4 | class College:
def __init__(self):
print('Outer Class Constructor')
def displayC(self):
print('College Method')
class Student:
def __init__(self):
print('Inner Class Constructor')
def displayS(self):
print('Student Method')
C = College()
C.displa... |
c1cf5e02b7633979955e42fde325a8cd278925ca | varshaammucmr/varshapython | /negative.py | 349 | 4 | 4 |
a=int(input("enter value of a:"))
b=int(input("enter value of b:"))
if(a>b):
print(a,"is negative")
elif(b>a):
print(b,"is negative")
dl211@soetcse:~/varsha$ python negative.py
enter value of a:67
enter value of b:56
(67, 'is negative')
dl211@soetcse:~/varsha$ python negative.py
enter value of a:78
enter value ... |
e4f5a3b824d6322cc45450eeee5e86701f8171bb | coolmich/py-leetcode | /solu/329. Longest Increasing Path in a Matrix.py | 1,109 | 3.53125 | 4 | class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix: return 0
dp = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
def traverse(matrix, r, c, dp):
if dp[... |
068af85eee72c080a8901afda501c608a7678cf8 | satishkr39/MyFlask | /Python_Demo/Bank_Account.py | 776 | 4 | 4 | class Bank:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def deposit(self, deposit):
print("Deposit in Account")
self.balance = self.balance + deposit
print("Balance is: {}".format(self.balance))
def withdraw(self, amount):
if a... |
7c1064cda385681135fd33e4993814938a8cd9e4 | arironman/MSU-Computer-Network-Lab | /lab-1/1.py | 449 | 3.921875 | 4 | # Objective: Implement a program that takes bit stream and input and applies even parity scheme on it.
num = int(input("Enter the Unsigned Integer: "))
binary_num = bin(num)
unsigned_binary_num = binary_num[2:]
print(unsigned_binary_num)
str_num = str(unsigned_binary_num)
no_of_one = 0
for i in str_num:
i... |
11ea93aa86d26175f468cb3e5f81c8b9600a77a2 | Jalbanese1441/Waterloo-CS-Circles-Solutions | /14 The Replacements.py | 107 | 3.578125 | 4 | def replace(list, X, Y):
while list.count(X)>0:
list.insert(list.index(X),Y)
list.remove(X)
|
0cb8649c62922c630d148518182f726e60ac7cb5 | santosalves/python-curso-em-video | /exer113.py | 953 | 3.8125 | 4 | def leiaInt(msg):
while True:
try:
num = int(input(msg))
except (ValueError, TypeError):
print('\033[0;31mERRO! Digite um número inteiro válido.\033[m')
continue
except KeyboardInterrupt:
print('\n\033[0;31mEntrada de dados interrompida pelo us... |
f9f1290d2b74c3184bc568e8586b7285638d875b | OceaneL/dypl | /week03/rockPaperScissors.py | 2,596 | 3.78125 | 4 | import random
class Result:
def __init__(self, value, name):
self.value = value
self.name = name
def __eq__(self, other):
return self.value == other.value
Result.LOSE = Result(1,"Your opponent wins!")
Result.WIN = Result(2,"You win!")
Result.TIE = Result(3,"It's a tie!")
class Weapon... |
1c023f82579284f3b95654768aad6da62f011c07 | romanazaruk/algorithms | /algo_lab_3/algo.py | 961 | 3.59375 | 4 | from collections import defaultdict
class Graph:
def __init__(self, graph):
self.graph = graph
self.visited = {} # to separate elements of graph
self.list = [] # stack for result
for i in graph.copy():
#Why i cant use .keys???
if i not in self.visited:
... |
43a2a58e017220c16ce9f57996206a66725745b5 | HanChen1988/BookExercise_02 | /Chapter_07/Page_100/greeter.py | 1,735 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/4/12 2:43 下午
# @Author : hanchen
# @File : greeter.py
# @Software: PyCharm
# ------------------ example01 ------------------
# # 准确地指出你希望用户提供什么样的信息
# name = input("Please enter your name: ")
# print("Hello, " + name + "!")
# ------------------ example01 ------------------
# pri... |
d6d264bc85fa6ef5b3cf0c5abfa93ecd6a10a867 | kyle-cryptology/crypto-algorithms | /Commitment/Commitment.py | 3,770 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
.. module:: Commitment
:synopsis: The cryptographic commitment.
.. moduleauthor:: Kyle
"""
from Essential import Groups, Utilities as utils
import abc
class Commitment(object):
"""Cryptographic Commitment"""
def __init__(self, arg):
raise NotImplementedError("DigitalSi... |
1990080a6d195acef0fb9514554f92d2c7f55274 | segunar/BIG_data_sample_code | /3. Temperatures - Good/my_python_mapreduce/my_reducer.py | 4,072 | 4.1875 | 4 | #!/usr/bin/python
# --------------------------------------------------------
# PYTHON PROGRAM
# Here is where we are going to define our set of...
# - Imports
# - Global Variables
# - Functions
# ...to achieve the functionality required.
# When executing > python 'this_file'.py in a terminal,
# the Python in... |
3b62576d4caf5fc06c02dc15dbf97ef0f5829786 | GhiffariCaesa/basic-python-b7-b | /list.py | 305 | 3.75 | 4 | mylist = []
mylist.append("a")
mylist.append(12)
mylist.append(20)
print(mylist)
print(len(mylist))
del mylist[2]
print(mylist)
# [a, 12, 20]
# [0 1 2]
mylist[2]=30 #mengedit isi list
print(mylist)
a = int(input("Masukkan data ke dalam mylist : "))
mylist.append(a)
print(mylist)
print(len(mylist)) |
6a85e3bbc4f85a829b329ca216628a840c050e65 | xingzuolin/logsitic_chi_woe_py3 | /func.py | 385 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/28 11:14
# @Author : Jun
# @File : func.py
import pandas as pd
def read_path(path, sep):
data = pd.read_csv(path, sep=sep)
return data
def convert_upper(data):
if isinstance(data,list):
data = [var.upper() for var in data]
... |
9ead11fd9f66723fadb44da4e5cd73efa6b4896b | Akshay199456/100DaysOfCode | /Topics/Topic/Data Structures and Alogrithms (Topic)/Grokking the Coding Interview/26(Merge Intervals).py | 4,947 | 3.96875 | 4 | """
Problem statement:
Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals.
Example 1:
Intervals: [[1,4], [2,5], [7,9]]
Output: [[1,5], [7,9]]
Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into
one [1,5].
sv... |
dee202f0dd33fc6f5533040f0b746ac50d1e6c05 | AndruhaGit/labs-Python | /lab 8/1.py | 2,047 | 3.859375 | 4 | # 1. Створіть клас з ім'ям student, що містить поля: прізвище та ініціали, номер групи,
# успішність (масив з п'яти елементів). Створити масив з десяти елементів такого типу,
# впорядкувати записи за зростанням середнього бала.
# Додати можливість виведення прізвищ і номерів груп студентів, які мають оцінки, рівні тіль... |
a6bcfb3641874c3f7b440ea893c37893445c1119 | BANDI-NAVEENKUMAR/palle_tech_programs | /some eg pro/b.py | 127 | 3.515625 | 4 | salary = 300
if salary > 500000:
salary = salary - (10/100*salary)
else:
salary = salary - (5/100*salary)
print(salary) |
4b624d88b8886439d2ea8a87bf96ba00703707c5 | ARundle01/brewery-tracking | /csv_prediction.py | 11,732 | 3.75 | 4 | """
This module is responsible for handling the data found within the provided CSV, to make predictions
about sales in any given month in the future. It can also sort the data by month, by recipe and
calculate figures such as percentage growth between months and the Average Annual Growth Rate.
"""
# Imports
impor... |
5073cd99bc8e8f1a1deecd262c2ade7a4466f7b7 | Drake-Firestorm/Think-Python | /code/ackermann_memo.py | 1,046 | 3.84375 | 4 | import pprint
known1 = dict()
known2 = dict()
# using nested dictionary
def ack1(m, n):
if not isinstance(m, int) or not isinstance(n, int) or m < 0 or n < 0:
print("m and n should be non-negative integers")
return None
elif m == 0:
return known1.setdefault(m, {}).setdefault(n, n+1)
... |
b7f5748bdfec01da3656e6d67994f43a07cfbdc4 | DesAbdWis/cw-python-temelleri | /notes.py | 276 | 4.1875 | 4 | notes = int(input("please enter your note : "))
if notes > 90:
if notes >= 95:
print("A+")
else:
print("A")
elif notes >= 80 and notes < 90 :
if notes >=85:
print("B+")
else :
print("B")
else :
print("Below B") |
67534f534e776a6e534eacca0f3c73b56eac765e | LayicheS/python_alg | /1189. “气球” 的最大数量.py | 624 | 3.5 | 4 | import queue
import copy
import time
class Solution:
def get_dict(self, text: str):
d = {k: 0 for k in text}
for each in text:
d[each] += 1
return d
def maxNumberOfBalloons(self, text: str) -> int:
d1 = self.get_dict(text)
d2 = self.get_dict('balloon')
... |
f3f647f27f7514aba6570bda12bc8a35e7972394 | SergiodeGrandchant/introprogramacion | /practico/ejercicio13.py | 255 | 3.671875 | 4 | # https://bit.ly/36LtifW
num = int(input("Dame los terminos a usar"))
suma = 0
for i in range(1, num + 1):
if i % 2 == 0:
signo = -1
else:
signo = 1
res = signo / (1 + 2 * (i - 1))
suma = suma + res
pi = 4 * suma
print(pi)
|
5b09debf4d04fcc7dabcecfeb836a56a7a5e8046 | LuxAter/Aetas | /test.py | 3,411 | 3.640625 | 4 | #!/usr/bin/env python3
from snake import *
import numpy as np
import time
import copy
N = 20
def user_input(position, N):
while True:
move = input()
if move == 'w':
return 0
elif move == 's':
return 1
elif move == 'd':
return 2
elif mov... |
63bfb3f7e87284dcbc1ba32f7e0cab935d66e68e | north314star/Weather-Final | /weather.py | 1,243 | 3.5 | 4 | import requests
start_over = 'true'
while start_over == 'true':
city = input('Enter a city name you want to look at:')
api_key ='dd29fda4360eb6271e53bbe6a6e445ce'
def get_weather(api_key, city):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&units=imperi... |
a6fea334dafbd4ea80330873947b7cf8068d2387 | sajithgowthaman/GA---All-Exercises- | /hw-09-inheritance-and-file-io/exercise3.py | 1,798 | 3.515625 | 4 | import csv
# Employees is a list of dictionaries.
# The keys in these dictionaries will be the header fields of your spreadsheet.
employees = [
{
'first_name': 'Bill',
'last_name': 'Lumbergh',
'job_title': 'Vice President',
'hire_date': 1985,
'performance_review': 'excellent'
},
{
'first_... |
30fbd39a29c38c7600ab041e227bbe4abe5d4f61 | shadow99chen/CF2 | /ex1.py | 967 | 3.5 | 4 | #对cars赋值
cars = 100
#对spase_in_a_car赋值
space_in_a_car = 4.0
#对drivers赋值
drivers = 30
#对pasengers赋值
pasengers = 90
#对cars_not_driven赋值
cars_not_driven = cars - drivers
#对cars_driven赋值
cars_driven = drivers
#对carpool_capacity赋值
carpool_capacity = cars_driven * space_in_a_car
#对average_passengers_per_car赋值
a... |
c6917ee6b5916a0c28e594219482d5ba392e4b6d | Mudrobot/Python-Crawler | /Requests/Xpath basic.py | 730 | 3.6875 | 4 | # Xpath是在xml文档中搜索内容的一种语言
# html是xml的一个子集
html="""
<book>
<id>1</id>
<name>野花遍地香</name>
<price>1.23</price>
<nick>臭豆腐</nick>
<author>
<nick id="10086">王者荣耀</nick>
<nick id="10010">和平精英</nick>
<nick class="game">原神</nick>
<nick class="joy">使命召唤</nick>
<div>
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.