blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cafed9495b95ff84fc5cfd9f090b679acac9caed | akidescent/GWC2019 | /challenge.py | 578 | 4.3125 | 4 | #imports the ability to get a random number (we will learn more about this later!)
from random import *
#Create the list of words you want to choose from.
aName = ["Mary", "Patricia", "Jennifer", " Linda", "Elizabeth", "Barbara", "Susan", "Karen", "Nancy", "Margaret", "Lisa", "Betty", "Dorothy", "Sandra", "Ashley", "K... |
5daa142c69163b5977e1aac69254ca081db3d30c | Thejoker2012/ExerciciosPython | /Desafio012.py | 286 | 3.828125 | 4 | print('========================================Desafio012============================================')
preco = float(input('Digite o preço do produto: '))
desc = preco*0.05
novoPreço = preco - desc
print('O preço é R${} e com desconto de 5% é R${:.2f}'.format(preco, novoPreço)) |
dcee1e24d22558dd42dc01ff43caa4e1b17af100 | abhatia05/Udemy---Colt-Steele-Modern-Python-Bootcamp-Codebook | /10. Loops/88. while_loops_password.py | 1,831 | 4.34375 | 4 | # 88. while_loops_password.py
# Use Case 1 : To check if a given password is correct or not
# msg = input("What is the password ? ")
# while msg != "minion_bannanaa":
# print("Uhh Oh...! Wrong Password.")
# msg = input("What is the password ? ")
# continue
# print("~~~~~~~YeeeHaw...! ^_^ Correct... |
78711ea9e66e8b3ba41f8f9e01546630ca590215 | zihuaweng/leetcode-solutions | /leetcode_python/855.Exam_Room.py | 1,041 | 3.734375 | 4 | #!/usr/bin/env python3
# coding: utf-8
# https://leetcode.com/problems/exam-room/
# Time complexity: O(n)
# Space complexity: O(n)
class ExamRoom:
def __init__(self, N: int):
self.seats = []
self.last = N - 1
def seat(self) -> int:
# print(self.seats)
if not self.seats:
... |
09f64ae611e76776e4c645d6bafaa42a2edebbe1 | Kvn12/MC102 | /Lab13.py | 2,358 | 3.9375 | 4 | from math import log2
def divisao(dicio, base, altura, i):
'''Calcula quantas vezes uma potencia de dois cabe em determinado espaço, delimitado pela base e altura, e calcula recursivamente\
para outras potencias de dois menores que a inicial, de modo a cobrir todo o espaço com quadrados de largura iguais a pot... |
13c68718495f942724fa5b5d30d8a4873e240926 | jacobgarcia/code-interviews | /py/js_interviews/sportradar/stack_implementation/stack_implementation.py | 575 | 3.765625 | 4 | class Node():
data = None
next = None
def __init__(self, data):
self.data = data
class Stack():
top = None
next = None
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
if (self.top is not None):
... |
4efc7ff2c352ab64304264a694e64fe35b9c887b | uminho-miei-engseg-19-20/Grupo1 | /aula11/safe.py | 2,183 | 4.09375 | 4 | #Programa em Python para o trabalho prático 11
import re, string
while True :
#inserção do valor pelo utilizador
valor = input("\nInsira valor a pagar (no formato xx(...)xx.xx): ")
#verificação do valor inserido
if not re.match("[0-9]{2,20}(\.[0-9][0-9])?$", valor) :
print("Inseriu um valor errado!")
else :
... |
99b4b29de2358adf97bec6b1ae304d1dca6ccceb | helenthai/Turtle-Charter | /turtle-charter.py | 6,849 | 4.1875 | 4 | def read_data(file_path, feature=1):
"""
(1) This function will read the given file
(2) Arguments: an input file
(3) The returned value: a dictionary {label:data}
"""
data = {}
lable = []
value = []
lines = open(file_path, 'r').readlines()
print("Content: \n")
print(lines)
... |
2156469746b076d4e25102d0e58c4cbbb6cd1ae0 | n0ppp/Implementasi-Integrasi-Aplikasi-Tix-Id-x-Dana | /dana.py | 5,110 | 3.546875 | 4 | '''
1. Saldo waktu awal daftar dihilangin
2. Tambah tabel history transaksi (+ waktu topup, - waktu transaksi)
'''
# Library yang digunakan agar program python dapat menggunakan database mysql
import mysql.connector
# Melakukan koneksi ke database ais_dana
mydb = mysql.connector.connect(
host="localhost",
user="... |
389ba615018782131be539f3ba6a8c38e711727f | AdityaBachal/Casino-7-Up-7-Down-Game | /Casino 7 Up 7 Down Game.py | 4,051 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import time
from random import randint
money = int(input("Welcome you, 7 Up 7 Down is a dice game which is played by betting on numbers more than 7 or less than 7.\nTwo dies are rolled in the game and if addition of numbers on both the dices matches your bet then the ... |
2f9aefff07f0e08a5dd225575a4c98651ebfa456 | EduChancafe/EduardoCH | /condicionalesmultiples/ejercicio3.py | 736 | 3.5 | 4 | import os
#declarar variables
cliente,numeros_de_zapatillas,precio_de_zapatilla="",0.0,0.0
verficador= False
#input
cliente=os.sys.argv[1]
numeros_de_zapatillas=int(os.sys.argv[2])
precio_de_zapatilla=float(os.sys.argv[3])
#processing
costo_zapatilla=(numeros_de_zapatillas*precio_de_zapatilla)
verificador=(costo_zapa... |
881bd355aa2ea0d078a888d292a15edcc7467390 | parimisankar/Machine-Learning | /Machine Learning using Python and R/Part 2 - Regression/Section 5 - Multiple Linear Regression/Multiple_Linear_Regression/multiple_linear_regression.py | 2,659 | 3.96875 | 4 | # Multiple Linear Regression
# Data Preprocessing
# 1. Importing the libraries
import numpy as np # Contains mathematical tools
import matplotlib.pyplot as plt # Contains plotting tools
import pandas as pd # Contains dataset import/manage tools
# 2. Importing the dataset
dataset = pd.read_csv('50_Startups.csv')
# 3.... |
fbaeba4d9c6e5f7cafe055087c0e850585ed658a | therikb31/Hospital_Database_Management_Python | /9.py | 137 | 4.0625 | 4 | def factorial(x):
if x==1:
return 1
return x*factorial(x-1)
n=int(input("Enter number:"))
y= factorial(n)
print y
|
9b6e801c4616ece0637af96845e1f53fc4ba74f3 | MyaGya/Python_Practice | /SW_Expert_Academy/Sorted_Solution.py | 952 | 3.640625 | 4 | #파이썬의 정렬 방법에 대한 기초적인 방법을 알아보자
from operator import itemgetter,attrgetter
data = [1,5,3,7,9,0,54,30,29,10]
#1. 기본 출력
print("1: " + str(data))
#2. 오름차순 정렬
data.sort()
print("2: " + str(data))
#3. 내림차순 정렬
data = sorted(data, reverse=True)
print("3: " + str(data))
#4 다중 배열 관련 정리
student = [
('john', 'A', 15),
... |
b0bc38477a088832fe1fefa2951485d80d7fcc76 | gus07ven/CCIPrac | /Stack.py | 1,192 | 4.28125 | 4 |
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return True if len(self.stack) == 0 else False
def push(self, data):
if data not in self.stack:
self.stack.append(data)
return True
else:
return False
def peek(se... |
b5ac25cbe00df82f793bcbcaf599b6aa9d76984f | ashcolecarr/Euler-in-Python | /Problems 1-50/problem041.py | 1,037 | 3.765625 | 4 | # Project Euler Problem 41
import time
from math import sqrt
startTime = time.clock()
# Pandigital numbers are divisible by 3 except for 1234 pandigital and 1234567 pandigital.
MAX = 7654321
# The problem already gives this number so it cannot be lower than this.
MIN = 2143
def isPandigital(n):
number = str(n)
... |
4107d481d0c6c81d5c2601006864f602e7be20cd | Aanjansai/Python-Programs | /algorithms/monthly_payment.py | 518 | 4.125 | 4 | """ Write a Util Static Function to calculate monthlyPayment that reads in three command-line
arguments P, Y, and R and calculates the monthly payments you would have to make over Y years
to pay off a P principal loan amount at R per cent interest compounded monthly."""
principal = float(input("enter the p... |
fbf14423e8e276d989bb425af6a79352d0047b99 | akanksha470/Connect-4 | /connect.py | 4,413 | 3.640625 | 4 | import numpy as np
import pygame
import sys
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
ROWS = 6
COLS = 7
def create_board():
board = np.zeros((ROWS, COLS))
return board
def draw_board(board):
for c in range(COLS):
for r in range(ROWS):
pygame.d... |
bb1e1e78462a23c13d5cd1a2c690c484cd963a7f | Soundwavepilot1969/Udemy_Art_of_Doing | /App8_Gravity_Simulator/app8_gravity_simulator.py | 8,268 | 3.6875 | 4 | #Gravity Simulator
import tkinter, matplotlib
from tkinter import BOTH,HORIZONTAL,CURRENT, END
from matplotlib import pyplot
root=tkinter.Tk()
root.config(bg="#D4F1F4")
root.title("Gravity Sim")
# root.geometry('600x650')
root.resizable(0,0)
img = tkinter.PhotoImage(file=r"D:\All_Git_Projects\Udemy_Art_of_Doing\App8_... |
6b9008dac89fd99130a78e6071b7ab80f032b1c7 | navanith007/github-actions-demo | /hello.py | 147 | 3.8125 | 4 | def add(x, y):
"""
This function adds the two numbers
:param x:
:param y:
:return:
"""
return x + y
print(add(1, 2))
|
6d68f6fd88c78477eafb925471db04494e2502a2 | basanneh/python_DataStructures | /fibonacci.py | 494 | 4.125 | 4 | def fibonacci_recursion(num):
if num < 0:
print("please enter a positive number")
return
if num <= 1:
return num
else:
return fibonacci_recursion(num -1) + fibonacci_recursion(num -2)
F = [-1]*50 #array to store fibonacci terms
def dynamic_fibonacci(n):
if (F[n] < 0):
... |
ded46f75e5436daaa7050381de1bd63fcbd07b24 | neeraj-somani/Python_Algos | /Leetcode-Arrays-101/FindAllNumbersDisappearedinanArray.py | 1,814 | 4.34375 | 4 | # Lets follow our procedure to solve this question:
'''
Definition - can be understood from question (https://leetcode.com/explore/learn/card/fun-with-arrays/523/conclusion/3270/)
Data -
- Input - a array that contains some intergers
- output - return third maximum number in array
- Edge case - number can vary f... |
eeee0aa943ba4a4864efae6351a9c3445989de15 | evelinacs/semantic_parsing_with_IRTGs | /code/analyse_input/type_finder.py | 592 | 3.671875 | 4 | import sys
import re
from collections import defaultdict
""" Finds and counts the types of phrase structures.
Should be used on the output of
code/generate_input_from_trees/extract_subtrees.py, like this:
python3 type_finder.py input_file | sort -n -r
"""
def type_finder():
replacer = re.compile(r"[a-zA-Z]+\)")
... |
6e119b5c4c071fbb6208e6be0ead15461f72a1ff | battle-test/basic-algorithm | /best_pratice/algorithm/binary_search.py | 650 | 3.84375 | 4 | import random
def binary_search(N, arr):
if len(arr) == 0:
return 0
left =0
right = len(arr)
while left < right:
middle = (left+right) // 2
if arr[middle] < N:
left = middle + 1
else:
right = middle
return left
def generate_data(N,l):
st... |
cb8c9104e00332265aed59e5ac1260726f0c9be8 | jcheung0/problemsolving | /ispalindrome.py | 313 | 3.5625 | 4 |
def isPalindrome(value):
numberVals = {};
for i in value:
temp = numberVals.get(i)
if temp:
numberVals[i] = numberVals[i] + 1
else:
numberVals[i] = 1
for i in numberVals:
print str(i) + ':' + str(numberVals[i])
isPalindrome("hello")
|
ee0a3fcbdcc01c437f778cae217f54a3f276c299 | tmjnow/kmooc-python | /lab_6/factorial_calculator.py | 1,638 | 4.3125 | 4 | # -*- coding: utf-8 -*-
import math
def get_factorial_value(integer_value):
return math.factorial(integer_value)
def is_positive_number(integer_str_value):
# '''
# Input:
# - integer_str_value : 숫자형태의 문자열 값
# Output:
# - integer_str_value가 양수일 경우에는 True,
# integer로 변환이 안되거나, 0, 음수일... |
075d10fc80ecad5d69406b896c23f965e4ea6129 | ShianLin/python_data_structure | /week3/try.py | 5,100 | 3.5625 | 4 | '''
class Solution:
def isValid(self, s: str) -> bool:
dic = {'{': '}', '[': ']', '(': ')', '?': '?'}
stack = ['?']
for c in s:
if c in dic:
stack.append(c)
elif dic[stack.pop()] != c:
return False
return len(stack) == 1
#作者... |
7dcce0da8fbdc3e7b072610914f83e47d76de5bc | hat20/Python-programs | /str_length.py | 156 | 4.125 | 4 | print("Computing length of string")
a = str(input("Enter a string"))
i = 0
a = a + ' '
while a[i] != ' ':
i= i+1
print("Length of the string is",i)
|
177629d45ab36b7797c340532133807acdd34863 | HenkT28/GMIT_Programming_Scripting | /squareroot.py | 576 | 4.5625 | 5 | # Write a program that that takes a positive floating point number as input and outputs an approximation of its square root.
# Verbatim: https://www.geeksforgeeks.org/python-math-function-sqrt/
# https://www.programiz.com/python-programming/examples/square-root
# https://docs.python.org/3/tutorial/floatingpoint.html
n... |
49265888d286916e3542bdffb29d0110cbf440e0 | TODUR/stepik-python | /solutions/week-1/malevia_livingarea.py | 494 | 3.8125 | 4 | figure = str(input())
if figure == "треугольник":
a = int(input())
b = int(input())
c = int(input())
p = float((a + b + c) / 2)
S = float((p * (p - a) * (p - b) * (p - c)) ** 0.5)
print(S)
elif figure == "прямоугольник":
a = int(input())
b = int(input())
S = float(a * b)
print(S)... |
6bde50277cdb93b001d029946a3531b397d67dcf | ancylq/design_patter | /command.py | 1,938 | 3.734375 | 4 | #!/usr/bin/env python
#coding:utf-8
'''
命令模式
模式特点:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排
队或记录请求日志,以及支持可撤销的操作。
程序实例:烧烤店有两种食物,羊肉串和鸡翅。客户向服务员点单,服务员将点好的单告诉大厨,
由大厨进行烹饪。可以进行点单、增加烤串和撤销。
代码特点:无。
注:在遍历时不要用remove,会出现bug。因为remove打乱了for迭代查询列表的顺序。
'''
class Barbecue(object):
def make_mutton(self):
'''烤羊肉串'... |
8fb75e6ed98e46f122625eaafc5877c17440ac64 | Nayald/algorithm-portfolio | /leetcode/daily challenges/2020-12/24-swap-nodes-in-pairs.py | 571 | 3.609375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy = ListNode(None, head)
p1 = dummy
p2 = head
while p2:
... |
8b2ba5bcdb50c92dfd1f73f18c724d45270b1c14 | grisha-dd/python | /lesson-3/3.2.py | 304 | 3.5625 | 4 | def user_info(**kwargs):
for key, value in kwargs.items():
print("{} is {}. ".format(key, value), end="")
user_info(Firstname=input("Firstname: "), Lastname=input("Lastname: "), Birthyear=input("Birthyear: "),
City=input("City: "), Email=input("Email: "), Phone=input("Phone: "))
|
4ce9d7e04007e70ce9115bfd417087b1942c1241 | YuriiPaziuk/leetcode | /divide and conquer/218. The Skyline Problem.py | 1,813 | 3.65625 | 4 | """
https://leetcode.com/problems/the-skyline-problem/description/
https://briangordon.github.io/2014/08/the-skyline-problem.html
"""
def critical_points(buildings):
import heapq
xi = [building[0] for building in buildings]
xi += [building[1] for building in buildings]
heapq.heapify(xi)
ret... |
3f2059de4581d31e9cff76b8c5c31ee26f10d342 | godinhok/PythonFuelManagement | /MainProgram.py | 1,512 | 3.84375 | 4 | from promptInput import inputPrompts
from UserInputFile import csvFileInputOutput
from AircraftFinder import AircraftFinder
from AirportAtlas import AirportAtlas
from CurrencyCodes import CurrencyDict
from ExchangeRates import ExchangeRates
# Main driver program which asks user for options of file-reading or manual in... |
e79b8cbbc744425db1cf2c24f410fa9f101749b5 | huggins9000211/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 524 | 3.796875 | 4 | #!/usr/bin/python3
"""
text indentation
"""
def text_indentation(text):
""" text indentation """
justFound = False
if not isinstance(text, str):
raise TypeError("text must be a string")
for x in range(0, len(text)):
if text[x] in ['.', '?', ':']:
print(text[x], end="\n\... |
2cc9d68a617d99a4ee27d7ee70cd62075a854c64 | shuxiangguo/Python | /Learn/spider/21DaysOfDistributedSpider/ch02/demo1.py | 279 | 3.5 | 4 | from urllib import parse
url = "http://www.baidu.com/s;hello?wd=python&password=123#a"
# urlparse和urlsplit的区别在于params url里;he ?之间的内容
result = parse.urlparse(url)
result2 = parse.urlsplit(url)
print(result)
print(result2)
print("netloc", result.netloc) |
2fbc2eaec3baa3f19b3c8afe0026046dd7b7c348 | rahulrj/MTV | /HackerRank/STRINGS/MORGANANDSTRING.py | 555 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
test=(int)(raw_input());
for i in range(0,test):
string1=[]
string2=[]
value=[]
count=0
string1=raw_input();
string2=raw_input();
string1=string1+'z';
string2=string2+'z';
length=len(string1)+len(string2)-2;
fo... |
a73ce37fa25f776cd8e9c363ba5badf6cd02ae5a | geekhub-python/strings-Elfpkck | /8.py | 207 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
s = input('Enter the string: ')
count_f = s.count('f')
if count_f == 1:
print(s.find('f'))
elif count_f > 1:
print(s.find('f'), s.rfind('f'), sep='\n') |
17b6917d40f5476673855037118135d3234da40c | krutik710/Python-Assessment | /Python/binary_search.py | 756 | 3.984375 | 4 | def binarySearch (l, l, r, x):
# Base Case
if r >= l:
mid = int(l + (r - l)/2)
# Element present at the middle itself
if l[mid] == x:
print("Element Found At Index", mid)
# Element smaller than mid, find left subarray
... |
707bf27cea991dfd9fec25d98e5822043ddc7626 | Jackie1995/leetcode_answers | /linkedList_Part/leetcode83.py | 2,039 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 15 21:08:09 2018
@author: jikang
"""
class ListNode(object):
def __init__(self,val,next_node = None):
self.val = val
self.next = next_node
def getDummyNode(node_val_list):
"""
node_val_list: list or tuple
returnType: ListNode
... |
bf014330ab5cebaa3f3e496a6c1ba902bd4ffb44 | StepicOrg/submission-complexity | /tests/code/python3/protocols.py | 2,158 | 3.5 | 4 | """Abstract Protocol class."""
__all__ = ['BaseProtocol']
class BaseProtocol:
"""Common base class for protocol interfaces.
Usually user implements protocols that derived from BaseProtocol
like Protocol or ProcessProtocol.
The only case when BaseProtocol should be implemented directly is
write-... |
271d5e65a74bd45c251301eb9764ac1b2d1205bf | NoelArzola/10yearsofPythonWoot | /projects/tax-calc.py | 2,417 | 4.09375 | 4 | # grab the type of transaction
print()
payment_type = input('Is this an Invoice, Reader, or a Card On File? ')
if payment_type.lower() == 'invoice':
# the amount you want to be paid for your work
print()
amount_desired = input('How much do you want to be paid? $')
print()
# current tax rate is 15%,... |
0ee3358390c0d37c2a7bf188c4f02cc729597e58 | franri/python-turtle-examples | /oblignegro.py | 3,071 | 3.546875 | 4 | import pickle
import random
PUNTAJE_GLOBAL = 5000
def obtener_opcion():
print('Seleccione una opción:')
print('\t1. Jugar nueva partida.')
print('\t2. Mostrar un ranking histórico de jugadores, ordenado por cantidad de partidas ganadas de mayor a menor.')
print('\t3. Mostrar el "máximo puntaje de todo... |
92b81c67e17433e205607286c9ca900523f216f2 | hermetico/string-algorithms-2016 | /Project 3/tools/fibonacci_strings.py | 948 | 4.0625 | 4 |
class FibonacciStrings(object):
def __init__(self, first='b', second='a'):
self.first = first
self.second = second
def generate(self, count=-float('inf'), length=-float('inf'), **kwargs):
if kwargs:
self.__init__(**kwargs)
if count == 0:
return self.fir... |
932235f3693f41e9480053c32f75ae1362cf7ebd | raghu-icecraft-fullstack/python-word-count-illustration | /package_1/classes.py | 1,921 | 3.671875 | 4 | '''
Author: Gautam Gadipudi
'''
from package_1.util import read_file
class WordCounter:
_slots = ["file", "counter"]
def __init__(self, file: str):
'''
Constructor
'''
# set the file property
self.file = file
# set the counter property
self.cou... |
396ace5dbc39b42b712ff667ccfdca35c8c0d85e | himichael/LeetCode | /src/701_800/0707_design-linked-list/design-linked-list.py | 3,360 | 4.15625 | 4 | class Node(object):
def __init__(self,val):
self.val = val
self.next = None
class MyLinkedList(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 0
self.dummy = Node(-1)
def print_info(self,info):
... |
9f634a1f6db63807ffe6d4223098eb4bd5f990f3 | gatlinL/csce204 | /Exercises/March4th/birthdays1.py | 684 | 3.921875 | 4 | # Author: Gatlin Lawson
from datetime import date, time, datetime
birthdays = [date(2021, 3, 22), date(2021, 2, 20), date(2021, 5, 29),
date(2021, 11, 21), date(2021, 10, 22), date(2021, 3, 2),
date(2021, 6, 24)]
closestBirthday = date(2021, 12, 31)
for birthday in birthdays:
... |
7091630f746a358b2fbc0a5cbe767d305f5247fb | manhducpham/phamducmanh-fundamental-c4e21 | /thinkcspy/chapter_3/ex_6.py | 183 | 4.0625 | 4 | n = int(input("Please enter the number of angles: "))
from turtle import *
shape("turtle")
# background("lightgreen")
for i in range(n):
forward(100)
left(360/n)
mainloop() |
11c5e7954ead331c8ff56155f4e86fc8b12a326e | cameradias/ApproxFileSize | /Input.py | 182 | 3.90625 | 4 | def inputInt():
while (True):
try:
return int(input("Enter size in bytes (-1 to quit): "))
except ValueError:
print("Enter only integers") |
f42dc3ee2e182c1303b26d9fe830f0ec8de91c31 | jeromeslash83/My-First-Projects | /random_stuff/Silent_bidding.py | 687 | 3.625 | 4 | from replit import clear
import art
bidder = True
bids ={}
while bidder == True:
print(art.logo)
name = input('What is your name? ')
your_bid = int(input('What is your bid? $'))
move_on = input("Are there any other bidder? 'yes' or 'no'\n")
def new_data (person, money):
bids[person] = money
if move... |
6352d53d7e7114f63b038c8aefbc57ec9e3d5317 | monoidic/silly-scripts | /fib.py | 823 | 3.734375 | 4 | #!/usr/bin/env python3
def get_fib_period(m):
period = []
previous, current = 0, 1
while True:
period.append(previous)
previous, current = current, (previous + current) % m
if previous == 0 and current == 1:
break # period found
return period
def fib_sum_slow(n, m):
total = 0
previous... |
9e168a22b5aca7f429f154ffe3ae8603f0566ae8 | lenamax2355/EDA | /build/lib/EDA/spread.py | 10,401 | 3.65625 | 4 | import inspect
from pandas import DataFrame, Series, concat
from EDA import if_to_csv, if_to_html, if_display, del_non_numeric, create_directory
_prefix = 'sp_'
def calculate_max_and_min(dataframe, *args, display=True, to_csv=False, to_html=False) -> DataFrame:
"""
This function calculates the maximum and ... |
05eb805be932a00118bd53a5e015c34950459ba3 | Green0v0/Algorithm | /Woosang/Greedy/04_만들_수_없는_금액.py | 1,009 | 3.625 | 4 | from itertools import combinations
n = 5
coins = [3, 2, 1, 1, 9]
add_set = set(coins) # 중복 제외
x = 2 # n개까지 모든 조합
while x != n:
# 모든 조합을 만들어 비교(완전탐색)
for i in set(combinations(coins, x)):
add_set.add(sum(i))
x += 1
# 가장 적은 숫자 반환
for i in range(1, max(add_set)):
if i not in add_set:
an... |
c0644ac9a95abbed70ecfb1ef520f40ac0998c1d | djanlm/Curso-Em-V-deo---Python | /Mundo 3/ex079_valoresUnicosEmUmaLista.py | 348 | 4.03125 | 4 | lista = []
while True:
valor = float(input("Digite um valor: "))
if valor not in lista:
lista.append(valor)
else:
print("Valor duplicado! Insira outro número...")
user = str(input("Quer continuar? [s/n]")).strip().lower()
if user[0] == 'n':
break
lista.sort()
print(f"Você dig... |
78c9b7a5bd1c23ec862edb1650e6ae7c07efab9c | isk02206/python | /informatics/previous/sungjoonpark/series_09/tansitions_and_transversions.py | 1,910 | 3.53125 | 4 | def transitions(a,b):
'''
>>> transition('G', 'A')
True
>>> transition('t', 'g')
False
>>> transition('C', 'c')
False
'''
a = a.lower()
b = b.lower()
if a == 'a' and b == 'g':
return True
if a == 'g' and b == 'a':
return True
if a == 'c' and b == 't':
... |
d8cec1706bfe0f6fb77d243ed599c9c9e14a17b6 | arunajasti/python_programs | /TypesOfVariablesInOOPS/Static Variables/Employee.py | 600 | 3.78125 | 4 | #we can Access static variables by using className or obj ref
class Employee:
company = 'Amazon' #static/class variables
def __init__(self,name,address):
self.name = name
self.address = address
def showDetails(self):
print("Emp details: ",Employee.company,self.name,self.a... |
2cab88517ed7b3cd24493bc19a8ebed79ad9cd43 | ametaxas/HW-5 | /HW-5.py | 178 | 3.71875 | 4 | import re
file_name = input('Enter the file name:')
nums_str = re.findall(r'[0-9]+', open(file_name, 'r').read())
nums_int = [int(num) for num in nums_str]
print (sum(nums_int)) |
33a43bfcea9c2a4738b623beafb700c7f1359b78 | swift-student-lambda/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 1,389 | 4.5625 | 5 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
# The simple solution would involve calculating the max
# for the whole window, looking at each visible value at each step of the way
# We co... |
7c81b2d9413be99811100709ba2cd84fefba6680 | bizzytay/Python-Projects | /Cars.py | 2,292 | 3.921875 | 4 | #Taylor Herrera 2/12/2017
#Requires data.txt file
"""Read in a file of cars with json and categorize each car. Calculates the average of the odometer."""
import json
#class car that has attributes of year, make, odometer and the status
class car:
def __init__(self,year=0,make="",odometer=0):
self._year ... |
19d53fbc8c6fd7a93714ca01c150e1231552e5e1 | Rupam-Shil/Python-Beginners-to-Pro | /Sequences/myprac.py | 588 | 3.625 | 4 | # a = "my name is rupam shil"
# print(a)
# list = a.split()
# print(list)
# print(a)
# b = [
# "8", "9", " ",
# "9", "0", "4", " ",
# "6", "7", " "
# "0", "3", "2",
# ]
# sorted_b = "".join(b).split(" ")
# print(sorted_b)
#
# for index, item in enumerate(sorted_b):
#
# sorted_b[index... |
f04d0a26fa6eabf4eeaba40db979104893217f1d | MastersAcademy/Programming-Basics | /homeworks/olha.bezpalchuk_olhabezpalchuk/homework-6/Cake.py | 615 | 3.609375 | 4 | class Cake(object):
def __init__(self, name, ingredients, price):
self.name = name
self.ingredients = ingredients
self.price = price
self.cooking_method = "Default method: just mix all ingredients." + str(self.ingredients)
def __str__(self):
return "Cake %s, %.2f\n" % (s... |
130c3e4b05027de3c7feca249416c3fa20ab2be5 | Avangarde2225/firstPythonProject | /jukebox.py | 268 | 3.734375 | 4 |
from Tuples.nested_data import albums
while True:
print("Please choose your album(invalid choice exists):")
for index,(title,artist,year, songs) in enumerate (albums):
print("{}: {}, {}, {}, {}".format(index+1, title ,artist, year, songs))
break |
ecd159de9763b5466c32cb2938de53f4676faafb | LuanCantalice/CaixaCores | /CaixaCores/CaixaCores.py | 1,017 | 3.8125 | 4 | cores = []
def AdicionarCor():
cor = input( "Você deseja adicionar qual cor? ")
cores.append(cor)
print("Nova cor adicionada:", cor)
def ListarCores():
print("As cores adicionadas são:")
for a in cores:
print(a)
def ExibirMenu():
perg = input("Você deseja adicionar mais a... |
42bb64a5d62d3b08e9a7ceb92fec4760549f38ea | JJThi0/ODE-analyzer | /ODE/Examples/Lorenz/Example_Lorenz.py | 1,951 | 3.609375 | 4 | import numpy as np
from ODE import ODE1
from functions import differential_equations, Interval_Generators
import matplotlib.pyplot as plt
#TO DO:code more ode's in differential_equations, write test cases
#define some constants for Lorenz ODE
a = 10.0
b = 8.0/3.0
r = 28.0
#define some constants for dampe... |
3a483f9f2356aa4717b4907f580d15e358d24651 | qiudebo/13learn | /code/pandas/pandas-demo.py | 6,107 | 3.546875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Numpy 提供了十分方便的数组处理功能,但缺少数据处理和分析的功能。
# Pandas 基于Numpy开发,提供更多的数据处理和分析的功能。
# Seires 和 DataFrame 是 Pandas 中最常用的两个数据对象。介绍这两个数据对象的基本概念和常用属性。
# 数据对象 Series,由index和values组成,下标存取:使用位置、索引标签
# DataFrame 对象
s = pd.Series... |
c355010d4e4885d2d513126586d65b0f3d70859f | Aasthaengg/IBMdataset | /Python_codes/p03567/s020031026.py | 170 | 3.703125 | 4 | s = input()
flag = True
for i in range(len(s)-1):
if s[i] == 'A' and s[i+1] == 'C':
if flag:
print("Yes")
flag = False
if flag:
print("No")
|
b51120e5c8c6ddd06a53c0799b58d5c8ced21e93 | rockman/learn-python-fluent | /test_snippets.py | 779 | 4.125 | 4 |
# testing Python features from various snippets of the book
def test_for_else():
flag = False
for _ in range(10):
pass
else:
flag = True
assert flag
for i in range(10):
if i > 5:
break
else:
assert False
def test_while_else():
flag = False
... |
5ccdb2c99fd4622d61e39ecdde2fff33e5033222 | Ranjani94/Leetcode_Problems | /leandata.py | 705 | 3.71875 | 4 |
class Student:
def __init__(self, id, name):
self.id = id
self.name = name
# name = 'Jack' -> 'John'
def populate():
NumberOfCourses = getCourses()
NumberOfClubs = getClubs()
studentList = getStudents() # ['Mary','John', 'Jack']
studentList[1] = 'Ross'
SaveToDatabase(st... |
00dcd2d98bbe4d55990d3fafe51c54c3d9cf9948 | yannyyss/python101 | /src/read_write_csv.py | 1,168 | 4.0625 | 4 | import csv
#Read a CSV ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#!!! Creta the given file first !!!
with open("software.csv") as software:
#Command user to read as a dictionary
reader = csv.DictReader(software)
for row in reader:
prin... |
bc28473b1cabaca0efcdc136ab4cf6c46ff981bc | pstrinkle/misc-umbc | /graduate/CMSC621 - Advanced Operating Systems/cs621-prj1/erlang/results/process_gossip.py | 1,196 | 3.515625 | 4 | #!/usr/bin/env python
import os
import fileinput
import sys
import re
msgCount = 0
badMsg = 0
knowdonttell = 0
dontknow = 0
def process_file(path):
"""This function processes the file!"""
global msgCount
global badMsg
global knowdonttell
global dontknow
global knowandtell
nodeset = {}
... |
0c4f99871e457d8b2884dd5c8aa722889f76a74f | ricky4235/Python | /Book/Ch05/Ch5_2_4b.py | 320 | 3.5625 | 4 | from bs4 import BeautifulSoup
from bs4.element import NavigableString
with open("Example.html", "r", encoding="utf8") as fp:
soup = BeautifulSoup(fp, "lxml")
tag_div = soup.find(id="q1")
for element in tag_div.previous_elements:
if not isinstance(element, NavigableString):
print(element.name)
|
ec17c06bd9ba71a24bac89e802fb79d2e9a1449f | rosafilgueira/defoe | /defoe/papers/queries/articles_containing_words_context.py | 3,621 | 3.8125 | 4 | """
Gets contextual information about the occurences of words and
group by year.
The query expects a file with a list of the words to search for, one
per line.
The result is of form, for example:
YEAR:
- { "filename": FILENAME,
"newspaper_id": NEWSPAPER_ID,
"article_title": TITLE,
"ar... |
d97f5a5aa5b6ae28e2eac3ba291a54c23292b0e4 | marczakkordian/python_code_me_training | /03_collections_homework/03_dictionary/06.py | 606 | 3.765625 | 4 | # Utwórz listę zawierającą wartości poniższego słownika, bez duplikatów.
#
# >>> days = {'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sept': 30}
days = [{'Jan': 31, 'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sept': 30}]
# first... |
83745d97ec7701803cf9ed717dfb31dfdd4a9f6b | KHVIII/CS1114- | /hw3/ytc344_hw3_q3.py | 259 | 3.515625 | 4 | def find_duplicates(lst):
check = [0] * (len(lst))
dups = []
for i in lst:
if check[i] ==0:
check[i]=1;
elif check[i] ==1:
check [i] =2;
dups.append(i);
return dups
#worst case run time: n
|
6867513d731d008529c294eba66913ad468033ef | RemusCM/Algorithms-in-Python | /merge_sort.py | 1,183 | 4.1875 | 4 | #Merge sort, divde and conquer method.
#if length 0 or 1, already sorted.
#if more than two, divde into two lists and sort each
#merge sorted sublists.
#We need to make a merge helper function, along with a merge_sort function.
#This algortihm uses recursion.
#O(nlogn)
#helper function to merge sorted arrays.
def merg... |
e8609e286e02d8177391b923e24f045ae0a1004e | Vlas-1/DOMASHCA | /DOMASHKA na 24.10.2020/24.10.2020.py | 758 | 3.515625 | 4 | dni=1
km=10
symKmDni=0
for i in range(1,31):
print(dni,"день",km,"километров")
km+=km/10
symKmDni+=km
dni+=1
if dni==7:
print("Лыжник прошол за 7 дней:",symKmDni,"км")
if km>=80:
print("Ему стоит остановится на",dni,"дне")
print("Введите 0 если хотите завершит... |
9415d99e441e97ce205354a75987c0ced2e37898 | Aldisugiarto/Data-Science | /Pekan 1/TugasPythonLanjutan_Hari_2_AldiSugiarto.py | 876 | 3.578125 | 4 | # Author :Aldi Sugiarto
# Tanggal : 21 Juli 2020
# Versi : 1.0
#---------------------------------------------------Tugas Python---------------------------------------------------#
#Import library untuk request open url dan beautifulsoup
from urllib.request import urlopen
from bs4 import BeautifulSoup
#Akses ... |
97ccc0c418296702613f0220b514f7c4e062ad53 | yordanivh/intro_to_cs_w_python | /chapter08/Exercise10and11.py | 1,398 | 4.28125 | 4 | """10.Variable units refers to the nested list [[’km’, ’miles’, ’league’], [’kg’, ’pound’, ’stone’]]. Using units and either slicing or indexing with positive indices, write expressions that produce the following:
The first item of units (the first inner list)
The last item of units (the last inner list)
The string ’k... |
1fda1b9e322c26698554e83b875419be6fda1d19 | commGom/pythonStudy | /sparta_algorithim/grammar/14_01map.py | 593 | 3.921875 | 4 | people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27},
{'name': 'bobby', 'age': 57},
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
def check_adult(person):
if person['age... |
ac6bedd125600c0691b4aa945a3f757cd6015258 | ZhengLiangliang1996/Leetcode_ML_Daily | /BST/501_FindModeInBST.py | 1,082 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
f1f2eab42929a491548fcb3aff03bebf7585ab8e | Rich-Wu/wallbreakers | /week4/backspaceCompare.py | 443 | 3.5625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
st1 = []
st2 = []
for char in S:
if char == "#":
if st1:
st1.pop()
else:
st1.append(char)
for char in T:
if char == "#":
... |
1d4ec1c318ef3546d43932416beb47971d71c36a | muhammad-younis/connect-four | /Connect4.py | 5,099 | 3.703125 | 4 | import sys
from final_board import *
from final_players import *
import random
class Connect4:
'''Instances of this class simulate an interactive Connect-4 game.'''
def __init__(self, opponent, toMove):
'''
Initializes the game.
Arguments:
opponent -- the computer opponent o... |
ed4dbdf4196444c59f651db14d2f91a34bd01567 | iamgauravsatija/AnomalyDetectionProject | /src/anomaly_detection.py | 9,371 | 3.828125 | 4 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # Anomaly detection algorithm using guassian dirtibution formula
# # for a 2 feature dataset
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# import matplotlib.pyplot as plt
# import numpy as np
# import pandas as pd
# # file = pd.... |
88a82ab7ad60d53af6f742400b67cf6708dcacdd | TBespalko19/test-repository | /01_python_part/09_the_in_keyword/code.py | 1,281 | 4.09375 | 4 | # # friends = {"Bob", "Rolf", "Anne"}
# # print("Bob" in friends)
# movies_watched = {"The Matrix", "Green Book", "Her"}
# user_movie = input("Enter something you've watched recently: ")
# # print(user_movie in movies_watched)
# if user_movie in movies_watched:
# print(f"I've eatched {user_movie} too!")
# else:
... |
702373438bd80b154ef71e65e31437961e37da92 | abhishek305/Problems | /Programs/Linear search User provided list.py | 445 | 3.703125 | 4 | arr=[int(x) for x in input().split()] #user provided array list
print(arr)
k=int(input()) #user provided element to search in arry
def findNumber(arr, k):
for i in range(len(arr)):
if arr[i] == k:
return True
return False
if findNumbe... |
03921a030efa396c20e4e85baf8e6e33579acd93 | targeton/LeetCode-cn | /Solutions/1669.合并两个链表.py | 1,928 | 3.71875 | 4 | #
# @lc app=leetcode.cn id=1669 lang=python3
#
# [1669] 合并两个链表
#
# https://leetcode-cn.com/problems/merge-in-between-linked-lists/description/
#
# algorithms
# Medium (76.75%)
# Likes: 12
# Dislikes: 0
# Total Accepted: 9.4K
# Total Submissions: 12.2K
# Testcase Example: '[0,1,2,3,4,5]\n3\n4\n[1000000,1000001,10... |
1682482bfbcb604009ddf3e8f5dc3b51c1b1f1d7 | jeremyrcouch/tictactoe | /utils/helpers.py | 13,801 | 3.625 | 4 | from copy import deepcopy
from typing import List, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
from utils.players import Player, Human
class Game:
board_shape = (3, 3)
empty_marker = 0
valid_markers = [-1, 1]
ind_to_loc = [
(0, 0), (0, 1), (0, 2),
(... |
9a8ba1ce83e8cb6f0e3bb8f5cad013338f635a21 | jefinagilbert/problemSolving | /hr88_pangramsOrNot.py | 511 | 4.03125 | 4 | def pangrams(s):
alphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
alpha = ''
for i in s:
if i.isalpha() and i.lower() not in alpha:
if s.count(i) <= 0:
return 'not pangram'
alpha += i.... |
b5dda9b8e414500d3bedb2b7655616adf11b0f5a | M0673N/Programming-Basics-with-Python | /exam_preparation/02_mock_exam/03_problem_solution.py | 754 | 3.8125 | 4 | term = input()
contract_type = input()
mobile_internet = input()
months = int(input())
if term == "one":
if contract_type == "Small":
price = 9.98
elif contract_type == "Middle":
price = 18.99
elif contract_type == "Large":
price = 25.98
else:
price = 35.99
else:
if c... |
ffa3e385940aebaa0f2aa50ada2bf291f3e5d7be | alexpirogovski/repka | /repka.py | 876 | 3.78125 | 4 | #!/usr/bin/env python
izba = ['Ded', 'grandma', 'girl', 'bitch', 'cat', 'mouse']
repka = ['repka']
def pull_repka(repka):
shout = len(repka) - 1
repka.append(izba[shout])
print ', '.join([repka[repka.index(x) + 1] + ' za ' + x for x in reversed(repka)
if repka.index(x) != len(repka) ... |
1c20727cd43eee632c4f744051666e970b76841b | yama2908/Codility | /min_ave_two_slice.py | 670 | 3.640625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
min_avg_value = (A[0] + A[1]) / 2.0
min_avg_pos = 0
for i in range(len(A) - 2):
if (A[i] + A[i + 1]) / 2.0 < min_avg_value:
min_avg_value = (A[i... |
a05d0be7c00dd5b82f1bc21dcb5bed6a2353ad7d | hongliang5623/vanyar | /script/link/kgroup.py | 2,766 | 3.71875 | 4 | # -*- coding: utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def print_link(source):
if not source:
return
while source is not None:
print source.val
source = source.next
print '<<<<<<<<<<<<<------------------>>>>>>>>>>>>>>>>>>'
... |
5e1ebbac570fe6b33cfaa3aca89992a08e31b7d8 | doraeball22/Python-for-kids | /2.if-else-assignment.py | 2,319 | 3.71875 | 4 | # ถ้าฉันมีเงินมากกว่าหรือเท่ากับ 1000 แสดงว่า ฉันรวย
# แต่ถ้าฉันมีเงืนน้อยกว่า 1000 แต่มากกว่าหรือเท่ากับ 500 แสดงว่า ฉันฐานะปานกลาง
# ถ้าไม่ใช่ฉันจน
# money= 300
# if money >= 1000:
# print('ฉันรวย')
# elif money < 1000 and money >= 500:
# print("ฉันฐานะปานกลาง")
# else :
# print('ฉันจน')
# โปรแกรมคำ... |
60cace0c67d6e1e7dbba4e3a85a053063d0f2bdb | AnilPokuri/Python---Assignment1 | /Eg18.py | 390 | 3.734375 | 4 | """
18. Write a program create a random list of length 10 and print all the elements except the elements which are divisible by 4.
"""
Input_List = []
for ele in range(10):
ele = raw_input("Enter Random List:")
print ele
Input_List.append(ele)
num = int(ele)
if num%4 == 0:
... |
0a7704fb71f64e8438edfded64eced899155e976 | alexbagirov/py-dns | /parser/answer.py | 635 | 3.5 | 4 | class Answer:
def __init__(
self,
name: str,
record_type: int,
record_class: int,
ttl: int,
data_length: int,
data: str,
):
self.name = name
self.record_type = record_type
self.record_class = record_class
self.ttl = ttl
... |
f16b99f38c1468adba21a959f41de16e5689a20a | everydayxy/xy_py | /日常练习/消费生产者模型.py | 871 | 3.703125 | 4 | import queue
import threading
import time
class Prodecer(threading.Thread):
def __init__(self, q):
super(Prodecer, self).__init__()
self.q = q
def run(self):
cont = 0
while True:
cont_str = '产品{}'.format(cont)
print('生产者---' + cont_str)
self... |
ed6ed94d136f9144911ecb579a6440d0e178135d | kurelaitisk/battleships | /Coordinates.py | 3,281 | 3.78125 | 4 | import random
class Coordinates:
def __init__(self, row=None, column=None, length=None, direction=None):
self.row = row
self.column = column
self.length = length
self.direction = direction
self.coordinates_list = self.generate_coordinates_list()
def generate... |
5fa2321b3c6ddda97b8a86bde17f2cdb1afe57e2 | chenxy3791/leetcode | /No2016-maximum-difference-between-increasing-elements-simple-dp.py | 2,759 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 26 08:17:05 2022
@author: chenxy
2016. 增量元素之间的最大差值
给你一个下标从 0 开始的整数数组 nums ,该数组的大小为 n ,请你计算 nums[j] - nums[i] 能求得的 最大差值 ,
其中 0 <= i < j < n 且 nums[i] < nums[j] 。
返回 最大差值 。如果不存在满足要求的 i 和 j ,返回 -1 。
示例 1:
输入:nums = [7,1,5,4]
输出:4
解释:
最大差值出现在 i = 1 且 j = 2 时,nums[j] - nums[... |
381e5ee44fc34b40c59aec132ae3615f57ec5d46 | xrlie/python_scripts | /Clase9.py | 3,923 | 3.984375 | 4 | ### Repaso de la clase 8
### Lambdas // Funciones una sóla línea de código
suma = lambda x, y: x + y
resta = lambda x, y: x - y
division = lambda x, y: x / y if y != 0 else 'No puedes dividir entre cero'
# def suma(x, y):
# return x + y
### Sintaxis de Clases
class Clase(object):
pass
# Métodos
class Celul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.