blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
9630ca90efc7a4a7cfe59d6012328e12f044148a | mlin367/InfiniteMonkey | /InfiniteMonkey.py | 850 | 3.53125 | 4 | import random
def RandString():
string = ''
for i in range(28):
string += random.choice("abcdefghijklmnopqrstuvwxyz ")
return string
def Score(generated):
goal = "methinks it is like a weasel"
score = 0
for i in range(28):
if goal[i] == generated[i]:
score += 1
r... |
9358f0873384c73f3e6f93ee913780197df923f5 | will-henney/bowshock-shape | /conic-projection/conproj_utils.py | 4,445 | 3.515625 | 4 | """Projection of conic sections (ellipses ... hyperbolae)
"""
from __future__ import print_function
import numpy as np
class Conic(object):
"""Bowshock shape - surface of revolution of a plane conic section
As the shape parameter `th_conic` is varied, this gives a sequence
from (`th_conic` = 45 - 90) obl... |
86111c137a1d1a289be16b2e57c45238b12526c8 | will-henney/bowshock-shape | /Stellar-Bowshocks-2017/regress_utils.py | 4,227 | 3.71875 | 4 | import numpy as np
from scipy.stats import linregress, pearsonr
from sklearn.linear_model import TheilSenRegressor
from matplotlib import pyplot as plt
def robust_linregress(x, y):
"""Simple interface to other regressors
This has same signature as `scipy.stats.linregress`
"""
# The Pearson correlat... |
1457af148ed128d0a8dae4254f9440727f39910e | aaronbss/Class_Test | /Class_Test_Selection_Sort.py | 3,528 | 4.15625 | 4 | # https://github.com/aaronbss/Class_Test
""" In this program i am taking the input of the student details in 3 different arrays and then manipulating it in
order to sort, fetch & delete entries. The sorting method used here is selection sort since it has a quick retrieve
time and also sorts in an ascending order making... |
4f79bf248975dd11aa9578ecc87cb56a287c7a99 | ArneRobben/DesertIslandDiscs | /code/Scraping.py | 6,730 | 3.625 | 4 | """ import libraries """
from urllib.request import urlopen
from bs4 import BeautifulSoup
import lxml
import requests
import re
import pandas as pd
import time
"""initialise a session"""
# load the landing page
landing_page = "https://www.bbc.co.uk/programmes/b006qnmr/episodes/player?page={}"
html = requests.get(lan... |
3eb7ee4a7864074572ba58faea66cc958f66acc2 | anishLearnsToCode/python-training-1 | /solution-bank/pattern/solution_17.py | 476 | 3.65625 | 4 | def sumNaturalNumbers(n: int) -> int:
return n * (n + 1) // 2
rows = int(input())
# upper triangle
number = 1
for i in range(rows):
for j in range(i + 1):
print(number if j == i else f'{number}*', end='')
number += 1
print()
# lower triangle
for i in range(rows):
number = sumNaturalN... |
d022fe369db2fc2786f226fc5173bf1b31ecfed0 | anishLearnsToCode/python-training-1 | /solution-bank/loop/solution_14.py | 206 | 3.796875 | 4 | """
WAP to calculate the sum of following series where n is input by user. 1 + 1/2 + 1/3 + 1/4 + 1/5 + ... 1/n
"""
n = int(input())
result = 0
for i in range(1, n + 1):
result += 1 / i
print(result)
|
5edca25761037ac2227f55e68046dfc0c024a049 | anishLearnsToCode/python-training-1 | /day_1/sum_n_natural_numbers.py | 467 | 3.890625 | 4 | """
Time Complexity: O(1)
k1 +k1 + n (k2 + k2) + k3 ==> n * K + a = O(n)
Space Complexity: O(1)
"""
"""
0: 0
1: 1
n: 1 + 2 + 3 + 4 + ... + n
"""
n = int(input()) # k1
result = 0 # k1
while n > 0: # n
result = result + n # k2
n = n - 1 # k2
print(r... |
f1047bb8c254008e8f8df6f9625f102b8c5e0476 | anishLearnsToCode/python-training-1 | /day_3/armstrong_number.py | 748 | 4.0625 | 4 | """
1
1^3 = 1
153
1^3 + 5^3 + 3^3
1 + 125 + 27 = 153
"""
"""
Time Complexity: O(number)
Space Complexity: O(1)
"""
def is_armstrong(number: int) -> bool:
sum_cubes = 0
for digit in str(number):
sum_cubes += int(digit) ** 3
return sum_cubes == number
"""
Time Complexity: O(b - a)
Space Complexity... |
061c84df4fcc64f1b7e52863a808533588f9bd7f | anishLearnsToCode/python-training-1 | /solution-bank/loop/solution_7.py | 312 | 4.09375 | 4 | """
WAP that reads a set of integers, and then prints the sum of the even and odd integers.
"""
numbers = list(map(int, input().split()))
even = 0
odd = 0
for number in numbers:
if number % 2 == 0:
even += number
else:
odd += number
print(f'Even Sum: {even}')
print(f'Odd Sum: {odd}')
|
fa876691a18d78065d3af8a9aff74eb8a14ccede | anishLearnsToCode/python-training-1 | /solution-bank/loop/solution_8.py | 368 | 4.1875 | 4 | """
WAP that prompts the user to input a positive integer. It should then output a message
indicating whether the number is a prime number.
"""
number = int(input())
is_prime = True
for i in range(2, number):
if number % i == 0:
print('composite number')
is_prime = False
break
if is_prime... |
4ce7acc6228c7452cbfc71994b7035049b484118 | anishLearnsToCode/python-training-1 | /solution-bank/pattern/solution_18.py | 337 | 4.03125 | 4 | # pascal's triangle
from math import factorial
def permutation(n, r) -> int:
return factorial(n) // factorial(n - r)
def combination(n: int, r: int) -> int:
return permutation(n, r) // factorial(r)
rows = int(input())
for i in range(rows):
for j in range(i + 1):
print(combination(i, j), end=... |
909a76f6f26af2922d5de1e25247bf11ed1e805f | anishLearnsToCode/python-training-1 | /solution-bank/loop/solution_6.py | 210 | 4.21875 | 4 | """
WAP that prompts the user to input an integer and then outputs the number with the digits reversed.
For example, if the input is 12345, the output should be 54321.
"""
number = input()
print(number[::-1])
|
1842271635038a3185babadbba2e739c3083dd6e | anishLearnsToCode/python-training-1 | /solution-bank/pattern/solution_9.py | 263 | 3.921875 | 4 | rows = int(input())
for row in range(rows - 1):
# first number
print(1, end=' ')
# xxxxx
print('x ' * (row - 1), end='')
# second number
print(row + 1 if row is not 0 else '')
# last row
for i in range(rows):
print(i + 1, end=' ')
|
15617df20cc9db3225a5b4ccf63bdedd06670b5f | anishLearnsToCode/python-training-1 | /day_2/pattern_13.py | 839 | 3.875 | 4 | """
n = 5
____*
___*_*
__*___*
_*_____*
*_______*
_*_____*
__*___*
___*_*
____*
2nd last row : (n - 2) th
spaces(n - 2) = 2(n - 2) - 1 = 2n - 5
# upper triangle (n)
# spaces: n - i - 1
# star: 1
# spaces: 2i - 1
# star: 1 except for first
# lower triangle (n - 1)
# spaces: i + 1
# star: 1
# spaces: k - 2i
# star: 1 ... |
811fc7158acb1087d21495628fbf4be99030e3cf | anishLearnsToCode/python-training-1 | /day_1/arithmetic_operators.py | 425 | 3.828125 | 4 | """
5 * print + 2 * =
Time: O(1)
Space: O(2 * int = O(k) = O(1)
"""
a = 10
b = 3
# REPL--> repeat evaluate print loop
# addition
print(a + b)
# subtraction
print(a - b)
# multiplication
print(a * b)
# division (--> float)
print(a / b)
# floor division (a // b = floor(a / b)) -> int
print(a // b)
# power operato... |
cd2545ac47f174ab0831554e9e34416e5296ad80 | anishLearnsToCode/python-training-1 | /day_3/dictionary.py | 530 | 4.03125 | 4 | """
Dictionary / HashMap / Map / HashTable
list
index --> value
int ----> anything
unique not unique
key ---> value
anything anything
unique not unique
- mutable
- iterable
- no booleans
- no lists
- no dict
"""
words = {
'hello': 100,
'world': 56,
'i': 567,
'am': 100,
'batman': 34,
Tr... |
a298b6e9d0490deeef0a2688b072d88f686a2ddc | anishLearnsToCode/python-training-1 | /day_1/print_funtion.py | 273 | 4.25 | 4 | """
Time Complexity: O(1)
Space Complexity: O(1)
"""
print('hello world', end=' ** ')
print('this is amazing!!!')
print('i am on top of the world')
print('\ni am on a new line\n\n', end='***')
print('\tsomething\ni am once again on a new line\t\t', end='this is the end')
|
30d4ecfd6c949b98bd694615047c7c9eb6e85cf3 | anishLearnsToCode/python-training-1 | /day_2/pattern_10.py | 592 | 3.703125 | 4 | """
n = 4
j 0 1 2 3 4
i
0: 1
1: 1 2 1
2: 1 2 3 2 1
3: 1 2 3 4 3 2 1
# increasing
count = i + 1
f(j) = j + 1
j : 0 1 2 3 4 5
s : 1 2 3 4 5 6 7
# decreasing
count = i
f(i, j) = i - j
j : 0 1 2 3 4
i = 3
s : 3 2 1
"""
"""
Time Complexity: O(n^2)
Space Complexity: O(1)
"""
n = int(input())
for i in range(n):
# ... |
1ca587eb7d4b26449dca116350ef3416bbffb432 | zolaneta/dictionary | /dic4ed.py | 814 | 3.53125 | 4 | # The Best Dictionary in The World
# created in Sleepy Hollow NY on October 28, 2015
# by Aneta Zolkiewicz for Edward Eames
print "You are the best in the world!\n"
world_best_dic = {'you are': "jestes", 'the best': "najlepsza", 'in': "na", 'the world': "swiecie"}
print world_best_dic['you are'], world_best_dic['... |
8d2b67127264b57599932c5c94d8cd81b3df0e3c | apisourse/netology_python | /1-06/1-6__init__.py | 943 | 4.1875 | 4 | class Car:
# pass #просто заглушка, если класс пустой, если не пустой, то писать не нужно
# Создаем атрибуты класса
color = 'black'
engine_volume = 1500
year = 2018
fuel = 0 #l
position = 0
speed = 0 #km/h
status = 'stopped'
coords = [0, 0, 0]
def __init__(self, fuel, position):
self.coords = [... |
5c585863fc23204da62d1e349cddc6081109155c | apisourse/netology_python | /1-03/1-3.py | 10,948 | 4.1875 | 4 |
my_integer = 10
my_float = 5.5
my_string = 'Hellow World'
my_string = "Hellow World"
My_bool = True
My_bool = False
#type - узнать/вывести тип данных
print(type(my_integer))
print(type(my_float))
print(type(my_string_1))
print(type(my_string_2))
print(type(my_bool_1))
print(type(my_bool_2))
#типы дан... |
44cb90685249d6f6a91188c03a6753547c22bc2e | virensachdev786/my_python_codes | /decorators4.py | 463 | 3.609375 | 4 | def wrap2(func2):
def wrapper2(a):
print("i am in wrap 2")
func2(a.upper())
print("wrap 2 is execuited")
return wrapper2
def wrap1(func):
def wrapper(a):
print("i am in wrap 1")
func(a.split())
print("wrap 1 is execuited")
return wrapper
@wrap2
@wrap1
d... |
db444f91e9b69917c48d70d4fc39393e59c0c70c | virensachdev786/my_python_codes | /OPERATOROVERLOADING.py | 1,130 | 4 | 4 | class Point(object):
def __init__(self,x,y):
self.x = x
self.y = y
#def __str__(self):
#print("{0},{1}".format(self.x,self.y))
# def __add__(self,secondobj):
# a = self.x + secondobj.x
# b = self.y + secondobj.y
# return (a,b)
#
def __sub__(self, se... |
5a5773da9a58a0f0688fbd7730ee89ff1907a226 | virensachdev786/my_python_codes | /pyDS.py | 992 | 4.25 | 4 | def main():
#LIST
# print("Enter the size of list")
# n = int(input())
# a = list()
#
# for i in range(n):
# print("enter elements of list: ")
# c = int(input())
# a.append(c)
#
# print("the entered list is: {0} ".format(a))
#Tuple
# print("Enter size of... |
f816e2fbab49db1993bf466c849ec0bf6322f559 | virensachdev786/my_python_codes | /101219.py | 526 | 3.890625 | 4 | class ABC(object):
def __init__(self):
pass
#class method has 2 types i.e static method and class method
@staticmethod
def hello():
print("hello i am inside hello !")
@classmethod
def hello2(cls):
print("hello i am inside hello2 !")
print(cls)
def main():
... |
400e46df1e58b1a6914e2e72e63ba6323e9e04f8 | josephwalker504/python-set | /cars.py | 1,470 | 4.125 | 4 | # Create an empty set named showroom.
showroom = set()
# Add four of your favorite car model names to the set.
showroom = {"model s", "camaro", "DB11", "B7"}
print(showroom)
# Print the length of your set.
print("length of set",len(showroom))
# Pick one of the items in your show room and add it to the set again.
... |
9526d123ae0572436181528704dd248c2e2958d4 | gbrown022/automate | /ch3/third.py | 3,117 | 3.90625 | 4 | # GCB 3/31/2020
#
# Questions
# 1. Why are functions advantageous to have in your programs?
# A. Functions are advantageous to reuse code, making it easier to
# debug and trace
#
# 2. When does the code in a function execute: when the function is
# defined or when the function is called?
# A. Fun... |
1c15083451c9db168ae0845a84b4518254f1d950 | xinlee92/PythonDemo | /4_1_2.py | 85 | 3.859375 | 4 | #print Hello! 10 8 6 4 2
print('Hello!')
for i in range(10,0,-2):
print(i)
|
3a8509c665c69547db951f53eec828c5469c501a | ssmero/CSCE240 | /39IteratorsFlick/PythonExample/ex.py | 679 | 3.578125 | 4 | ##
class MyList():
def __init__(self):
self._myList = []
def __str__(self):
s = ''
for item in self._myList:
s += str(item)
return s
def __iter__(self):
for item in self._myList:
yield item
def add(self, rec):
self._myList.append... |
bcf70ec3b7be74467025c7bcf160e7c699d1d6c8 | h294liu/2020_01_01discretization | /.ipynb_checkpoints/step1_download_dem_function-checkpoint.py | 1,236 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 22:39:15 2019
@author: hongl
"""
import argparse, os
import urllib.request
import shutil
def process_command_line():
'''Parse the commandline'''
parser = argparse.ArgumentParser(description='Script to download TNM DEM.')
parser.add_argument(... |
ff4bd30eab1be0f7cdffe65d89d1f635f8aadb5d | zerosoftwere/python-tut-demo | /authenticate_4.py | 378 | 3.875 | 4 | # Wrong way of doing it
users = [{'username': 'henry', 'password': 'secret'}, {'username': 'xero', 'password': 'secure'}]
username = input('Enter username: ')
password = input('Enter password: ')
for user in users:
if user['username'] == username and user['password'] == password:
print('Login Successful'... |
91edad8c1a7978d660c77fcc7606c71e96773fe8 | shereenElSayed/python-github-actions-demo | /src/main.py | 885 | 4.15625 | 4 | #!/usr/bin/python3
import click
from src import calculations as calc
@click.command()
@click.option('--name', prompt='Enter your name',
help='The person to greet.')
def welcome(name):
"""Simple program that greets NAME for a total of COUNT times."""
click.echo(f'Hello {name}')
@click.command()... |
f8d0cc9cb0e5f8adf9077ffb39dd6abedfedaa12 | jiheon356/MyPython | /ch4/ㅁㄴ.py | 183 | 3.578125 | 4 | a = int(input('점수를 입력하세요'))
if a >= 70 :
print:('통과입니다.')
print:('축하합니다.')
else :
print:('불합격입니다.')
print("안녕")
|
bf019174ad2356fa85ed600e9a4149955a374719 | jiheon356/MyPython | /ch5/elif2.py | 323 | 3.734375 | 4 | age = int(input("나이를 입력하세요"))
if age >= 19:
print("성년입니다")
print("무조건 입장하세요")
elif age >=13:
print("청소년입니다")
print("청소년 관람가만 입장가능합니다")
else :
print("어린이입니다")
print("나이 구분을 끝냈니다")
|
aa3fb63f0c8cbbea09529aa75ac0e0817880e1ba | jacobjiggler/Location-Visualizer | /utils.py | 2,658 | 3.671875 | 4 | import csv
import sys
from math import radians, cos, sin, asin, sqrt
class Point:
def __init__(self, lat, lon, time, acc):
self.lat = lat
self.lon = lon
self.time = time
self.acc = acc
def __str__(self):
return "{lat: " + '%.7f'%self.lat + ", lon: " + '%.7f'%self.lon + ... |
c88f314ad4a77694123e4495d97fff1787f48da5 | niranjanvl/test | /py/misc/min.py | 429 | 4.03125 | 4 | """
Given a list of numbers,
find the minimum number
> min.py 3 4 5 2 30 -1 6 7 8 -2
min : -2
> min.py 31 4 5 2 30 6 7 -8 100
min : -8
"""
import sys
if(len(sys.argv) < 2):
print("Usage :\n\t min.py <list of numbers>")
exit(0)
num_list = [int(x) for x in sys.argv[1:]]
print(num_lis... |
cb14a75694c303c8ced888a2dbb06d95cf424a82 | niranjanvl/test | /py/misc/word_or_not.py | 611 | 4.40625 | 4 | #--------------------------
# for each of the given argument
# find out if it is a word or not
#
# Note : Anything not a number is a Word
#
# word_or_not.py 12 1 -1 abc 123b
# 12 : Not a Word
# 1 : Not a Word
# -1 : Not a Word
# abc : Word
# 123b : Word
#--------------------------
import sys
values = sys.argv[1:]
... |
737013cf2ef608e5a672dbcbb129137ade18f9e9 | niranjanvl/test | /py/misc/gen_odd_even.py | 2,505 | 4.34375 | 4 | '''
Generate odd/even numbers between the given numbers (inclusive).
The choice and the range is given as command line arguments.
e.g.,
gen_odd_even.py <odd/even> <int> <int>
odd/even : can be case insensitive
range can be ascending or descending
gen_odd_even.py odd 2 10
3, 5, 7, 9
gen_odd_even.py odd 10 ... |
82ef0d627b03c478a1988b33cc7f81cb04493380 | niranjanvl/test | /py/misc/power.py | 438 | 4.28125 | 4 | import sys
def pow(x,y):
#x to the power of y
result = 1
if y > 0:
#repetitive multiplication
i = 0
while i < y:
result *= x
i += 1
elif y < 0:
#repetitive division
i = y
while i < 0:
result /= x
i += 1
... |
d2a35e08ee389b9a9b0a47a3c7d78ee5a11fa10f | niranjanvl/test | /py/misc/conjunction.py | 3,153 | 3.96875 | 4 | """
Take a series of True or False and compute conjunction
T : True, F : False
conjunction : x AND y AND z ...
Overall True when ALL are True
-->Overall False when any of one them is False
"""
import sys
values = sys.argv[1:]
result = True
count = 0
for v in values:
count += 1
if (v == 'F'):
result = ... |
3e31a528908f76d20fabf4e0198322b22ff861cf | SantiagoYoung/aidingwang | /Store/helper.py | 173 | 3.53125 | 4 | # -*-coding:utf-8 -*-
# 判断手机号是否正确
def check_phone_num(num):
num = num.replace(' ', '')
return num.isdigit() and len(num) == 11 and num[0] == '1'
|
41099a375c5cbe212a9d4dafe8d98f6fd3c341db | abhishekboy/MyPythonPractice | /src/main/python/04Expressions.py | 934 | 4.125 | 4 | a =12
b =3
print (a+b) # 15
print(a-b) # 9
print(a*b) # 36
print(a/b) # 4.0
print(a//b) #interger division,rounder down to minus infinity
print(a % b) #modulo : remainder after interger division
print(a**b) #a power b
print() #print empty line
# in below code a/b can't be used as it will ... |
7949e71c08d54862ec13c8606a5701debaad36ac | Mjayendr/My-Python-Learnings | /amount to cents.py | 1,945 | 3.984375 | 4 | # program to find number of coins required to make a total amount
def main ():
# enter the amount in euro
amount = input("enter the amount in Euro:")
# conver the amount into cents
cents = int(amount*100)
# calculate the number of E2 coins required
coins = int(cents/200)
cents = int(cents%200)... |
b05d92cbbb972902b5fb5b6ca213408d6d8b77a9 | Mjayendr/My-Python-Learnings | /discon.py | 1,409 | 4.375 | 4 | # This program converts distance from feet to either inches, yards or meters.
# By: Jay Monpara
def main():
print
invalid = True
while invalid:
while True:
try: # using try --- except statements for numeric validation
distance = raw_input("Enter the distance in feet: ") # prompt user to... |
66ce742e5725c7d94a6e119ae5fbe050d6ec5d0e | Mjayendr/My-Python-Learnings | /Temperatur C to F.py | 644 | 4.375 | 4 | #A program to convert temperature from degree celcius to Degree farenheit.
# By Jay Monpara
def Main():
print
Celcius = input("What is the temperature in celcius?") # provoke user to input celcius temperature.
Fahrenheit = (9.0/5.0) * Celcius + 32 # process to convert celcius into fahrenheit
pri... |
fc62d6f18d7bd1e3ff07e8640c79e1216999b294 | markser/InClassGit3 | /wordCount.py | 643 | 4.28125 | 4 | # to run the program
# python3 wordCount.py
# then input string that we want to retrieve the number of words in the given string
def wordCount(userInputString):
return (len(userInputString.split()))
def retrieve_input():
userInputString = (input('Input a string to determine amount of words: '))
if len(us... |
b9343d3e9b06ba213d9df0ebb481935c473efb84 | dym0080/learn-python | /python-crash-course/chapter04/c4.py | 99 | 3.59375 | 4 | ## 动手试一试
# 4.1
pizzas=['pizzaA','pizzaB','pizzaC']
for pizza in pizzas:
print(pizza) |
d2d013888400f4cc77b1969937181589c32c5db3 | bhankit1410/Data-Structures-Algorithms-Coursera-UCSD-HSE | /1 Algorithmic Toolbox/Homeworks/5 Dynamic Programming 1/3 Edit Distance/Python/edit_distance.py | 924 | 3.703125 | 4 | # Uses python3
def edit_distance(A, B):
n = len(A)
m = len(B)
# array of distances (n+1 x m+1)
D = [[0] * (m+1) for i in range(n+1)]
# initialize zero row and column
for i in range(n+1):
D[i][0] = i
for j in range(m+1):
D[0][j] = j
for j in range(1, m+1):
for i... |
e6bdb8d5f661d5c69ba9d84b5987b0b4f39955b0 | bhankit1410/Data-Structures-Algorithms-Coursera-UCSD-HSE | /1 Algorithmic Toolbox/Homeworks/2 Algorithmic Warm-up/2 Last Digit of a Large Fib Num/Python/fibonacci_last_digit.py | 338 | 3.578125 | 4 | # Uses python3
def calc_fib_last_digit(n):
fib_nums_last_dig = []
fib_nums_last_dig.append(0)
fib_nums_last_dig.append(1)
for i in range(2, n + 1):
fib_nums_last_dig.append((fib_nums_last_dig[i - 1] + fib_nums_last_dig[i - 2]) % 10)
return fib_nums_last_dig[n]
n = int(input())
print(calc_f... |
d9dd60ee5d6ef7303f6f2890eb57e382e9cf4bfb | zinvergo93/Python-2 | /nest-function-in-parent.py | 2,206 | 3.59375 | 4 | # def greeting(first, last):
# def full_name():
# return f'{first} {last}'
# print(f'Hi {full_name()}!')
# greeting('Kristine', 'Hudgens')
# **********DEFAULT ARGUMENT**************
# def greeting(name = 'Guest'):
# print(f'Hi, {name}!')
# greeting()
# greeting('Zac')
# def some_function(collection ... |
a7cfb74a8f730b575f68cfca2f2d6cf40cfe3064 | adagenlik/vowels-in-sentence | /unlu_harf_sayisi_bulma.py | 270 | 3.859375 | 4 | def text(sentence,number=0):
letter="aeiouAEIOU"
for character in sentence:
if character in letter:
number+=1
return number
sentence=input("Type a sentence: ")
print("There is {} vowels in this sentence".format(text(sentence))) |
2f280b65e023274be93d4caeb358ab1c82d0a031 | claudimf/python_collections_01 | /src/aulas/05.py | 926 | 3.671875 | 4 | class ContaCorrente:
def __init__(self, codigo):
self.codigo = codigo
self.saldo = 0
def deposita(self, valor):
self.saldo += valor
def __str__(self):
return "[>>Código {} e Saldo {}<<]".format(self.codigo, self.saldo)
conta_do_gui = ContaCorrente(15)
conta_do_gui.deposit... |
a2aa208306a84b18b33473d8e2d958697d797a00 | juliandwain/agora | /stats/utils.py | 3,573 | 3.5625 | 4 | # -*- coding: utf-8 -*-
from typing import Union
import numpy as np
__all__ = [
"get_neighbors",
]
# ------------------------------------------------------------------------------------------------------------
# helper functions for the percolation module
def get_neighbors(current: tuple,
... |
52c937dd434578982d4ddd4aa65cb2981414f71e | zhangwhitemouse/pythonDataStructure | /datastructure/python-data-structure-stack/comparestring.py | 1,146 | 3.765625 | 4 | #比较含有#(退格)的字符串
"""
问题解析:
输入两个字符串,比较两个字符串是否相等,# 号代表回退一个字符
如 ab#c ad#c 这两个字符串是相等的,都为ac
算法分析:
将两个字符串都压入栈,然后比较栈中的元素
"""
from python_stack import Stack
class Solution:
def backspaceCompare(self, S, T):
s1 = Stack()
s2 = Stack()
str1 = ""
str2 = ""
... |
19d5309eeeb5429350a3e3dae8368c265c4d3034 | zhangwhitemouse/pythonDataStructure | /datastructure/python-data-structure-linkedlist/reverselinkedlist.py | 2,242 | 4.4375 | 4 | """
反转链表
问题分析:反转链表就是将单链表的每个节点的指针域指向前一个节点,头节点特殊一点,它需要指向None
算法分析:第一反应就是暴力解法呀,就是将单链表的每个元素拿出来放入列表,然后再构建一遍链表(被自己蠢到了哈哈哈)。
然后想了想发现我用两个变量,一个存储当前节点,一个存放当前节点的前一个节点不就行了
"""
# class Solution:
# def reverseList(self, head):
# prev = None
# curr = head
# while curr != None:
# temp = cur... |
1b9c88dee4e0454746f0278283342c671e1dda00 | zhangwhitemouse/pythonDataStructure | /datastructure/python-data-structure-linkedlist/partatitionlinkedlist.py | 946 | 3.703125 | 4 | #给定一个值,将链表分成两部分
"""
问题分析:给定一个值,当链表中的元素小于这个值时,放在链表的左边,大于等于这个值时放在链表的右边
算法解析:使用两个哑节点,一个节点存放左边的链表,一个存放右边的链表,最后将两个链表拼接起来
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def partition(self, head, x):
left = ListNode(-1)
right =... |
a9f69df548eeeb1ba6c3fc3f108f8332d7b87829 | zhangwhitemouse/pythonDataStructure | /labuladong/dynamic planning/coins.py | 1,612 | 3.5625 | 4 | """凑零钱问题
给你 k 种面值的硬币,面值分别为 c1, c2 ... ck,
每种硬币的数量无限,再给一个总金额 amount,
问你最少需要几枚硬币凑出这个金额,如果不可能凑出,算法返回 -1 。
"""
def coinChange(coins, amount):
def dp(n):
# base case
if n < 0: return -1
if n == 0: return 0
# 初始化 求最小所以初始化成正无穷
res = float("INF")
for i in coins:
... |
72d8861e6615b5f6beadac21c0e584ec809ff7cb | zhangwhitemouse/pythonDataStructure | /leetcode/max_sum.py | 315 | 3.734375 | 4 | """
给定一个数组,计算数组中的元素和的最大值,要求相邻元素不能相加
(leetcode198 打家劫舍)
动态规划的思想
"""
def max_sum(arr):
prev = 0
curr = 0
for i in arr:
curr,prev = max(prev+i,curr),curr
return curr
arr = [5,3,2,6]
print(max_sum(arr)) |
7d38e37cc4bcabf62ea0ed45419723292b4f87a2 | zhangwhitemouse/pythonDataStructure | /datastructure/python-data-structure-other/klargenumber.py | 1,098 | 3.703125 | 4 | #找到数据流中第K大的数
"""
问题描述:给你一个数组,返回指定第K大的元素(是排好序的第K大元素)
算法分析:我觉得最简单的方法就是对数组进行排序,然后返回第几大的数,就是返回相应的索引对应的值,比如返回第2大的数,索引就为1
然后想了想,用堆也可以做;返回第几大的索引,就pop几次呗
"""
# class KthLargest:
# def __init__(self, k: int, nums: List[int]):
# self.k = k
# self.nums = nums
# def add(self, val: int)... |
2b4678080f6a2ec73f8d29966edf5ef9905d59b6 | gtohill/library | /Education.py | 599 | 3.5625 | 4 | import nltk
import re
def education(text):
regexInst = re.compile('University|College')
regexDegree = re.compile('Bachelor|Master|Degree|Diploma|Certificate|University|College')
file = open('/home/gary/PycharmProjects/Resume/education/degreetypes.txt', 'r')
typeList = file.read().split()
lines = ... |
3f9d4042e057824cd67db069464dd85aa738bcff | gtohill/library | /Data_Structures/BST/Node.py | 1,716 | 4.0625 | 4 |
class Node:
def __init__(self, value):
print("Node created")
self.root = value
self.leftChild = None
self.rightChild = None
def insert(self, data):
if self.root == data:
return False
elif self.root > data:
if self.leftChild:
... |
d7066aeb50397c6ae47dd20d599a4fbd13826198 | taydon220/AverageLocation | /location.py | 507 | 3.90625 | 4 | class Location:
def __init__(self, name, lat, lon, weight=1):
self.name = name # String, name of city. Ex) Houston, TX
self.lat = lat # Float, decimal value latitude.
self.lon = lon # Float, decimal value longitude.
self.weight = weight # Float, years spent in this location.
... |
00c308e997cbee87bf44671d09c585ee6c2e7fd8 | jankaWIS/euler_problems | /euler_p7.py | 909 | 3.953125 | 4 | def prime(a):
""" returns list of prime numbers less than a"""
primes = []
for val in range(1, a + 1):
# If num is divisible by any number between 2 and val, it is not prime
if val > 1:
for n in range(2, val):
if (val % n) == 0:
break
... |
69da5c3786c54322535074c92654f468af3fa14e | Abdelrahmansameh/mlLab | /GridWord.py | 6,456 | 3.515625 | 4 | from Q import Q
import matplotlib.pyplot as plt
import numpy as np
class GridWord(object):
def __init__(self, grid=None):
"""
Args:
> grid: (np.array) defines the labyrinth.
in binary:
000000 (0) blank cell
001000 (8) wall up
... |
cea697c2c197c3e651e79de50b68ec6c131f5952 | alr13g/Travelennial | /parseFlights.py | 2,279 | 3.5 | 4 | import json
import requests
all_flights = []
def parse_all_flights(scraped_datas, source, destination):
print("IN HERE")
file_name = "{0}-{1}-flight-results.json".format(source, destination)
print(file_name)
with open(file_name) as data_file:
allFlights = json.load(data_file)
for flight in allFlights:
arri... |
c3c9e667952c268e888324b5bdaef9a67928e702 | Nielsjonathan/RSL | /Python/filter.py | 2,052 | 3.921875 | 4 | #I start with importing the Pandas library and saving it as pd
import pandas as pd
#I read to csv into the dataframe called data
data = pd.read_csv('userReviews all three parts.csv',sep=';')
#I create the names for the columns
column_names = ['movieName', 'Metascore_w', 'Author', 'AuthorHref', 'Summary','origin_ratin... |
9e37a237b16036501a185d95fb4b2940a17053fd | fidler32/schoolWork | /CupsAndDice.py | 9,320 | 3.96875 | 4 | # William Fidler
# 02/09/20
# Dice and Cups
# "I have not given or received any unauthorized assistance on the assignment
# Link here: https://youtu.be/nYY9GrAjXgc
from random import randint
class SixSidedDie():
"""
Class for a six sided die
"""
def __init__(self): #Initializer sets
self.n = ... |
8744dc8c9eba8768cf4e278cb878169a82792fe3 | fidler32/schoolWork | /DiceAndCups.py | 3,252 | 3.953125 | 4 | # William Fidler
# 02/09/20
# Dice and Cups
# "I have not given or received any unauthorized assistance on the assignment
# Link here: https://youtu.be/7rc21vwnZYw
from random import randint
class SixSidedDie():
"""
Class for a six sided die
"""
def __init__(self): #Initializer
self.n = 6
... |
98adcb3d1fcd05a757ed636012128e92e6dd9db0 | MarquezLuis96/Intermediate_Python | /Module III/02 - High Order Functions (Filter, Map & Reduce)/02 - Map/not_using_map.py | 323 | 4.09375 | 4 | # Powering using list comprehensions
##
def powering(list):
powered_list = [i**2 for i in list]
return powered_list
def run():
list = [0,1,2,3,4,5,6,7,8,9]
powered = powering(list)
print("List:")
print(list)
print("Powered List:")
print(powered)
if __name__ == "__main__":
ru... |
de034cb5b76c14f33c4caac5fb75179e3b410c77 | MarquezLuis96/Intermediate_Python | /Module V/01 - Files management/files.py | 1,168 | 3.546875 | 4 | #
# #
from os import remove
def create_file(file_dir: str):
with open(file_dir, "w") as f:
pass
f.close()
def read_INT_in_file(file_dir: str):
numbers = []
with open(file_dir, "r", encoding="UTF-8") as f:
for line in f:
numbers.append(int(line))
print(numbers)
... |
7a27b518abf3b833d3cf0bd5922c5112683e2fc4 | MatMoore/Connection | /tests/testCases.py | 6,314 | 3.90625 | 4 | from scripting.parser import Node
def syntaxTree():
'Iterator returning syntax trees representing an expression, the value of each expression, and a name for the test'
# 1 + 1
tree = Node(
'functioncall',
[
Node('literal',[],1),
Node('literal',[],1),
],
'add'
)
ans = 2
yield tree,ans,'simple_add'
... |
1b5f3862b4b0005d5a5b2df1473474dc635e20b3 | Pepper-Targaryen/PACT_3.2 | /Module Traitement d'Image/OutilPython/getLibrary.py | 576 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 29 14:22:19 2018
@author: yfei
"""
#get a library of judgement
flagSet = []
#For each instance, judge whether it can be eliminated
for i in range(256):
print("line%d:" %i)
str = '{0:08b}'.format(i)
print(str[0]+str[1]+str[2])
print(str[3]+' '+str[4])
... |
2530ebec42d1045deb932d94ad6611d34b1a88cb | EricSeokgon/PythonTutorial | /sequence/sequence.py | 90 | 3.546875 | 4 | s = 'hello'
print s[-3:]
print s[:-3]
print s[-1:-3]
print s[-1:0]
print s[-1:-3:-1]
|
e6054132eec724147a9e3a541a35cd25ce4aee80 | EricSeokgon/PythonTutorial | /function/2.py | 176 | 3.640625 | 4 | _author__ = 'sklee'
#number = input("숫자를 입력 하세요: ")
a = 123
print(a)
a = "Python"
print(a)
a = [1, 2, 3]
print(a)
for i in range(10):
print(i, end=' ') |
1db1373cfba847a27fa58baa102baa00aeeed6f3 | aijimenez/Application | /Habitsbox_app/app/habit.py | 998 | 3.8125 | 4 | """
These module contains the characteristics of a habit
"""
import datetime
class Habit:
"""Information about the characteristics of a habit """
def __init__(self, name, periodicity, motivation, description):
"""
Parameters
----------
name : str
Name of the habit
... |
d874651cc4b2c0ae54c5492b3d09be02b93d36d9 | markellofff/Data-Structures | /SLL_stack.py | 1,928 | 3.953125 | 4 | """
Stack Using SLL(singly linked list)
"""
class Node:
# Constructor
def __init__(self):
self.data = None
self.next = None
# for setting data
def set_data(self, data):
self.data = data
# for getting data
def get_data(self):
return self.data
# for setting... |
b600e6a4736c8e148f189c02c545bce1cf06a2d9 | Bourdonn/TP-Python | /TP2/my_prog.py | 2,213 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 25 19:04:50 2019
@author: makhatchabdulvagabov
"""
#ASCII A:65 - Z:90, a:97 - z:122
def coding(message, key, isCoding):
"""code the giving message with the giving key.
If the bollean isCoding is true we code the message. Otherwise we decod... |
24c54c38da306b928b261a535092ede01b84fbc7 | eduever/python_scripts | /read-file.py | 1,728 | 3.984375 | 4 | #!/usr/bin/python
"""
## read last N lines
def read_lastNline(fname, N):
with open(fname) as file:
for lines in (file.readlines() [-N:]):
print(lines, end='')
read_lastNline('text.txt',3)
if __name__ == '__main__':
filename = 'text.txt'
number = 3
try:
read_lastNline(filename,number)
except:
print('fi... |
b9b047e95e2edcd68a1addf8aec82d55a1979cd6 | joaovictor78/Sistema-de-Venda-de-A-ai- | /src/pages/main.py | 657 | 3.515625 | 4 | # 2 ano de Informatica - Matutino
# Joao Victor Bezerra da Silva
# ***** Linguagem de programação *****
from tkinter import *
import tela_home,tela_cadastro
class Application(Tk):
def __init__(self):
Tk.__init__(self)
self._frame = None
self.switch_frame(tela_home.Home)
def switch_fr... |
8283d4d65fef8af21e5dab025305417d5dc2fe38 | AshmeadAli/Text-Adventure-Game | /Misc/agregation.py | 1,150 | 3.828125 | 4 | class Room():
def __init__(self,name):
self.name = name
self.room = None
self.key = None
def set_room(self,name):
self.room = name
def describe(self):
print(self.name)
print(self.room)
def set_key(self,... |
8c9de28c7550a9906e04e9815eb101d585107d87 | yaaaang/3D_B_field_biot_savart | /magnetic_field.py | 1,797 | 4.03125 | 4 | """
This is a code to generate and visualize the 3-D magnetic field generated by either circular coils, straight coils or
any combinations of the two types of coils, with constant current flowing inside.
Note the volume of the coils is neglected.
Here we need numpy, mayavi.
The basic theory is based on Biot-Savart's... |
43e89a01a12c0e2d0ccf2731e8edefa283daff37 | mageoffat/Python_Lists_Strings | /Rotating_List.py | 1,291 | 4.4375 | 4 | # Write a function that rotates a list by k elements.
# For example [1,2,3,4,5,6] rotated by two becomes [3,4,5,6,1,2].
# Try solving this without creating a copy of the list.
# How many swap or move operations do you need?
num_list = [1,2,3,4,5,6,7,8,9] # my numbered list
val = 0 # value
def rotation(num_... |
a7b5e2edf7c556e6924bf1422c39459008e119b7 | mageoffat/Python_Lists_Strings | /Number_to_List.py | 327 | 3.921875 | 4 | # Write a function that takes a number and returns a list of its digits.
# So for 2342 it should return [2,3,4,2].
number = 2342
num_list = []
a = True
while(a):
temp = number%10
number = number//10
num_list.insert(0, temp)
if (number == 0):
a = False
break
print(nu... |
4d00095273473999da0e7fe06d9ce7fd9609687d | mishajw/informational_influence | /informational_influence/cache.py | 772 | 3.609375 | 4 | """
Support for caching function results
"""
from pathlib import Path
import pickle
class Cache:
"""
Caches the result of a function in a pickle'd file
"""
def __init__(self, inner_fn):
self.inner_fn = inner_fn
def __call__(self, *args, **kwargs):
return self.inner_fn(*args, **k... |
9822925967bd614fdeaf60e475348b316d262c7d | r00tSe7en/PythonCode | /2019.08.01/E第五章-if语句/条件测试/检查列表中特定值.py | 204 | 3.828125 | 4 | #!/usr/bin/env python
#coding=utf-8
list = ['abcd','ABCD','1234','5678']
print(list)
#判断类表中存在某值
print('abcd' in list)
#判断类表中不存在某值
print('efgh' not in list)
|
44f48e9d9f34745a57ed9d2fb4f45776e9493336 | r00tSe7en/PythonCode | /2019.08.01/G第七章-用户输入和while循环/while循环/while().py | 92 | 3.703125 | 4 | #!/usr/bin/env python
#coding=utf-8
num = 1
while num <= 5:
print(num)
num += 1 |
4843ce7cd3dabc3c8373a543cd02cd87e920fcc3 | r00tSe7en/PythonCode | /2019.08.01/D第四章-操作列表[含元组]/使用列表的一部分/遍历切片.py | 156 | 3.59375 | 4 | #!/usr/bin/env python
#coding=utf-8
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for value in players[0:3]:
print(value.title())
|
db9c3beeb0de41689507fdf526b0d1f3a8fadc0a | r00tSe7en/PythonCode | /2019.08.01/D第四章-操作列表[含元组]/遍历数值列表/遍历整个列表.py | 201 | 3.734375 | 4 | #!/usr/bin/env python
#coding=utf-8
lists = ['abcd','ABCD','1234','5678']
for list in lists:
print(list)
#在循环中执行更多操作
for list in lists:
print(list.title() + ",eee")
|
f0f1ab90df7c2f4aa6af3d890047ad1fe3e37b4f | laraib22/Assignment | /cal01.py | 121 | 3.875 | 4 | def add(num1, num2):
return num1 + num2
def sub(num1,num2):
return num1-num2
res = (add(5, 3),sub(6,2))
print(res) |
13ecd656f3fe1fa576935a259ee42f8c180c22b2 | akimmi/cpe101 | /poly.py | 591 | 4.1875 | 4 | import math
# the purpose of this function is add the values inside the list
# list, list --> list
def poly_add2(p1, p2):
a= p1[0] + p2[0]
b= p1[1] + p2[1]
c= p1[2] + p2[2]
return [a, b, c]
# the purpose of this function is to multiply the values inside the list (like a polynomial) by using the distrib... |
7d8597e25693fa0c6514ee4ce063263665eb5b82 | akimmi/cpe101 | /pattern01.py | 552 | 3.828125 | 4 | import driver
# the purpose of this function is to match the puzzle with the code
# int, int --> string
def letter(row,col):
if (0 <= row <= 19):
if (row % 2 == 0):
if (0 <= col <= 2):
return 'L'
else:
return 'G'
elif (row % 2 == 1):
... |
30d1fe21755f9b35eec18c0cddc00f94086d5f8b | gixlg/Advent-of-Code-2019 | /Day5/Day5_1.py | 3,034 | 3.8125 | 4 | from Day5.Operation import Operation
class Program:
def __init__(self, program, program_input=None):
print(program)
self.instructions = program.split(",")
self.instructions = list(map(int, self.instructions))
self.outputs = []
self.program_input = program_input
self... |
9ded94ec0fce77c9027eaaa5c86604e225baf575 | ashishrawat93/brown-cs-2470 | /rnn_lm/assignment.py | 8,610 | 4.0625 | 4 | """
Stencil layout for your RNN language model assignment.
The stencil has three main parts:
- A class stencil for your language model
- A "read" helper function to isolate the logic of parsing the raw text files. This is where
you should build your vocabulary, and transform your input files into data that ... |
d48296ee82a301f601312d82e05f0c7ffb73d396 | Kaplun-Alex/Beetroot_Courses | /2021_02_17/tupleex.py | 2,363 | 3.578125 | 4 | def firstex():
print(t)
for i in t:
tup = tuple(i.split(','))
print(tup)
if tup[1] == ' м':
f = open('male.txt', 'a')
f.writelines('Кобєль пративный - ' + tup[0] + '\n')
f.close()
print('Кобєль пративный - ' + tup[0])
elif tup[1] ==... |
4a089606290f405116af2b37c132b031e65606d4 | Kaplun-Alex/Beetroot_Courses | /2021_03_13/OOP.py | 2,490 | 3.703125 | 4 | class Person:
def __init__(self, name, surname, age):
self.nm = name
self.srn = surname
self.ag = age
def talk(self):
print('Ппривет меня зовут', str(self.nm), str(self.srn), 'и мне', str(self.ag), 'лет')
p = Person('Kaplun', 'Alex', 35)
p.talk()
class Dog:
def __init__(... |
18d665eba87ae845d1184dd5a6a59dbd81a00286 | the-last-question/team7_pythonWorkbook | /Imperial Volume.py | 1,838 | 4.59375 | 5 | # Write a function that expresses an imperial volume using the largest units possible. The function will take the
# number of units as its first parameter, and the unit of measure (cup, tablespoon or teaspoon) as its second
# parameter. Return a string representing the measure using the largest possible units as the ... |
ad96d98d4d22a8e7df1170264c9e50f494246946 | mac160382/airtravel | /flght.py | 3,195 | 3.9375 | 4 |
class Flight:
"""A flight with a particular passenger aircraft."""
def __init__(self, number, aircraft):
if not number[:2].isalpha():
raise ValueError("No airline code in {}".format(number))
if not number[:2].isupper():
raise ValueError("Invalid airline code {}".forma... |
82cda6b117d2bc918b8d675313db9f7a5b6314ba | sunyumail93/Python3_StepByStep | /Day02_IfElse/Day02_IfElse.py | 653 | 4.15625 | 4 | #!/usr/bin/python3
#Day02_IfElse.py
#Aim: Solve the missing/extra input problem using if/else statement. Use internal function len(), print()
#This sys package communicate Python with terminal
import sys
Total_Argument=len(sys.argv)-1 #sys.argv[0] is the script name
if Total_Argument == 0:
print("Please input two... |
723fac97b86ec70045e619e816a6fc698fa0596d | sunyumail93/Python3_StepByStep | /Day08_TupleSet2DList/Day08_TupleSet2DList.py | 3,253 | 4.34375 | 4 | #!/usr/bin/python3
#Day08_TupleSet2DList.py
#Aim: Besides list and dictionary, there are more objects/data structures: tuple, set and two dimensional list (array)
#Tuple: (1,2,3,’string’,1,2,3), different to List, Tuple is unmutable, so you cannot append or change values. Same as List, Tuple and can store repeated, dif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.