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 |
|---|---|---|---|---|---|---|
6df26dde295f7469571316d03b5897b470c9d5ce | jaymax01/web_scraping | /scraping world population table/table_scraping.py | 1,071 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 21:46:11 2021
@author: Max
"""
# Importing libraries for reqesting HTML and scraping the data
import pandas as pd
import requests
from bs4 import BeautifulSoup
# Loading the worldmeters population table and its HTML
url = 'https://www.worldometers.info/world-populatio... |
1e54ffb0b9b6a4643d5014a5311d394b5d58fbee | 690/Runetrader | /tools/utils.py | 934 | 3.546875 | 4 | from ast import literal_eval
import random
import numpy as np
def random_position(x1, y1, x2, y2):
""" Return a random (x, y) coordinate from a square """
return random.randint(x1, x2), random.randint(y1, y2)
def dynamic_coordinate_converter(parent, child, operator):
if operator == '-':
return... |
c6145249ef56fe9890f142f597766fdb55200466 | Ahmad-Saadeh/calculator | /calculator.py | 810 | 4.125 | 4 | def main():
firstNumber = input("Enter the first number: ")
secondNumber = input("Enter the second number: ")
operation = input("Choose one of the operations (*, /, +, -) ")
if firstNumber.isdigit() and secondNumber.isdigit():
firstNumber = int(firstNumber)
secondNumber = int(secondNumber)
if opera... |
1145f9426e46a217bbe2a7f8618eef9beb963028 | skuxy/ProjectEuler | /problem17.py | 2,579 | 3.90625 | 4 | #! /usr/bin/env python
"""
If the numbers 1 to 5 are written out in words:
one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand)
inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or ... |
10307facddb2c1bbdd074b4212026f24e7e7b7b3 | skuxy/ProjectEuler | /Problem5.py | 718 | 3.921875 | 4 | # Project Euler: Problem 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# worst.function.name.ever.
def n_evenly_divisible_by_n_to_check(n, n_to_check=... |
4370c07de04f74ab6b193353c651208359fd7402 | EricSchles/stanford_algo_class | /first_pass/assignment_two/part_one.py | 914 | 3.921875 | 4 | def class_qsort(alist):
left = 0
right = len(alist)-1
while left < right:
mid = (right - left)//2
partition(alist,left,mid)
partition(alist,mid+1,right)
def quick_sort(alist):
if len(alist) <= 1:
return alist, 0
else:
less = []
equal = []
gr... |
3ae8822e763883c09c6dd49325ec331874cf09c7 | josephine151/josephine151.github.io | /python/instructions.py | 982 | 4.09375 | 4 | from random import *
# list of first and last names
names = ["faith", "kathy", "sara", "aleef", "jesus", "lenny"]
last_names = ["smith", "johnson", "duggan", "doe", "riley", "brown"]
# list of names already used
names_used = []
last_names_used = []
#generate all names
for x in range(len(names)):
# get 2 random numb... |
e90d473af4c3813c79b79a197137c95dd0144c6f | hgunawan/python_data_structures | /binary_search/binary_search.py | 1,054 | 4.03125 | 4 | def binary_search0(input_array, value):
"""Your code goes here."""
length = len(input_array)/2
current_index = length
while length > 0:
length = length/2
# print(current_index)
current_value = input_array[current_index]
if(current_value==value):
... |
04e5e4d754215941401cb1ed5d6446adbdeea7de | Lunreth/pyleecan | /pyleecan/Methods/Output/Output/getter/get_machine_periodicity.py | 1,096 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from math import gcd
def get_machine_periodicity(self):
"""Return / Compute the (anti)-periodicities of the machine in time and space domain
Parameters
----------
self : Output
An Output object
Returns
-------
per_a : int
Number of space periodicit... |
9c29aab8e0246210cfe7d562e3a49c42790807c1 | jdowzell/Thesis | /header_check.py | 947 | 3.6875 | 4 | def areAllHeadersPresent(heads):
"""
A function to make sure that all headers required for plotting a Light Curve
are present, and alert the user if any are missing (and which ones).
Input parameter (heads) should be of the form: heads=fits.getheader("file.fits")
"""
# Generic Flag
... |
ab2c78b99d9943f51e24159e297f5ecc43b412af | Jamlet/python | /ejer1.py | 109 | 3.6875 | 4 | num1 = input("Año nacimiento: ")
num2 = input("Año actual: ")
print("Tu edad es: " + str(num2 - num1))
|
a77a7070703a6fa7456b19e0d71887faeb1aa6f8 | wilber-guy/Project-Euler | /4_Largest_palindrome_product.py | 248 | 3.59375 | 4 | largest_num = 0
for i in range(1,1000):
num = i
for p in range(1,1000):
total = num * p
if total > largest_num:
if str(total) == str(total)[::-1]:
largest_num = total
print(largest_num)
|
5f0d32469ffa9391088cbbe715b209ee3211c466 | jngo102/ECE_203_Project | /main.py | 10,788 | 3.78125 | 4 | from Tkinter import *
import os
import pickle
# Class definition for main map
class Game:
def __init__(self, root):
self.root = root
self.root.title("Space Exploration")
self.canvas = Canvas(self.root, width=1280, height=720)
self.canvas.pack()
# Booleans that will be toggl... |
30dfcf31f9272f5253b052d4aa342dc05663dded | abdelhadisamir/SIRD_Model | /get_day_of_day.py | 317 | 3.828125 | 4 | from datetime import timedelta, date
def get_day_of_day(n=0):
'''''
if n>=0,date is larger than today
if n<0,date is less than today
date format = "YYYY-MM-DD"
'''
if(n<0):
n = abs(n)
return date.today()-timedelta(days=n)
else:
return date.today()+timedelta(days=n) |
4f603beccd737bea2d9ebd9d92bf3013dc91b9d1 | surajkumar0232/recursion | /binary.py | 233 | 4.125 | 4 | def binary(number):
if number==0:
return 0
else:
return number%2+10 * binary(number//2)
if __name__=="__main__":
number=int(input("Enter the numner which binary you want: "))
print(binary(number)) |
41003f89f2b8940c34a017c9f93ba9ca44e85b52 | CHyuye/ObjectOriented | /ObjectConcept_inherit.py | 5,663 | 4.125 | 4 | # 面向对象编程 —— 继承: 子类拥有父类的所有属性和方法
"""
面向对象三大特点
1、封装 —— 根据职责将属性和方法封装到一个抽象的类中
2、继承 —— 实现代码的重用,相同的代码不用重复的编写
3、多态 —— 不同的对象调用相同的方法,产生不同的执行结果,增加代码的灵活度
"""
# 继承的概念:子类拥有父类的所有属性和方法
# 专业术语:Dog类是Animal的派生类,Animal是Dog类的基类,Dog从Animal类中派生
# 1、单继承
# class Animal:
#
# def eat(self):
# print("吃--")
#
# def... |
9a7c37180aeb52ef8192ffffa20261bf89169c2b | CHyuye/ObjectOriented | /python_FileOperation.py | 2,923 | 3.734375 | 4 | # 1、文件基本操作
"""
三个步骤: 一个函数open,三个方法
1、open —— 打开文件,并且返回文件操作对象
2、读,写文件
read —— 将文件内容读取到内存
write —— 将指定内容写入文件
3、关闭文件 close
"""
# 打开文件,默认是只读模式
# file = open("README")
#
# # 读取文件
# # 读取完文件后,文件指针会移动到文件末尾
# text = file.read()
# print(text)
# print(len(text))
#
# print("-" * 30)
#
# # 当执行了一次rea... |
572d03f6ffd2cd9582c1ce93dc44f064bcac5a4e | ksambaiah/python | /leet/leet_136.py | 463 | 3.890625 | 4 | #!/usr/bin/env python3
'''
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
'''
def singleNumber(nums):
result = 0;
for i in nums:
result ^= i
... |
9edae297e93650718436858af87ddf2026ca3b1a | ksambaiah/python | /leet/addNumbers.py | 1,025 | 3.8125 | 4 | #!/usr/bin/env python3
''' leetcode 12268 '''
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
sumll = ListNode
followup = 0
while l1.next or l2.next:
... |
65e7f36fb7862257cf9557101f4570273d9fed28 | ksambaiah/python | /misc/enum.py | 120 | 3.625 | 4 | #!/usr/bin/env python3
nums = [-100, -20, 0, 2, 23, 44, 55]
for i, num in enumerate(nums):
print(i)
print(num)
|
52a4c94eacea03a662dffaacb42008bbf80b031c | ksambaiah/python | /pythonds/chap1/binarySearch.py | 697 | 3.859375 | 4 | #!/usr/bin/env python3
import random
def binarySearch(a, left, right, num):
if right >= left:
middle = (right + left) // 2
if a[ middle ] == num:
return middle
elif a [ middle ] > num:
return binarySearch(a, left, middle-1, num)
else:
re... |
a9ee8a83512a5bc4f404b8244a1168a4329ddc2a | ksambaiah/python | /leet/maxSwap.py | 476 | 3.9375 | 4 | #!/usr/bin/env python3
'''
You are given an integer num. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
'''
def maxnum(i):
a = 0
t = i
a = []
while t:
a.append(t % 10)
print(a)
t = t // 10
a = rev(a)
max = a... |
31e16b0a88fa71b18df243af4b46ee3030a3c51d | ksambaiah/python | /salesforce/leet_220.py | 1,180 | 3.828125 | 4 | #!/usr/bin/env python3
'''
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
For each 0 <= i < nums1.length, find the index j such that... |
698ff141a859099a6a39834f018eee6d55399945 | ksambaiah/python | /leet/leet1534.py | 645 | 3.96875 | 4 | #!/usr/bin/env python3
'''
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
'''
def goodArray(arr,a,b,c):
result = 0
l = len(arr)
for i in range(l-2):
for j in range(i+1,l-1):
for k in range(j+1,l):
a1 = abs(arr[j... |
86cbf381166e71e7b50d958c67cc156f81426078 | ksambaiah/python | /educative/fr.py | 208 | 4.15625 | 4 | friends = ["xyz", "abc", "234", "123", "Sam", "Har"]
print(friends)
for y in friends:
print("Hello ", y)
for i in range(len(friends)):
print("Hello ", friends[i])
z = "Hello ".join(friends)
print(z)
|
45aff915fec08bc0c3e299c9be9b2796f153abc0 | ksambaiah/python | /educative/ll.py | 2,602 | 4.09375 | 4 | #!/usr/bin/env python3
'''
Linked list and Node implementation in Python3
'''
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self):
self.head = None
def append(self... |
8345d871035574f880766fc17503c1331fbe62ab | ksambaiah/python | /slidingwindow/sliWind2.py | 688 | 4.03125 | 4 | #!/usr/bin/env python3
import sys
# Maximum sum of contiguous array of size 3
# Not sure how to get minint getting maxint and negating
def slidingWindow2(arr, num):
total = 0
ptotal = 0
for i in range(len(arr)):
if i < num:
total = total + arr[i]
ptotal = total
else:
... |
7a02b7fb90ff4990ffc97fb57ef4af420db7519d | ksambaiah/python | /misc/merge.py | 546 | 3.734375 | 4 | #!/usr/bin/env python3
def merge(a, b):
i = 0
j = 0
c = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i = i + 1
else:
c.append(b[j])
j = j + 1
while i < len(a):
c.append(a[i])
i += 1
while j < len(b)... |
55f6c6dd5be7fd981e708927ba51f51c622f9b45 | ksambaiah/python | /leet/palindrome.py | 355 | 3.984375 | 4 | #!/usr/bin/env python3
def isPalindrome( x: int) -> bool:
y = 0
x1 = x
while x:
y = x % 10 + y * 10
x = x // 10
if x1 == y:
return True
else:
return False
if __name__ == '__main__':
print(1234)
print(isPalindrome(1234))
print(1... |
97dff201244de680e04f4a00776ed8a10b35297e | ksambaiah/python | /leet/leet217_1.py | 266 | 3.859375 | 4 | #!/usr/bin/env python3
def containsDuplicate(nums) -> bool:
b = set(nums)
if len(b) == len(nums):
return False
else:
return True
if __name__ == '__main__':
a = [1,2,3,4,1]
print(a)
print(containsDuplicate(a))
|
a6fac80206f0a4db0aff4d33454cf93beb3f2d66 | ksambaiah/python | /files/fileRead.py | 219 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: samkilar
"""
f = open("testfile.txt", "r")
line = f.readline()
while line:
# Take out new line
print(line.rstrip())
line = f.readline()
f.close()
|
0cf3d8481c243de3b9d354ad30ce1a281461aca4 | ksambaiah/python | /educative/find_string_anagrams.py | 439 | 4.375 | 4 | #!/usr/bin/env python3
import itertools
'''
'''
def find_string_anagrams(str, pattern):
arr = []
for p in itertools.permutations(pattern):
p = "".join(p)
#arr.append(str.find(p))
if p in str:
arr.append(str.index(p))
arr.sort()
return arr
if __name__ == '__main__':
... |
4afc4191fd6650dac57415404d36803373e071e4 | ksambaiah/python | /hackerRank/arraySum.py | 436 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 00:41:04 2020
@author: samkilar
"""
def addArray(arr):
y = 0
for i in range(len(arr)):
y = y + arr[i]
return y
if __name__ == "__main__":
# We are taking array, later we do take some random values
arr = [0, ... |
81fe8bfbb8b91b076661c5b80e59c910eaf87a76 | ksambaiah/python | /pythonds/chap1/greatNum.py | 813 | 3.75 | 4 | #!/usr/bin/env python3
''' leet 1431
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has.
For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Noti... |
ba10c88ad9067c960b174ac2af00eca60b395f8c | Neb2/Text-RPG | /data/enemies.py | 3,955 | 3.578125 | 4 | import random
# generates a random enemy from a txt file.
class Mobs:
def enemy_gen(self, character):
if character.location in ["b6", "c5", "c6", "c7", "d4", "d5", "d6", "d7", "d8", "e5", "e6", "e7", "f5", "f6",
"g6", "h6", "i6", "j6", "k5", "k6", "k7", "l5", "l6",... |
9f1ad80a37d8ad76083ffaf29b4cf15ab6ddfd96 | Neb2/Text-RPG | /data/save_exit.py | 1,076 | 3.640625 | 4 | import os
import pickle
import sys
def save(character, en1):
from data.menu import game_menu
if os.path.exists("save_file"):
print("Are you sure you want to overwrite your current save? Y/N")
option = input("> ")
if option.lower() == "y":
with open('save_file', '... |
bfe2a975900f1efd6c10c1d22e9e4da1593719df | derekb/2018-advent-of-code | /day-05/solution.py | 669 | 3.578125 | 4 | #!/usr/bin/env python
import sys
import string
def reactive_units():
forward = set([f'{char}{char.upper()}' for char in list(string.ascii_lowercase)])
backward = set([f'{char}{char.lower()}' for char in list(string.ascii_uppercase)])
return forward.union(backward)
def react(molecule):
for reaction in... |
fbb36c0dcde24118eea1546ac1f96fc7b0b5f108 | shreeyash-hello/Python-codes | /replace.py | 112 | 3.71875 | 4 | inp=input('enter the string: ')
char = inp[0]
inp = inp.replace(char, '$')
inp = char + inp[1:]
print(inp)
|
f5f0bd3a82563eed93c8e034204dd7c090be67fa | shreeyash-hello/Python-codes | /sorting.py | 1,079 | 4 | 4 | def selection_sort():
A = []
inp = int(input('enter the number of students: '))
for i in range(inp):
enter = float(input(f'enter the percentage of student {i + 1}: '))
A.append(enter)
for i in range(len(A)):
# print(A)
a = i
for j in range(i + 1, len(A)):
... |
4647a038acd767895c4fd6cdbfcc130ef60a87ce | shreeyash-hello/Python-codes | /leap year.py | 396 | 4.1875 | 4 |
while True :
year = int(input("Enter year to be checked:"))
string = str(year)
length = len(string)
if length == 4:
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!")
break
else:
print("The year isn't a leap year... |
b74ba7ee11dafa4f0482c903eeee240142181873 | bengovernali/python_exercises | /tip_calculator_2.py | 870 | 4.1875 | 4 |
bill = float(input("Total bill amount? "))
people = int(input("Split how many ways? "))
service_status = False
while service_status == False:
service = input("Level of service? ")
if service == "good":
service_status = True
elif service == "fair":
service_status = True
elif service_... |
20c8bf9296f70690fcb550759d1b3e2461b88d6a | 0xJinbe/Exercicios-py | /Ex 051.py | 560 | 4.03125 | 4 | """Altere o programa de cálculo do fatorial, permitindo ao usuário calcular o fatorial várias vezes e limitando o fatorial a números inteiros positivos e menores que 16."""
import math
lista = []
count = 0
qnt = int(input('Digite a quantidade de numeros que deseja entrar: '))
while qnt != count:
numero = float(in... |
7626ba157020a6e67630d783a958221ad18ace0d | 0xJinbe/Exercicios-py | /Ex 021.py | 1,241 | 4.3125 | 4 | """Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações:
Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve ... |
6734d25a36b656fea9923b2f73deb3348ee77a1d | 0xJinbe/Exercicios-py | /Ex 041.py | 412 | 3.984375 | 4 | """Faça um programa que leia 5 números e informe a soma e a média dos números.
"""
lista = []
i = 1
while i <= 5:
a = int(input('Informe os numeros: '))
lista.append(a)
media = sum(lista)/len(lista)
soma = sum(lista)
i += 1
print(lista, soma, media)
l = []
for i in range (5):
a = int(input('Inf... |
7c1038a8db99d96fbb4a35323a8f5a2e27d4c8d4 | 0xJinbe/Exercicios-py | /Ex 057.py | 793 | 3.921875 | 4 | """Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato."""
n_eleitores = int(input('Qual o numero total de eleitores? '))
l_candidatos = []
count_A = 0
count_B = 0
count_C = 0
n_repetiç... |
d3379c4e3a7e371830181a9c671d33b77048399e | 0xJinbe/Exercicios-py | /Ex 025.py | 652 | 4.125 | 4 | """Faça um Programa para leitura de três notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e presentar:
A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva média alcançada;
A mensagem "Reprovado", se a média for menor do que 7, com a respectiva média alcançada;
A me... |
56d6c020e5cd346dcae49b952bfd6b60bf5d8b1c | 0xJinbe/Exercicios-py | /Ex 031.py | 1,131 | 3.640625 | 4 | """Um posto está vendendo combustíveis com a seguinte tabela de descontos:
Álcool:
até 20 litros, desconto de 3% por litro
acima de 20 litros, desconto de 5% por litro
Gasolina:
até 20 litros, desconto de 4% por litro
acima de 20 litros, desconto de 6% por litro Escreva um algoritmo que leia o número de litros vendidos... |
53c4bae226ec0c1fe618f6bad7e74682ea30d227 | IgorKwiatkowski/codecademy-excersises | /sum_digits.py | 582 | 3.5625 | 4 | # def sum_digits(n, result=0):
#
# if n <= 9:
# result += n
# return result
# else:
# result += int(str(n)[0])
# print(result)
# if len(str(n)[1:]) > 0:
# sum_digits(int(str(n)[1:]), result)
def sum_digits(n):
if n <= 9:
return n
last_digit ... |
8f3f0618149fd6b523685e69c8a7c262e53bc5f1 | sijaannapurna/InfyTQ-DSA | /day1_assgn_2_car_and_service.py | 1,720 | 3.625 | 4 | #DSA-Assgn-2
class Car:
def __init__(self,model,year,registration_number):
self.__model=model
self.__year=year
self.__registration_number=registration_number
def get_model(self):
return self.__model
def get_year(self):
return self.__year
def get_registration_nu... |
fcf99d62f5b4618ce054af060aaf342067ec8ea1 | desireevl/hackerrank-regex-solutions | /applications/utopian_identification_number.py | 211 | 3.90625 | 4 | import re
n_lines = int(input())
for i in range(n_lines):
line = input()
match = re.search(r'^[a-z]{,3}\d{2,8}[A-Z]{3,}', line)
if match:
print('VALID')
else:
print('INVALID')
|
85a0fbe3a7492c11b2cab082b448251deac9edb5 | SebKleiner/Project_ITC_Data_Mining | /user_args.py | 3,467 | 3.671875 | 4 | """
Arg parse and clean results
"""
import argparse
from utils import utils
class UserInputs:
"""Constructs a class from user inputs"""
def __init__(self, input_args):
"""Takes in user/default inputs as attributes"""
self.command = input_args.command[utils['MAGIC_ZERO']]
self.sleep = ... |
fa9d388ce7eb2b049aef558bd002d67eff84ef86 | Myeongchan-Kim/NHNNEXT_ML | /elice_1_10_solution.py | 3,612 | 3.578125 | 4 | '''
Introduction to Numpy
조금 지루했나요? 마지막으로 가장 중요한 부분인 Numpy를 이용한 기초 통계처리에 대해 배우겠습니다.
numpy.sum
배열에 있는 모든 원소의 합을 계산해서 리턴합니다.
A = numpy.array([1, 2, 3, 4])
print(numpy.sum(A))
사칙연산
재미있게도 Numpy의 배열에 사칙연산을 그대로 적용할 수 있습니다. 수학에서는 행렬에 숫자를 더하고, 빼고, 곱하고, 나누는 것을 허용하지 않지만 편의를 위해 만들어진 기능입니다. 실제로 큰 데이터를 다루는 통계분석 시에 굉장히 유용한 기능입니다. ... |
c5670156343d5f5b21aa6e56155afa368fb42cc8 | natalieborgorez/python_projects | /once_upon_a_time.py | 955 | 3.953125 | 4 | # Strange code by Natalie Borgorez
character_name = 'April'
character_age = 18
#print('Once upon a time there was a lass called ' + character_name + ', ')
#print('she was ' + character_age + ' years old. ')
print('Once upon a time there was a lass called %s, ' % character_name)
print('she was %i years old.' % c... |
3500f4e3506310d48f80196e03cb8f43d5fe949f | Molexar/akvelon_python_internship_3_Nikita_Potasev | /task_1/utils.py | 503 | 3.796875 | 4 | # Calculating by recursion
def fibonacci_rec(n):
if n == 0 or n == 1 or n == 2:
return 1
return fibonacci_rec(n-1) + fibonacci_rec(n-2)
# Calculating by cached values
fibs = {0: 0, 1: 1, 2: 1}
def fib_cache(n):
if n in fibs:
return fibs[n]
fibs[n] = fib_cache(n-1) + fib_cache(n-2)
... |
6c5499a4e2f71f024850a73bc10a738ac82486e4 | MynorSaban1906/Proyecto1_Compi1 | /pru.py | 22,156 | 3.65625 | 4 | from simbolos import *
class Scanner:
lista_tokens = list() # lista de tokens
lista_errores = list() # lista errores lexico
pos_errores = list() # lista de posiciones de errores
# estado = 0
lexema = ""
lista_reservadas=list()
transiciones=list()
def __init__(self):
sel... |
5d73028bb1e3d44a55398bac1775a2130e8758c3 | onokatio/nitkc-Python-training | /No6.py | 284 | 4.0625 | 4 | #!/usr/bin/python
inputs = []
while True:
print("input string a >",end='')
a = input()
print("input string b >",end='')
b = input()
if b in a:
print(b,"is exist in ",a)
print("index is", a.find(b))
else:
print(b,"is not exist in ",a)
|
d547858a9796f7da6ddecfc925c01577793976d7 | mhirayama/python | /tutorial/numpy11.py | 608 | 3.65625 | 4 | import numpy as np
array = np.random.randint(0, 100, 20)
print(array)
X = np.sum(array) #配列の総和
print(X)
X = np.mean(array) #配列の平均
print(X)
X = np.var(array) #配列の分散
print(X)
X = np.std(array) #配列の標準偏差
print(X)
X = np.max(array) #最大値
print(X)
X = np.argmax(array) #最大値のインデックス
print(X)
X = np.min(array) #最小値
print(... |
b447fae2e619f5d8779cdc222f6d2796b5e81f54 | mhirayama/python | /tutorial/pandas08.py | 646 | 3.671875 | 4 | import numpy as np
import pandas as pd
#標準正規分布に従った乱数のデータフレームを2個生成
df_1 = pd.DataFrame(data = np.random.randn(5, 5), index = ['A','B','C','D','E'],
columns = ['C1','C2','C3','C4','C5'])
df_2 = pd.DataFrame(data = np.random.randn(5, 5), index = ['F','G','H','I','J'],
columns = ['C1... |
cac0f57c99df4f1d46d0c8334c96b122146e986b | aki202/nlp100 | /chapter6/052.py | 187 | 3.578125 | 4 | import reader
from stemming.porter2 import stem
for word in reader.words():
if word == None:
print('')
continue
stem_word = stem(word)
print('%s\t%s' % (word, stem_word))
|
08318811782f882ed856f2ff1eef82456b94977a | aki202/nlp100 | /chapter6/051.py | 156 | 3.703125 | 4 | import reader
for index, word in enumerate(reader.words()):
if word == None:
print('')
else:
print(word)
#print('[%d] %s' % (index, word))
|
e54410cf9db5300e6ef5c84fd3432b1723c017c6 | MeganTj/CS1-Python | /lab5/lab5_c_2.py | 2,836 | 4.3125 | 4 | from tkinter import *
import random
import math
# Graphics commands.
def draw_line(canvas, start, end, color):
'''Takes in four arguments: the canvas to draw the line on, the
starting location, the ending location, and the color of the line. Draws a
line given these parameters. Returns the handle of the l... |
fb565965becf2065b92aea2e4c9099df396f7dce | MeganTj/CS1-Python | /lab4/lab4_d2.py | 1,274 | 3.96875 | 4 | from tkinter import *
def draw_square(canvas, color, length, center):
'''Takes in four arguments: the canvas to draw the square on, the color of
the square, the length of the sides of the square, and the center of the
square. Draws a square given these parameters. Returns the handle of the
square that... |
5ba66ebea016f39abea513010890110bfe2329d3 | varbees/snakepy | /food.py | 705 | 3.71875 | 4 | from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.penup()
self.color("darkgrey")
self.speed('fastest')
self.shapesize(stretch_wid = 0.6, stretch_len = 0.6)
self.refresh()
# Experimental code for Bonus food
# de... |
53e0756741f417f26cea140eecd97a6f30bc7802 | stepan-martynov/PY-3_2-1 | /cook-book.py | 1,955 | 3.78125 | 4 | def read_cook_book():
cook_book = {}
cook_book_file_name = input('Введите название файла, где лежит книга рецептов: ')
with open(cook_book_file_name) as f:
while True:
dish_name = f.readline().strip()
if dish_name:
cook_book[dish_name] = []
num... |
8d538e4137a49cd2591721869b75fb4022308834 | cpingor/leetcode | /547.省份数量.py | 1,251 | 3.6875 | 4 | #
# @lc app=leetcode.cn id=547 lang=python3
#
# [547] 省份数量
#
# @lc code=start
class UnionFind:
def __init__(self, M):
self.father = {}
for i in range(len(M)):
self.father[i] = None
def find(self, x):
root = x
while self.father[root] != None:
root = s... |
7250d83b8a2c97c679118c2619e80e246d2158f2 | cpingor/leetcode | /1791.找出星型图的中心节点.py | 1,309 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=1791 lang=python3
#
# [1791] 找出星型图的中心节点
#
# https://leetcode-cn.com/problems/find-center-of-star-graph/description/
#
# algorithms
# Medium (80.64%)
# Likes: 5
# Dislikes: 0
# Total Accepted: 7.2K
# Total Submissions: 8.9K
# Testcase Example: '[[1,2],[2,3],[4,2]]'
#
# 有一个无向的 星型 图,由 n 个... |
01859508e4b130f513d46aa7523c02b879dff1a2 | cpingor/leetcode | /721.账户合并.py | 1,479 | 3.625 | 4 | #
# @lc app=leetcode.cn id=721 lang=python3
#
# [721] 账户合并
#
# @lc code=start
import collections
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def union(self, index1: int, index2: int):
self.parent[self.find(index2)] = self.find(index1)
def find(self, index: int) ->... |
a42616fae37499e939717c41c293680688f3bcb1 | bryanbeh/Coding-Bits | /IC Hack 2018/ml_disease.py | 3,625 | 3.71875 | 4 | # Mortality Rate model
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the dataset
dataset= pd.read_csv('ml_disease.csv')
x = dataset.iloc[:,:5].values
y = dataset.iloc[:,-2].values
print y
pd.DataFrame(dataset)
#Categorical Data
from sklearn.preprocessing... |
aa28d546c84fc8d420b7c4204ba4bb324e0ef7ca | khan-pog/all_practicals | /practical_3/password_checker.py | 787 | 3.90625 | 4 | """Module docstring"""
# imports
# CONSTANTS
MIN_LENGTH_OF_PASSWORD = 3
def main(): # DONE: ALL INSIDE MAIN FUNCTION
"""Function docstring"""
# varables...
password = get_password()
# statements...
if len(password) >= MIN_LENGTH_OF_PASSWORD:
print_asterisk(password)
else:
p... |
133c23391d22fd3a68d2e050af72c0511e1baaab | khan-pog/all_practicals | /practical_6/guitar_test.py | 908 | 3.875 | 4 | """ Test guitar
Creator: Khan Thompson
Date: 06/09/2021
"""
from practical_6.guitar import Guitar
gibson = Guitar("Gibson L-5 CES", 1922, 16035.40)
gibson.get_age()
print(gibson.get_age()) # Done.
print(gibson.is_vintage()) # Done.
print("My guitars!")
name = input("Name: ")
guitars = []
# Done.
while name != '':
... |
95a22b3bec1f5f7a5aa0111ba1f7a076e4911b99 | khan-pog/all_practicals | /practical_5/hex_colours.py | 971 | 4.03125 | 4 | """Hexadecimal colour lookup # DONE: CREATE A PROGRAM THAT ALLOWS YOU TO LOOK UP HEXADECIMAL COLOUR CODES."""
COLOUR_CODES = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7",
"AntiqueWhite1": "#ffefdb", "AntiqueWhite2": "#eedfcc",
"AntiqueWhite3": "#cdc0b0", "AntiqueWhite4": "#8b837... |
50f8832c2f1f020ec82bb90e2c6c7204ed0e561e | Manojna52/python_practice | /rrepeated_tuple.py | 176 | 3.671875 | 4 | from collections import Counter
x=(1,2,3,4,5,3,2)
a=list(x)
freq=dict()
freq=dict(Counter(a))
for item in freq:
if freq[item]>1:
print(item)
else:
pass
|
1c48b21164da452476dccac470c5615ddadbb863 | AnnaTashuk/Project1 | /s11.py | 434 | 3.875 | 4 | import re
def findSumReg(fileName):
"""
Returns amount of all numbers in the input file. Ignores letters, non-characters
like punctuation and spaces.
fileName: name of input file
returns: sum of all numbers
"""
return sum([int(num) for num in re.findall('[0-9]+',open(fileName).r... |
0fc854d7238f12e1cf625fb5d26ff101ca32d44a | hyeokjinson/algorithm | /ps프로젝트/알고리즘/3번.py | 540 | 3.703125 | 4 | from collections import deque
def solution(enter, leave):
answer = [0]*len(enter)
enter=deque(enter)
leave=deque(leave)
stack=[]
for i in range(len(enter)):
if enter[i]==leave[i]:
enter.popleft()
elif enter[i] in stack:
while True:
if enter[i]... |
7e8552f809d2102a77a0991bbabf40a0fa7af254 | hyeokjinson/algorithm | /ps프로젝트/str/나이순정렬.py | 244 | 3.578125 | 4 | if __name__ == '__main__':
n=int(input())
arr=[]
for i in range(n):
age,name=map(str,input().split())
arr.append((int(age),i,name))
arr.sort(key=lambda x:(x[0],x[1]))
for x,y,z in arr:
print(x,z)
|
56a736abb43922156a58a29f11bc73c669e3ac5f | hyeokjinson/algorithm | /그리디/거스름돈.py | 110 | 3.71875 | 4 | n=int(input())
coin_type=[500,100,50,10]
cnt=0
for coin in coin_type:
cnt+=n//coin
n=n%coin
print(cnt) |
83739ae5597e9731669dbd432df88ed8055d7ffb | hyeokjinson/algorithm | /ps프로젝트/str/ROT13.py | 486 | 3.9375 | 4 | if __name__ == '__main__':
s=input()
tmp=''
for x in s:
if x==' ':
tmp+=' '
elif x.isdigit():
tmp+=x
elif x==x.upper():
if 65<=ord(x)+13<=90:
tmp+=chr(ord(x)+13)
else:
tmp+=chr(ord(x)+13-90+64)
el... |
a01e7f12af7334e03f5c292c8d65fafea0d0a2e0 | hyeokjinson/algorithm | /dfs/bfs/bfs기초.py | 515 | 3.609375 | 4 | from collections import deque
def bfs(graph,start,visited):
q=deque([start])
visited[start]=True
while q:
v=q.popleft()
print(v,end=" ")
for i in graph[v]:
if not visited[i]:
q.append(i)
visited[i]=True
if __name__ == '__main__':
... |
51bf5c6a414fd4be2b1687cf3b20dff8fad54763 | hyeokjinson/algorithm | /deque.py | 355 | 3.78125 | 4 | from queue import Queue
class Deque(Queue):
def __init__(self):
self.input_data=[]
self.output_data=[]
def enqueue_back(self,item):
self.items.append(item)
def dequeue_front(self):
value=self.items.pop(0)
if value is not None:
return value
else:
... |
17fc46628b707243b760888a74ae7785f936bea9 | hyeokjinson/algorithm | /삼성기출/큐빙.py | 527 | 3.71875 | 4 | def rotate(area):
t,x,y,z,w=u,
if __name__ == '__main__':
T=int(input())
u=[['w']*3 for _ in range(3)]
d=[['y']*3 for _ in range(3)]
f=[['r']*3 for _ in range(3)]
b=[['o']*3 for _ in range(3)]
l=[['g']*3 for _ in range(3)]
r=[['b']*3 for _ in range(3)]
for _ in range(T):
n=... |
c83c80a5ae86d94eddaddfa6e6b6d1341a21d4b9 | hyeokjinson/algorithm | /ps프로젝트/DP/파도반 수열.py | 242 | 3.546875 | 4 | if __name__ == '__main__':
padovan=[0]*100
padovan[0:5]=1,1,1,2,2,3
t=int(input())
for i in range(6,100):
padovan[i]=padovan[i-1]+padovan[i-5]
for _ in range(t):
n=int(input())
print(padovan[n-1]) |
a94d7d1d1c5b7cff38d14d712d6d8cf39738d106 | aparrado/cs207_andres_parrado | /homeworks/HW3/Bank.py | 6,897 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 24 10:15:52 2020
@author: andresparrado
"""
from enum import Enum
class AccountType(Enum):
SAVINGS = 1
CHECKING = 2
class NotEnoughMoney(Exception):
pass
class NegativeAmount(Exception):
pass
class AccountError(Exception):... |
15ba68ba65bc99ac0376575155ff45e0c73659e5 | aparrado/cs207_andres_parrado | /homeworks/HW2/HW2-final/P5a.py | 615 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 6 12:38:32 2020
@author: andresparrado
"""
def make_withdrawal(balance):
init_balance = balance
print("Your initial balance is",init_balance)
def withdraw(withdrawal_amount):
if init_balance - withdrawal_amount < 0:
... |
f84fdef224b8a97d88809dcf45fb0f574dc61ed4 | SnarkyLemon/VSA-Projects | /proj06/proj06.py | 2,181 | 4.15625 | 4 | # Name:
# Date:
# proj06: Hangman
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on t... |
fee1d7c30aa228e4859f7a8e2031d4a431466916 | jaanos/zelvje-dirke | /zelva.py | 622 | 3.53125 | 4 | import turtle
class Zelva(turtle.Turtle):
"""
Splošna želva.
"""
def __init__(self, ime, barva='green', hitrost=1):
"""
Konstruira želvo z danim imenom, barvo in hitrostjo.
"""
turtle.Turtle.__init__(self)
self.ime = ime
self.color(barva)
self.sp... |
b9bcd87a3d6d7826a6a74da5c3b63059f6701515 | Anmol1696/klargest | /klargest/models.py | 2,510 | 3.984375 | 4 | """
Models for working with heapq for adding data and keeping track of k largest values
"""
import heapq
class KLargest:
"""
Implements a class to hold min heap of constant length
for k largest values and additional information as keys
Values, stored in `self.values` are the k largest values,
whi... |
c5eb6e78abf3f9844428fea2718aa096305df6fd | alexmehandzhiyska/softuni-python-basics | /05-while-loop/06-cake.py | 319 | 3.859375 | 4 | width = int(input())
length = int(input())
pieces = width * length
while pieces > 0:
command = input()
if command == 'STOP':
print(f'{pieces} pieces are left.')
exit()
pieces_eaten = int(command)
pieces -= pieces_eaten
print(f'No more cake left! You need {abs(pieces)} pieces more.') |
12578bebc71a9ea6b10205f8d0ae427ab4ba36ac | alexmehandzhiyska/softuni-python-basics | /04-for-loop/02-half-sum-element.py | 272 | 3.5625 | 4 | n = int(input())
max_num = 0
sum = 0
for i in range(n):
num = int(input())
if num > max_num:
max_num = num
sum += num
if max_num == sum - max_num:
print(f'Yes\nSum = {max_num}')
else:
print(f'No\nDiff = {abs(max_num - (sum - max_num))}') |
fb8bf25c92d07b7b70202eae995b7fe7d0217b08 | alexmehandzhiyska/softuni-python-basics | /06-nested-loops/02-equal-sums-even-odd-position.py | 372 | 3.75 | 4 | num1 = int(input())
num2 = int(input())
valid_nums = []
for num in range(num1, num2 + 1):
num_str = str(num)
sum_odd = int(num_str[1]) + int(num_str[3]) + int(num_str[5])
sum_even = int(num_str[0]) + int(num_str[2]) + int(num_str[4])
if sum_even == sum_odd:
valid_nums.append(num_str)
if len... |
59673e8c44bd1d903252869f4efa28448791cf60 | alexmehandzhiyska/softuni-python-basics | /03-conditional-statements-advanced/04-fishing-boat.py | 565 | 3.84375 | 4 | budget = int(input())
season = input()
fishers_count = int(input())
rent_prices = { 'Spring': 3000, 'Summer': 4200, 'Autumn': 4200, 'Winter': 2600 }
rent = rent_prices[season]
if fishers_count <= 6:
rent *= 0.9
elif fishers_count <= 11:
rent *= 0.85
else:
rent *= 0.75
if fishers_count % 2 == 0 an... |
f45eb498c0088ee757ea6c2a05d682f300f35100 | CristhianCastillo/introduction-computational-thinking-python | /edades_usuarios.py | 551 | 3.875 | 4 | def run ():
user_name_1 = input("USUARIO_1: Ingresa tu nombre: ")
user_age_1 = int(input("USUARIO_1: Ingresa tu edad: "))
user_name_2 = input("USUARIO_2: Ingresa tu nombre: ")
user_age_2 = int(input("USUARIO_2: Ingresa tu edad: "))
if(user_age_1 > user_age_2):
print(f'{user_name_1} es mayo... |
4055f749736fc7854a3035a60e8c98611cad0de9 | CristhianCastillo/introduction-computational-thinking-python | /abstraccion_funciones.py | 1,532 | 3.84375 | 4 | # Constants
EPSILON = 0.001
# Functions
def exhaustive_search(goal):
result = 0
while result ** 2 < goal:
result += 1
if result ** 2 == goal:
print(f"La raiz cuadrada de {goal} es {result}.")
else:
print(f"{goal} no tiene raiz cuadra exacta.")
def search_approximation(goal, e... |
39c50a39962f9e8e1b0412a6f911e4c08431853b | cheekclapper69/01_Lucky_Unicorn | /03_coffee.py | 1,003 | 3.96875 | 4 |
if token == "unicorn":
# prints unicorn statement
print()
print("***********************************************************")
print("***** Congratulations! it,s a ${:.2f} {}*****".format(UNICORN, token))
print("***********************************************************"... |
5bdd1fc2beb202a1ab028a3569900c3ab34367d3 | Quatroctus/cs362-git-activity | /password.py | 549 | 3.59375 | 4 | from random import choice, shuffle
def gen_password(n: int):
digits = "0123456789"
symbols = "!@#$%^&*()[]{}\|/?><,.`~"
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()[]{}\|/?><,.`~0123456789"
a = []
if n > 2:
a.append(choice(digits))
a.append(choice(symbo... |
eea72a173f8ca1ed7025bfb5548068ee1fb56603 | dorishay1/Demographic_Data_Analyzer_python_freecodecamp | /demographic_data_analyzer.py | 4,443 | 4.1875 | 4 | import pandas as pd
def calculate_demographic_data(print_data=True):
# Read data from file
df = pd.read_csv('adult.data.csv')
# How many of each race are represented in this dataset? This should be a Pandas series with race names as the index labels.
race_count = df['race'].value_counts()
# What... |
d7736ee0897218affa62d98dbb4117ff96d59818 | djmgit/Algorithms-5th-Semester | /FastPower.py | 389 | 4.28125 | 4 | # function for fast power calculation
def fastPower(base, power):
# base case
if power==0:
return 1
# checking if power is even
if power&1==0:
return fastPower(base*base,power/2)
# if power is odd
else:
return base*fastPower(base*base,(power-1)/2)
base=int(raw_input("Enter base : "))
power=int(raw_i... |
ec12c6c77432475f71ae4f7efb6ef4fc0d80cbcf | KrishanSritharar2000/Modelling-Quantum-Gravity | /turtle/Grid.py | 2,643 | 3.96875 | 4 | #Grid
import turtle
from Main2 import *
pen = turtle.Turtle()
turtle.delay(0)
pen.ht()
turtle.colormode(255)
turtle.tracer(0,0)
def grid(col, row, len_th, mode, coordinates):
width = turtle.window_width()
height = turtle.window_height()
x1 = round((0)- ((col/2)*len_th),0)#These two lin... |
0f40ebd07a5dbce3f230fc2a22ff9b488be6d2b4 | KrishanSritharar2000/Modelling-Quantum-Gravity | /turtle/scipySim2.py | 18,044 | 3.5 | 4 | #Krishan Sritharar
#Random Walks
import random
import turtle
from scipy import spatial
from Grid import *
pen = turtle.Turtle()
turtle.delay(0)
pen.ht()
turtle.colormode(255)
turtle.tracer(0,0)
def setup():
fullScreen()
noLoop()
def point(x,y):
pen.up()
pen.goto(x,y)
... |
719112abb89b446104833235b2022c0a5ed3ad49 | kingspider/CodinGame | /MIME Type.py | 884 | 3.875 | 4 | import sys
import math
minemap = {}
mineext = []
def extension(filename):
""" Function takes a filename reverses it and then gets the extension. """
fileextention = ""
for char in filename:
if char == ".":
fileextention = fileextention[::-1]
return fileextention.lower()
... |
47f8774a796e018036c88eadc8b9f8bfbf20348f | JoanMora/UCD-Data-Science-in-Python | /Introduction to Data Science/Lab/overlap.py | 332 | 3.5625 | 4 | import sys
def parseData(File):
try:
f = open(File, "r")
num = set()
for number in f.readlines():
num.add(number.strip())
f.close()
except FileNotFoundError:
print("Warning: File not found")
return num
file1 = parseData(sys.argv[1])
file2 = parseData(sys.argv[2])
print("Overlap: ", file1.intersect... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.