blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
039916b7ca6174a0c119d08ee6e8848337a12c26 | abigail-hyde/flood-agh54-bjw68 | /floodsystem/geo.py | 5,853 | 3.71875 | 4 | # Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
from .utils import sorted_by_key # noqa
import plotly.express as px
import geopandas
import pandas as pd
from haversine import haversine, Unit
from .analysis import... |
10434d3fba05ecfd9cda0e34a4629511f6c9e657 | superman-wrdh/python-application | /product_and_consume/demo_4.py | 1,811 | 3.90625 | 4 | """
4、信号量模型
"""
import sys, time
import random
from threading import Thread, Semaphore
product = []
mutex = Semaphore(1)
full = Semaphore(0)
empty = Semaphore(5)
class Producer(Thread):
def __init__(self, speed):
Thread.__init__(self);
self.speed = speed;
def run(self):
while True:
... |
541b931a10c54f951a05271d70425d085634da56 | superman-wrdh/python-application | /python_thread/ConsumerProduct.py | 1,053 | 3.75 | 4 | # -*- encoding: utf-8 -*-
import threading
import queue
import random
import time
class Producter(threading.Thread):
"""生产者线程"""
def __init__(self, t_name, queue):
self.queue = queue
threading.Thread.__init__(self, name=t_name)
def run(self):
for i in range(100):
#ran... |
554629c99caf7f3c1fab124b412a16fd865b8f4b | Colaplusice/hello_fluent_python | /chapter 1/1.2.py | 830 | 4.0625 | 4 | #encoding=utf-8
from math import hypot
#设计一个向量类
#hypot 返回欧氏距离
class Vector:
def __init__(self,x,y):
self.x=x
self.y=y
pass
#求欧式距离
def __abs__(self):
return hypot(self.x,self.y)
pass
##打印对象
def __repr__(self):
return "Vector({},{})".format(self.x,self.y... |
7e0665c20c10efb75b64bc249ebd832c615de897 | Colaplusice/hello_fluent_python | /chapter7_decorator/program_time.py | 657 | 3.59375 | 4 | import time
def clock(func):
def clocked(*args):
t_1 = time.perf_counter()
# 运行实体函数
result = func(*args)
t_2 = time.perf_counter()
name = func.__name__
arg_str = ",".join(repr(arg) for arg in args)
print("spend time is {},arg is{}".format(t_2 - t_1, arg_str)... |
e919859a9e00b0da6f488fa5160e4b699a550e2a | Insight-book/data-science-from-scratch | /scratch/probability.py | 4,737 | 3.703125 | 4 | def uniform_cdf(x: float) -> float:
"""Returns the probability that a uniform random variable is <= x"""
if x < 0: return 0 # uniform random is never less than 0
elif x < 1: return x # e.g. P(X <= 0.4) = 0.4
else: return 1 # uniform random is always less than 1
import math
SQRT_TWO_PI ... |
777f8bcef8f9630c473f891529f57ad1c824c1a9 | Insight-book/data-science-from-scratch | /scratch/databases.py | 12,901 | 3.59375 | 4 | users = [[0, "Hero", 0],
[1, "Dunn", 2],
[2, "Sue", 3],
[3, "Chi", 3]]
from typing import Tuple, Sequence, List, Any, Callable, Dict, Iterator
from collections import defaultdict
# A few type aliases we'll use later
Row = Dict[str, Any] # A database row
WhereClause = ... |
5200b01aac613d06740c4654226c7a74aa960aea | Insight-book/data-science-from-scratch | /scratch/simple_linear_regression.py | 3,316 | 3.84375 | 4 | def predict(alpha: float, beta: float, x_i: float) -> float:
return beta * x_i + alpha
def error(alpha: float, beta: float, x_i: float, y_i: float) -> float:
"""
The error from predicting beta * x_i + alpha
when the actual value is y_i
"""
return predict(alpha, beta, x_i) - y_i
from scratch.li... |
52932753322af66b2837825e7012181a39bf56fe | LearnDreamCode/Python | /for_while_loop.py | 1,013 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 06:10:26 2021
@author: kalai
"""
#for loop is iretation based
# range(<start>,<stop>,<step>)
# start and step are optionnal and the default values are 0 and 1 respectively
# num_list = [0,10,200,3000,40000]
# for num in num_list:
# num *= num
# print(num)
... |
e6bbe92ecd3a9ac0966e3f9aecd907178a6b5c63 | LearnDreamCode/Python | /Find_index_a.py | 390 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 06:16:27 2021
@author: kalai
"""
magic_word = 'abracadabra'
search_str = 'a'
start_pos=0
iteration_count=len(magic_word)-len(magic_word.replace('a', '') )
for i in range(iteration_count):
start_pos=magic_word.index(search_str,start_pos)
print('a is present a... |
778ddbbe8fb9c307c2d59218d7ff01f318d79636 | LearnDreamCode/Python | /repeated_charcters.py | 793 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 06:44:20 2021
@author: kalai
"""
# Q3:
# o4 e3 u2 h2 r2 t2
# print the repeated characters in a string.
# Sample string: 'the quick brown fox jumps over the lazy dog'
# Expected output : o4 e3 u2 h2 r2 t2
input_string= 'the quick brown fox jumps over the lazy dog'... |
612d6ac158e726eafc396a65c515f048d053aa25 | LearnDreamCode/Python | /ex1_q3_2characters.py | 557 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 15:03:24 2021
@author: kalai
"""
# Q3: Write a Python program to get a string made of the first 2 and the
# last 2 chars from a given a string. If the string length is less than 2,
# return an empty string, for example, if:
# sample_string = "abcdefghij", the expecte... |
7fa64bd1facdd7be31696a26f8239536e43a93d6 | LearnDreamCode/Python | /generate_pwd.py | 2,266 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 28 06:22:48 2021
@author: kalai
"""
# Q: Generate a password of 8 characters long
# - one of them should be upper case
# - one of them should be numeric
# - one of them should be a special character
import random
# numList = [random.randint(0, 10)]
# print('int',numList... |
c4a153490c7f2e6b1d87dc01b9feace934b33d3e | deep-scribe/handwriting-recognition | /src/rc.py | 2,814 | 3.6875 | 4 |
"""
The code to generate the risk-coverage curve given the model and the test data.
It is assumed that the model is implemented using pytorch
Usage:
$ python
>>> import rc
>>> rc.draw_curve(model, input_data)
# png file saved to the current directory
"""
import numpy as np
import matplotlib.pyplot as plt
def d... |
01ce27d5d65b55566cccded488d1c99d2fd848b0 | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_019.py | 1,079 | 4.1875 | 4 | """
You are given the following information, but you may prefer to do some
research for yourself.
* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on le... |
f8b7c76ef696215141cce020ad7a7d89f702aacc | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_046.py | 1,716 | 3.921875 | 4 | """
It was proposed by Christian Goldbach that every odd composite number
can be written as the sum of a prime and twice a square.
9 = 7 + 2x1^(2)
15 = 7 + 2x2^(2)
21 = 3 + 2x3^(2)
25 = 7 + 2x3^(2)
27 = 19 + 2x2^(2)
33 = 31 + 2x1^(2)
It turns out that the conjecture was false.
What is the smallest odd composite that... |
159b7422dc21ca5c01cec91b1c27ee3a88b08ca1 | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_029a.py | 759 | 4.15625 | 4 | """
Consider all integer combinations of a^(b) for 2<=a<=5 and 2<=b<=5:
2^(2)=4, 2^(3)=8, 2^(4)=16, 2^(5)=32
3^(2)=9, 3^(3)=27, 3^(4)=81, 3^(5)=243
4^(2)=16, 4^(3)=64, 4^(4)=256, 4^(5)=1024
5^(2)=25, 5^(3)=125, 5^(4)=625, 5^(5)=3125
If they are then placed in numerical order, with any repeats removed,... |
c82c4d48f19a55298f5dce09cca394ea676114e8 | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_027.py | 2,122 | 3.703125 | 4 | """
Find the product of the coefficients, a and b, for the quadratic
expression that produces the maximum number of primes for consecutive
values of n, starting with n = 0.
n^2 + an + b,
abs(a) < 1000,
abs(b) < 1000
"""
def is_prime(n):
if n in prime_list:
return True
elif n < 0:
return False... |
4f9bf7956310ee9dd9ea90c99ce45a3534a0e2ff | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_037a.py | 2,320 | 4 | 4 | """
The number 3797 has an interesting property. Being prime itself, it is
possible to continuously remove digits from left to right, and remain
prime at each stage: 3797, 797, 97, and 7. Similarly we can work from
right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable fr... |
0858af55a19ec262d3dc7bd9d8c6b72ff28153c3 | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_028.py | 456 | 3.5625 | 4 | """
Starting with the number 1 and moving to the right in a clockwise direction
a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of both diagonals is 101.
What is the sum of both diagonals in a 1001 by 1001 spiral formed ... |
099c512c463ddfa211338eea98842567cbb5b43a | dablackwood/my_scripts_project_euler | /specific_solutions/project_euler_056.py | 472 | 3.890625 | 4 | """
Considering natural numbers of the form, a^b, where a and b < 100,
what is the maximum digital sum?
"""
import time
t1 = time.time()
def digit_sum(n):
tally = 0
for digit in str(n):
tally += int(digit)
return tally
max_sum = 0
for a in xrange(1, 100):
if a % 10 != 0:
for b in xra... |
c141565f89ce702eaa419f11c5627325475147a2 | claudiugroza/msa | /a-02/a_05.py | 456 | 3.921875 | 4 | #!/usr/bin/python
# Write a new script that takes three arguments as input.
# The program should execute sequences of LED pulses using the previous given configuration:
# the first argument is the number of pulses contained by one sequence,
# the second argument is the interval (in seconds) between two pulses in a se... |
26e8ab97f958a339586216bd10d7488a5791b2e0 | NinahMo/lock-in | /user.py | 897 | 3.78125 | 4 | class User:
user_list = []
def __init__(self,full_name,login_name,email,password_value):
'''
Here we call ana array which has the login information and what is needed for the login.
'''
self.full_name = full_name
self.login_name = login_name
self.email = email
... |
0368c583e2098cfdff1da61e00c0f7e997a42120 | shaziya21/PYTHON | /static_methods.py | 386 | 3.65625 | 4 | class student:
school = "telusko"
def __init__(self,m1,m2,m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
def avg(self):
return(self.m1 + self.m2 + self.m3)/3
@staticmethod
def info():
print('this is a student class.. in abc mmodule')
s1 = student(... |
627e26b857e77b466da042acef1737e3d0816d1e | shaziya21/PYTHON | /zip.py | 349 | 4.25 | 4 | # if we want to join two list or tuple or set or dict we'll use zip
names = ('shaz','naaz','chiku')
comps = ('apple','hp','asus')
zipped = list(zip(names,comps))
print(zipped)
# or we can use loop to iterate like
names = ('shaz','naaz','chiku')
comps = ('apple','hp','asus')
zipped = list(zip(names,comps))
for (a,... |
56645c2bf5af3de091280d873c5ccf0a45a19201 | shaziya21/PYTHON | /instance_method.py | 604 | 3.8125 | 4 | class student:
school = "telusko"
def __init__(self,m1,m2,m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
def avg(self):
return(self.m1 + self.m2 + self.m3)/3
def get_m1(self): #getter
return self.m1,self.m2,self.m3
def set_m1(self,a,b,c):
self.m1 ... |
5ce1f734f8785fd51730ec0f34e62e59c4a45a2c | shaziya21/PYTHON | /pali.py | 907 | 3.96875 | 4 | def count(lst):
even = 0
odd = 0
for i in lst:
if i%2==0:
even+=1
else:
odd+=1
return even,odd
lst=[20,25,14,19,16,24,28,47,26]
even,odd = count(lst)
print(even)
print(odd)
print(type(even))
######################################
def count(lst):
even =... |
68a88b204fc3ee4e82f5d493be81f5de27f61fb9 | shaziya21/PYTHON | /linear_search.py | 865 | 3.6875 | 4 | pos = -1
def search(list,n):
i = 0
while i < len(list):
if list[i] == n:
globals()['pos'] = i
return True
i = i + 1
return False
list = [2,3,4,5,6,7,9]
n = 2
if search(list,n):
print('found at', pos)
else:
print('not found')
# ---------------------------... |
73980da3c813213a81f11db877458ff72c0a47b7 | shaziya21/PYTHON | /constructor_in_inheritance.py | 732 | 4.1875 | 4 | class A: # Parent class / Super class
def __init__(self): # Constructor of parent class A
print("in A init")
def feature1(self):
print("feature1 is working")
def feature2(self):
print("feature2 is working")
class B(A):
def __init__(self):
super().__init__() # jum... |
6ffafcc1da316699df44275889ffab8ba957265f | shaziya21/PYTHON | /MRO.py | 1,004 | 4.4375 | 4 | class A: # Parent class / Super class
def __init__(self): # Constructor of parent class A
print("in A init")
def feature1(self):
print("feature 1-A is working")
def feature2(self):
print("feature2 is working")
class B:
def __init__(self): # Constructor of class B
... |
1e870f6429ff8f0b0cde4f40b7d0f3e148242257 | JoshiDivya/PythonExam | /Pelindrome.py | 354 | 4.3125 | 4 | def is_pelindrome(word):
word=word.lower()
word1=word
new_str=''
while len(word1)>0:
new_str=new_str+ word1[-1]
word1=word1[:-1]
print(new_str)
if (new_str== word):
return True
else:
return False
if is_pelindrome(input("Enter String >>>")):
print("yes,this is pelindrome")
else:
pri... |
dde0ef91117d5b96b9822b4be184133f84ccb59b | abalasky/algorithms | /dp/knapsack.py | 1,990 | 3.875 | 4 | """
Dynamic programming solution to 0/1 knapsack
"""
import numpy as np
def knapsack(items, weight):
"""
Maximizes value of items given a weight limit
"""
#Init DP Table x: 0->items y: 0 ->weight
opt = np.zeros((len(items)+1, weight+1), dtype = int)
#Fill out base cases i.e. first row/first ... |
6c96de768cdd8d50ee6a8e2fc2f9f1a92afb40ba | S8A/voting-simulator | /voting-simulator/result.py | 2,243 | 3.65625 | 4 | # coding=utf-8
"""Each election result records the voting system used, counts, winners, etc."""
from .utils import sort_dict_desc, make_table
class ElectionResult:
def __init__(self, voting_system, counts, winners, count_type='Votes',
percent_column=True, details=[]):
"""Creates an ele... |
08f0a1f3b617dc4ec04d2c46f0690fb75a9f9711 | RugeljGG/AdventOfCode | /2019/day1.py | 663 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 1 09:54:54 2019
@author: gape
"""
def task1():
with open('day1.txt') as file:
total = 0
for row in file:
w = int(row)
total += (w / 3) // 1 - 2
print('Task 1 result: ', total)
def task2():
with open('day1... |
2dd93300d7ede7b2fd78a925eeea3d912ae55c51 | dhaffner/pycon-africa | /example1.py | 408 | 4.53125 | 5 | # Example #1: Currying with inner functions
# Given a function, f(x, y)...
def f(x, y):
return x ** 2 + y ** 2
# ...currying constructs a new function, h(x), that takes an argument
# from X and returns a function that maps Y to Z.
#
# f(x, y) = h(x)(y)
#
def h(x):
def curried(y):
return f(x, y)
r... |
6fe75095725512cb6f19b389882d0cd32558ca4d | Joaoflavo/codigos-de-treino | /aula3 operadores logicos.py | 639 | 4.09375 | 4 | #programa de treino feito para aprender a usar operadores lógicos
#programa desenvolvido por: João Flavo J°@°2@2@ 14-10-2020 03:14 AM
print ('Escolha uma opção e descubra o que acontece')
print('Menu:\n1 = Escolha Guilherme: \n2 = Escolha João:\n3 = Escolha Maria:')
opcao = input('Escolha uma opção do menu:')
... |
76e613510e58653a02ff08a4821f357b8dfd1d22 | diptijadhav1999/Pattern | /number.py | 134 | 3.5 | 4 | #1111
#2222
#3333
#4444
n=int(input())
for i in range(1,n+1):
for j in range(1,n+1):
print(i,end="")
print() |
7447eb932ce829288aa0ce3491b07e049733d552 | liweisunny/InterviewQuestions | /4.单列模式.py | 391 | 3.640625 | 4 | #__author:liwei
#date:2017/2/23
# 使用 __new__()方法实现
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
class MyClass(Singleton):
a=1
c... |
8a70aebde7d72dfaca31b9223863e3ba14415acf | cpe202fall2018/lab0-loogyboy | /planets.py | 655 | 4 | 4 | #
#Name: Peter Moe-Lange
#Student ID: 014335967
#Date (Last Modified): September 23th
#
#Lab 0
#Section 13
#Purpose of Lab: intro/warm up to python and github
#additional comments: in this program I prompt the user for an input which then format. after this I take the input and multiply it by the constant and the print... |
dafb3e2d94649cf1f7a26a0a5930f640529ae88a | vbelousPy/py_base | /Lesson_04/fourth/main.py | 215 | 3.90625 | 4 | myList = list()
while True:
try:
n = input("Input number: ")
if len(n) == 0:
break
myList.append(float(n))
except ValueError:
print("Invalid value")
print(myList)
|
96a3983fba2043c726e287e809ed03614f7ae037 | vbelousPy/py_base | /Lesson_02/1.py | 342 | 3.984375 | 4 | import math
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
d = b ** 2 - 4 * a * c
if d < 0:
print("The result is a complex value")
else:
if d == 0:
print("x =", (-b / 2 * a))
else:
print("x1 =", (-b - math.sqrt(d)) / 2 * a)
print("x2 =", (-b + m... |
383a51887fc50cf85359feb303af2e5a8a268245 | vbelousPy/py_base | /Lesson_03/5.py | 792 | 3.6875 | 4 | length = int(input("Enter length: "))
t = int(input("Select type (1-4): "))
result = str()
if t == 1:
i = 0
while i < length:
temp = "".ljust(length - i, "*")
temp = temp.ljust(length, " ")
result += temp + "\n"
i += 1
elif t == 2:
i = length - 1
while i >= 0:
te... |
aa5cd6b20b24b8c70cb89851eb573c18ae3fed90 | vbelousPy/py_base | /Lesson_05/3.py | 277 | 3.90625 | 4 | def foo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return foo(n - 1) + foo(n - 2)
try:
print("result =", foo(int(input("Enter a number greater than zero: "))))
except (RecursionError, ValueError):
print("Incorrect value")
|
d50179cb3e7e9f91a92a310ceaa1ce4b035dadb3 | vbelousPy/py_base | /Lesson_03/3.py | 161 | 3.9375 | 4 | cortege = tuple()
while True:
text = input("Input text: ")
if len(text) == 0:
break
else:
cortege = cortege + (text,)
print(cortege)
|
f05722b55357f9116b536e2e110e1b4b35769fa4 | korymath/talk-generator | /talkgenerator/util/random_util.py | 509 | 3.78125 | 4 | import random
# From https://stackoverflow.com/questions/14992521/python-weighted-random
def weighted_random(pairs):
if len(pairs) == 0:
return None
total = sum(pair[0] for pair in pairs)
r = random.uniform(0, total)
for (weight, value) in pairs:
r -= weight
if r <= 0:
... |
22b54ee1f842906a09ce8408a788d1c8819f25a8 | javier-ls/PracticasTeoriadelaComputacion | /expresiones regulares/101.py | 201 | 3.6875 | 4 | import re
expresion = r'(1)(0)(1)'
resultado = re.compile(expresion)
prueba = raw_input("entrada: ")
busqueda = re.search(resultado,prueba)
if busqueda:
print busqueda.group()
else:
print "qr"
|
bc596e74392c23e4fb099068b6d0929ba02aa830 | Yaambs18/python-bootcamp | /Dockerfiles/Second_image/perfect_num.py | 281 | 3.703125 | 4 | def perfect_num(num):
sum = 0
for i in range(1,num):
if num%i==0:
sum+=i
if sum==num:
return f"The {num} is perfect number."
return f"The {num} is not a perfect number."
n = int(input("Enter a number :"))
print(perfect_num(n))
|
b86300067afe20ac6d3661a4d8a6b85446b57512 | Yaambs18/python-bootcamp | /Day3/Ineheritance.py | 1,251 | 4.15625 | 4 | #Multilevel Inheritance
class Base():
def __init__(self, name):
self.name = name
def getName(self):
return self.name
class Child(Base):
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age
def getAge(self):
return self.age
class GrandChild(Child):
def __init__(self, name, ag... |
da75875b647a9673efb113e14ebd237cd4e4d1fa | Yaambs18/python-bootcamp | /Day4/line_class_test.py | 560 | 3.546875 | 4 | import unittest
import line_class
class Test_Dist_slope(unittest.TestCase):
def test_distance(self):
coordinate1 = (3,2)
coordinate2 = (8,10)
obj = line_class.Line(coordinate1,coordinate2)
result = obj.distance()
self.assertEqual(result, 9.433981132056603)
def test_... |
84239ec9ebda1d612b73379e7cb439fb8f4f857c | kgarrison343/Randomizer | /Main.py | 814 | 3.75 | 4 | from RandomChoice import choose_randomly
from os import listdir
def list_files(files: list):
print("What file would you like to choose from?")
for i, file in enumerate(files):
print(str(i + 1) + ". " + file)
def main():
files = listdir("./Choices")
list_files(files)
choice = int(input())... |
a93f8e9ac02ba81adbd2b0ead5aa0a2af11d6011 | egill12/pythongrogramming | /P3_question4.py | 842 | 4.625 | 5 | '''
Write a program that asks the user for a long string containing multiple words.
Echo back to the user the same string, except with the words in backwards order.
For example, say we type the string:
My name is Michele
Then we would expect to see the string:
Michele is name My
'''
def reverse_str(string):
'''
... |
30ef3384627cae5a2c54746091e041319a9907a9 | richardcostarocha/atividades_blue | /exerciciosEntrega.py | 8,049 | 4.5 | 4 | #01 - Utilizando estruturas condicionais faça um programa que pergunte ao usuário dois números e mostre:
# A soma deles;
# A multiplicação entre eles;
# A divisão inteira deles;
# Mostre na tela qual é o maior;
# Verifique se o resultado da soma é par ou impar e mostre na tela;
# Se a multiplicação en... |
c0d14de9fc61072d34558eec22c277fa45e321ea | BjornChrisnach/Basics_of_Computing_and_Programming | /count_for_loop.py | 127 | 4.0625 | 4 | print("Please enter a positive integer: ")
input_num = int(input())
for counter in range(1, input_num + 1):
print(counter) |
97c210b42a229ca7690b464160e088b3480ae193 | BjornChrisnach/Basics_of_Computing_and_Programming | /convert_Fahr_to_Celsius.py | 398 | 4.03125 | 4 | def main():
print("Please enter the temperature in Fahrenheit: ")
temp_fahr = float(input())
temp_celsius = fahrenheit_to_celsius(temp_fahr)
print(temp_fahr, "Fahrenheit is", temp_celsius, "Celcius")
def fahrenheit_to_celsius(F):
temp_celc = (F - 32) * (5/9)
temp_celc = round(temp_celc, 3)
... |
c9fb1db790544b2d33dafa3e7e4c3f65558c695c | BjornChrisnach/Basics_of_Computing_and_Programming | /evennumbers.py | 139 | 3.984375 | 4 | print("Please enter a positive integer: ")
number_of_numbers = int(input())
for i in range(2, (number_of_numbers*2) + 1, 2):
print(i)
|
fc044bef4295e8e85313366be4a89689938756c2 | BjornChrisnach/Basics_of_Computing_and_Programming | /days_traveled.py | 233 | 4.125 | 4 | print("Please enter the number of days you traveled")
days_traveled = int(input())
full_weeks = days_traveled // 7
remaining_days = days_traveled % 7
print(days_traveled, "days are", full_weeks, "weeks and",\
remaining_days,"days") |
f5740230d40654e8af5c0c75b2cc77eaeb470a89 | BjornChrisnach/Basics_of_Computing_and_Programming | /str_count_number_words_ex3.py | 267 | 4.09375 | 4 | print("Please input several words, so a line of text, seperated with spaces: ")
line = input()
spaces_count = 0
for curr_char in line:
if(curr_char == " "):
spaces_count += 1
number_of_words = spaces_count + 1
print("You typed", number_of_words, "words") |
5b8a04e1bd700a830a788b62704c6a8526dc32ba | BjornChrisnach/Basics_of_Computing_and_Programming | /print_triangle.py | 118 | 4 | 4 | print("Please enter a positive integer: ")
n = int(input())
for i in range(1,n + 1):
line = i*'*'
print(line) |
20676d87b7477c1403c8077ba0d012065903113c | jlroland/retirement-success | /randomize.py | 7,313 | 3.5625 | 4 | import numpy as np
import pandas as pd
import random
from statistics import mean
from plotly.subplots import make_subplots
import plotly.graph_objects as go
run calculations.py #import clean data & function to calculate interest
#display distribution of historical returns for S&P 500
fig = go.Figure(data=[go.Hist... |
bd9cbc8368a63b0652102e1490ba049386c32b20 | thusyasin/python-programming | /leapy.py | 88 | 3.890625 | 4 | a=int(input())
if a%4==0:
print a,"is a leap year."
else:
print a,"is not a leap year."
|
386917245b7e7130aa3a96abccf9ca35842e1904 | getachew67/UW-Python-AI-Coursework-Projects | /Advanced Data Programming/hw2/hw2_pandas.py | 2,159 | 4.1875 | 4 | """
Khoa Tran
CSE 163 AB
This program performs analysis on a given Pokemon data file,
giving various information like average attack levels for a particular type
or number of species and much more. This program immplements the panda
library in order to compute the statistics.
"""
def species_count(data):
"""
... |
2a0042d38b10f6c4639988b12112e8ee795b480e | getachew67/UW-Python-AI-Coursework-Projects | /Advanced Data Programming/hw1/hw1.py | 4,316 | 3.921875 | 4 | """
Khoa Tran
CSE 163 AB
Program that implements the solution code for various problems presented
"""
def total(n):
"""
Returns the sum of the numbers from 0 to n (inclusive).
If n is negative, returns None.
"""
if n < 0:
return None
else:
result = 0
for i in range(n +... |
f72d0033f0c5504ad87e558f6a6b097b54c14c6b | veryspecialdog/pythonpractice | /创建函数.py | 525 | 3.671875 | 4 | x=1
while x<=9:
y=1
while y<=x:
print("{}*{}={}\t".format(x,y,x*y),end='')
y +=1
print()
x +=1
print()
names = ['anne','beth','george','damon']
ages = [12,45,32,102]
for i in range(len(names)):
print(names[i],'is',ages[i],'years old')
print(list(zip(names,ages)))
from math im... |
62963b58ed75d45c53c5ccbc3dcb01ed292307d4 | Baloolaoo/python-test | /02 - Matplotlib/candlestick.py | 928 | 3.8125 | 4 | # imports
import pandas_datareader as data
import pandas as pd
import mplfinance as mpf
import trading_functions as tf
'''
This scripts purpose is to plot a candlestick chart out of a pandas dataframe.
Next To-Do:
- Add functions for
- Inside days
- Outside days
- Plot Inside/Outside days in ch... |
c3626ea1efb1c930337e261be165d048d842d15a | Razorro/Leetcode | /72. Edit Distance.py | 3,999 | 3.515625 | 4 | """
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (rep... |
5d01d82bfd16634be636cce2cf2e1d31ea7208b1 | Razorro/Leetcode | /88. Merge Sorted Array.py | 1,353 | 4.28125 | 4 | """
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
I... |
86323e12a03901c476e861a37956ec4b04406ea7 | Razorro/Leetcode | /32. Longest Valid Parentheses.py | 2,151 | 3.890625 | 4 | """
Description 32:
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: "((()()))"
Output: 4
Explanation: The longest valid... |
2cd13056f72eaf8f16e342bacde6c9b17bd43d3b | Razorro/Leetcode | /49. Group Anagrams.py | 863 | 4.125 | 4 | """
Description:
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
Runtime: 152 ms, faster than 39.32% of Pytho... |
fad684b0de4618f7f7b2986dffc215705a382862 | Razorro/Leetcode | /77. Combinations.py | 1,177 | 3.6875 | 4 | """
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
执行用时: 160 ms, 在Combinations的Python3提交中击败了85.61% 的用户
内存消耗: 9.1 MB, 在Combinations的Python3提交中击败了56.38% 的用户
Not bad, just use recur... |
d2d6f21556955a4b8ec8893b8bf03e7478032b68 | Razorro/Leetcode | /7. Reverse Integer.py | 817 | 4.15625 | 4 | """
Description:
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overfl... |
c0de2ccf5660c74c913334edfee8f488603b9643 | Razorro/Leetcode | /24. Swap Nodes in Pairs.py | 1,194 | 3.984375 | 4 | """
Description 24
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Runtime: 48 ... |
1e806c64ffe1956225f22f369b5f355a053876c4 | fangmingc/ChuannBlog | /Python/Beginning_of_Python/3Function/作业3/Simulate_SQL.py | 13,814 | 3.75 | 4 | # 实现员工信息表
# 文件存储格式如下:
# id,name,age,phone,job
# 1,Alex,22,13651054608,IT
# 2,Egon,23,13304320533,Tearcher
# 3,nezha,25,1333235322,IT
#
# 现在需要对这个员工信息文件进行增删改查。
# 基础必做:
# a.可以进行查询,支持三种语法:
# select 列名1,列名2,… where 列名条件
# 支持:大于小于等于,还要支持模糊查找。
# 示例:
# select name,age where age>22
# select * where job=IT
# select * where p... |
c0c1620a94c64f7b13fe354fbbbe3032533a88c6 | jrahman1988/PythonSandbox | /myPandas_DataFrame_FromList.py | 733 | 4.0625 | 4 | '''
A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns.
Features of DataFrame:
Potentially columns are of different types
Size – Mutable
Labeled axes (rows and columns)
Can Perform Arithmetic operations on rows and columns
'''
import pandas a... |
92b2ac96f202ac222ccd4b9572595602abf0a459 | jrahman1988/PythonSandbox | /myDataStruct_CreateDictionaryByFilteringOutKeys.py | 677 | 4.34375 | 4 | '''
A dictionary is like an address-book where we can find the address or contact details of a person by knowing only his/her name
i.e. we associate keys (name) with values
Dictionary is represented by dict class. Pair of keys and values are specified in dictionary using the notation
d = {key1 : value1, key2 : value2 }... |
1a4d781b35cfbb98acbc1b8b9fad8aa9a78c51ac | jrahman1988/PythonSandbox | /myPandas_DescriptiveStatistics.py | 1,754 | 4.40625 | 4 | '''
A large number of methods collectively compute descriptive statistics and other related operations on DataFrame.
Most of these are aggregations like sum(), mean(), but some of them, like sumsum(), produce an object of the same size.
Generally speaking, these methods take an axis argument, just like ndarray.{sum, st... |
ebb36c2e43bbe17c911516f90c0874f406463b51 | jrahman1988/PythonSandbox | /myWebScrapping_fmNYTimes_VaccineProgress02.py | 867 | 3.875 | 4 | '''
Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF
We'll use here the pandas.read_html(), which returns a list of data frames. According to the PANDAS doc:
"This function searches for <table> elements and only for <tr> and <th> rows and <td> elements within
each ... |
e10c97db1dd0330fdc54271714ae7dbd607d3005 | jrahman1988/PythonSandbox | /myMatplotlib_CoronaVirusGraphs_v1.py | 4,580 | 3.875 | 4 | '''
Using Matplotlib module of Python, draw a different graphs, data read from (corona_virus.csv)
Note that, here we do the followings to fine tune the dataframe:
1. Read the data file corona_virus.csv from file system and create a dataframe
2. Delete the last row so that 'Total' is not considered in any calculations u... |
f45471a04eef4398d02bbe12151a6b031b394452 | jrahman1988/PythonSandbox | /myFunction_printMultipleTimes.py | 427 | 4.3125 | 4 | '''
Functions are reusable pieces of programs. They allow us to give a name to a block of statements, allowing us to run that block
using the specified name anywhere in your program and any number of times. This is known as calling the function.
'''
def printMultipleTimes(message:str, time:int):
print(message * tim... |
b2965c970bce71eee39841548b95ab6edf37d99b | jrahman1988/PythonSandbox | /myLambdaFunction.py | 1,212 | 4.125 | 4 | '''
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
'''
#define the lambda function
sentence = "I bought a bike, from a bike store, she bought a bike from amazon, they bought a bike from bike sto... |
a1a0da1d51bcc8c4f129c11550512d1221c9de92 | jrahman1988/PythonSandbox | /myPandas_WriteToCSV.py | 3,426 | 4.125 | 4 | '''
The Series and DataFrame class of Pandas has an instance method called to_csv() which allows to write the DF to a file
either in .xlsx, .txt or .csv format
'''
import pandas as pd
desired_width=320
pd.set_option('display.width', desired_width)
pd.set_option('display.max_columns',100)
#Read the pokemon_data.csv fr... |
ecc2b9c95284d27fc838148c5c3c0bd4f6d90358 | jrahman1988/PythonSandbox | /myPandas_FindValuesFromCSV.py | 642 | 4.03125 | 4 | '''
Find and output all rows contain a specific value in a specific column using df.loc()
'''
import pandas as pd
desired_width=320
pd.set_option('display.width', desired_width)
pd.set_option('display.max_columns',100)
#Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() met... |
56056f96ce0b1faa68b0937b60bbbf8294e1f3d8 | jrahman1988/PythonSandbox | /myWebScrapping3.py | 870 | 3.578125 | 4 | '''
Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF
'''
import pandas as pd
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate
from pandas import DataFrame
# GET the response from the web page using requests library
# url = 'https://www.t... |
76e7dc6bfa340596459f1a535e4e2e191ea483bc | jrahman1988/PythonSandbox | /myOOPclass3.py | 2,017 | 4.46875 | 4 | '''
There is way of organizing a software program which is to combine data and functionality and wrap it inside something called an object.
This is called the object oriented programming paradigm.
In this program we'll explore Class, behaviour and attributes of a class
'''
#Declaring a class named Mail and its methods... |
dafcc8c5cf58608ca4bba1a27dda168aa2980533 | jrahman1988/PythonSandbox | /myWebScrapping_fmAPIsample.py | 1,171 | 4.09375 | 4 | '''
Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF
We'll use here the pandas.read_html(), which returns a list of data frames. According to the PANDAS doc:
"This function searches for <table> elements and only for <tr> and <th> rows and <td> elements within
each ... |
cf3158ef73377ac7fe644d4637c21ae1501d804b | jrahman1988/PythonSandbox | /myStringFormatPrint.py | 551 | 4.25 | 4 | #Ways to format and print
age: int = 20
name: str = "Shelley"
#Style 1 where format uses indexed parameters
print('{0} was graduated from Wayne State University in Michigan USA when she was {1}'.format(name,age))
#Style 2 where 'f' is used as f-string
print(f'{name} was graduated from Wayne State University in Michi... |
75d2d53e7ca3ab189536b69d71a45abaa9c16435 | moyales/Data-Visualization | /Exercises/Ch15/15_1_cubes.py | 617 | 4.09375 | 4 | import matplotlib.pyplot as plt
# 15.1: Plot the first 5 cubic numbers;
# Then plot the first 5000 cubic numbers.
# Simple list of first 5 cube numbers
# x = [1, 2, 3, 4, 5]
# y = [1, 8, 27, 64, 125]
# plt.plot(x, y, linewidth=3)
# First 5000 cubes
x_val = list(range(1, 5001))
y_val = [x**3 for x in x_val]
plt.scat... |
892e851f82ea063d2c0dfff954ca742a16e6108a | YuZih/MystanCodeProJects | /stanCode_projects/Breakout Game/breakout.py | 2,734 | 3.984375 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao.
Here is the basic version of breakout game.
"""
from campy.gui.events.timer import pause
from breakoutgraphics import BreakoutGraphics
FRAME_RATE = 1000 / 120 # 120 frames per second
NU... |
0ca475cbfde5171ee06d55f0a4bb3e7209e33794 | aastrand/aoc2015 | /14/solve.py | 1,427 | 3.5 | 4 | #!/usr/bin/env python3
import re
import sys
from collections import defaultdict
def run_reindeer(speed, time, resting_time, run_time):
total = time + resting_time
laps = run_time // total
rest = run_time - (laps * total)
return laps * time * speed + (speed * (rest if rest < time else time))
def ra... |
dc3af3cadad3ebf5b5afc2f35a84716f47fb50dc | DAFFA4EVER/Jeruk-Nipis | /1.0/data_user.py | 1,384 | 3.75 | 4 | user_list = []
id = 0
class user:
def __init__(self, uid, name, age, film, food, address):
self.uid = uid
self.name = name
self.age = age
self.film = film
self.food = food
self.address = address
def save_list():
global user_list
data_list = open(r'1.0\user_... |
2f8eb7b30968c7c80f498a119cb82663c0eed891 | RomanYes/RomanYevchackProject | /HW_2_3.py | 95 | 3.90625 | 4 | a=int(input("Your number a:"))
b=int(input("Your number b:"))
a,b=b,a
print("Your answer:",a,b) |
5bde28c19b34d4d55a137b2ef673df2bcfe58f71 | yuanhsin8311/Spark-Projects | /Tutorial/Airline Delay Analysis/airline.py | 2,023 | 3.6875 | 4 | sc
# Set up the file paths for data
# If it's on the local system append file:// to the beginning of the path
# If it's on hdfs append hdfs://
airlinePath = "hdfs:///user/yuanhsin/flightDelaysData/airlines.csv"
airportPath = "hdfs:///user/yuanhsin/flightDelaysData/airports.csv"
flightPath = "hdfs:///user/yuanhsin/f... |
2b1a371545c766dc0cab3e981c587382d4d4aead | mimipeshy/pramp-solutions | /code/arr_i_and_element_equality.py | 1,749 | 3.75 | 4 | """
Array Index & Element Equality
Given a sorted array arr of distinct integers, write a function indexEqualsValueSearch that returns the lowest index i for which arr[i] == i.
Return -1 if there is no such index. Analyze the time and space complexities of your solution and explain its correctness.
input: arr = [-8... |
2b2895c74d089f7685f264b6e70a7ab8b090dc6e | mimipeshy/pramp-solutions | /code/award_budget_cuts.py | 1,967 | 3.671875 | 4 | """
Award Budget Cuts
The awards committee of your alma mater (i.e. your college/university) asked for your assistance with a budget allocation problem they’re facing.
Originally, the committee planned to give N research grants this year. However, due to spending cutbacks, the budget was reduced to newBudget dollars ... |
8788d7516ed9bd589cd392a1af5c37f453a8796c | mimipeshy/pramp-solutions | /code/array_quadruplet.py | 1,798 | 3.859375 | 4 | """
Array Quadruplet (meaning 4Sum)
Given an unsorted array of integers arr and a number s, write a function findArrayQuadruplet that finds four numbers (quadruplet) in arr that sum up to s.
Your function should return an array of these numbers in an ascending order. If such a quadruplet doesn’t exist, return an empt... |
34653fdfffaacb579ad87ee2d590c6ae37c5bb71 | mimipeshy/pramp-solutions | /code/drone_flight_planner.py | 1,903 | 4.34375 | 4 | """
Drone Flight Planner
You’re an engineer at a disruptive drone delivery startup and your CTO asks you to come up with an efficient algorithm that calculates
the minimum amount of energy required for the company’s drone to complete its flight.
You know that the drone burns 1 kWh (kilowatt-hour is an energy unit) f... |
c7f8cc285310a8dac2a2b4e62cf76f476323c2a8 | kwitte2232/CS121 | /pp6/permutationencryption.py | 1,703 | 3.96875 | 4 | import sys
# Skeleton code for problem https://uchicago.kattis.com/problems/permutationencryption
#
# Make sure you read the problem before editing this code.
#
# You should focus only on implementing the solve() function.
# Do not modify any other code.
def encrypt(string, perm):
'''
Takes a string and a li... |
22070230157e2d2621270485f3820923f3949923 | kwitte2232/CS121 | /pa3/cps.py | 14,879 | 3.578125 | 4 | # CS121 A'15: Current Population Survey (CPS)
#
# Functions for mining CPS data
#
# Kristen Witte
from pa3_helpers import read_csv, plot_histogram
import statistics
# Constants
HID = "h_id"
AGE = "age"
GENDER = "gender"
RACE = "race"
ETHNIC = "ethnicity"
STATUS = "employment_status"
HRWKE = "hours_worked_per_w... |
fa778ff469feb683a8373a688ef68ef6a31626c1 | kwitte2232/CS121 | /pa6/model.py | 16,266 | 4.0625 | 4 | # CS121 Linear regression
#
# Kristen Witte, kwitte
import numpy as np
from asserts import assert_Xy, assert_Xbeta
#############################
# #
# Our code: DO NOT MODIFY #
# #
#############################
def prepend_ones_column(A):
'''
Add a ones... |
dd9c666ab17a5afeb3e6c0fa1bdd1b27bb7f78ce | CSC1-1101-TTh9-S21/lab-week3 | /perimeter.py | 594 | 4.3125 | 4 | # Starter code for week 3 lab, parts 1 and 2
# perimeter.py
# Prof. Prud'hommeaux
# Get some input from the user.
a=int(input("Enter the length of one side of the rectangle: "))
b=int(input("Enter the length of the other side of the rectangle: "))
# Print out the perimeter of the rectangle
c = a + a + b + b
print("Th... |
daf9244c272a6fcf552cf3fc20c6a65566fa2d43 | HarshalBhoir/hackerrank-solutions | /python_practice/print_function.py | 343 | 3.59375 | 4 | if __name__ == '__main__':
n = int(input())
i = 1
numbers = []
while i <= n:
numbers.append(str(i))
i+=1
start = 0
count = len(numbers)
total = ""
total =str(total)
for number in numbers:
total+=numbers[start]
if start <= count:
start+=1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.