blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
16525fa3b1d7239a42f73707fa92c3f463d115f5 | jerry-mkpong/DataCamp | /Intermediate_Python_for_Data_Science/3.Logic_Control_Flow_and_Filtering/Cars per capita (1).py | 711 | 4.28125 | 4 | '''
Let's stick to the cars data some more. This time you want to find out which countries have a high cars per capita figure. In other words, in which countries do many people have a car, or maybe multiple cars.
Similar to the previous example, you'll want to build up a boolean Series, that you can then use to subset... |
9d61cc79f7980694035dd0435c30b4a021aab85d | trungnob/cs188 | /src/proj2/multiAgents.py | 18,820 | 3.796875 | 4 | from util import manhattanDistance
from game import Directions
import random, util
from game import Agent
class ReflexAgent(Agent):
"""
A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are we... |
ee42807c96a6ecfb0343d21e72b7033520f5b853 | joshmedeski/dc-cohort-week-one | /day2/string-interpolation.py | 121 | 3.78125 | 4 | first_name = input('First Name: ')
last_name = input('Last Name: ')
print(f'Hello, My name is {first_name}, {last_name}') |
ef9864a7d29d05a2e98324eb4a448db4d110bc0b | ngoldsworth/Proj-Euler | /p003.py | 1,249 | 4.1875 | 4 | from primes.primelist import PrimesList
from math import ceil, sqrt
def is_prime(n:int):
is_it_prime = True # Boolean variable to hold whether n is prime or not
# n is assumed prime until proven otherwise
root = ceil(sqrt(n)) # if a number isn't prime, it has factors both ... |
cbed02406bc14980c2ef0ce851e7b09a5cc96289 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/19_iterative_search_BST.py | 768 | 3.9375 | 4 | ''' Iterative search BST '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def iterative_search(root, key):
if not root:
return -1
cur = root
while cur != None:
if cur.val == key:
return True
... |
d7bfb8e296974fd7639a8ca0d9cc2522fc41e2c1 | bobcaoge/my-code | /python/leetcode/1387_Sort_Integers_by_The_Power_Value.py | 732 | 3.8125 | 4 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
class Solution(object):
def getKth(self, lo, hi, k):
"""
:type lo: int
:type hi: int
:type k: int
:rtype: int
"""
def get_step(num):
ret = 0
while num != 1:
if num % 2 == 0:
... |
bd8c2eee9454dff520a88727e8507c34edf378ca | chatreesr/py-project-euler | /p004.py | 761 | 3.921875 | 4 | # Problem 004 - Largest palindrome product
# TODO: Make this function work with any n?
def is_palindrome(n: int) -> bool:
if ( (n // 100000) == (n % 10) and
(n % 100000) // 10000 == (n % 100) // 10 and
(n % 10000) // 1000 == (n % 1000) // 100 ):
return True
else:
return Fals... |
c63d59604912233758b319ad9093b260bdfdb130 | dlc9113/yoyoyo | /lib/helpers/concurrent.py | 548 | 3.5 | 4 | from threading import Thread
from queue import Queue
class Concurrent(object):
"""docstring for Concurrent"""
def __init__(self):
super(Concurrent, self).__init__()
self.queue = Queue()
def add(self):
arg = self.queue.get()
self.method(arg)
self.queue.task_done()
def start(self, method, a... |
1ec1e3479fe0a7068cff5d4a71fe166d146b9763 | DishantK1807/Leetcode-Practice | /189 - Rotate Array/PythonSolution.py | 459 | 3.578125 | 4 | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
temp = 0
length = len(nums)
if k > length:
k -= length
if k == length:
k = 0
for i in range(k):
... |
ca08175253d45686d220b671bffe67ad3004f35f | lucascortes96/Rosalind_Solutions- | /09. Finding_a_Motif_in_DNA.py | 392 | 3.625 | 4 | ## Got to get the position(s) of a given substring in your string
def motif_count(test_str, test_sub):
# if char in test starts with sub then add to list 'res'
res = [i for i in range(len(test_str)) if test_str.startswith(test_sub, i)]
## Adding one to each int in list for question format
new_res =... |
e9285ee8b0b16847eaca22f66c95850f7660a3c5 | nmaswood/Random-Walk-Through-Computer-Science | /lessons/day3/exercises.py | 1,177 | 4.21875 | 4 | from random import randint
def create_random(number_of_elements, n):
"""
Use the function randint which takes an integer n and produce a random number [0,n]
to generate a list of size number_of_elements where the numbers are between [0,n]
e.g.
create_random(3, 1000) -> [234, 512, 999]
"""
... |
330a01657bffc5fb2315ab05fc1198be46f12caf | vyahello/upgrade-python-kata | /kata/06/padovan.py | 913 | 4.4375 | 4 | """
The Padovan sequence is the sequence of integers P(n) defined by the initial values
P(0)=P(1)=P(2)=1
and the recurrence relation
P(n)=P(n-2)+P(n-3)
The first few values of P(n) are
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...
"""
def padovan(number: int) -> int:
"... |
9b07794a2e9046c36a73dc4aedf2631e4248c780 | dbgkswn7581/python_basic_questions | /1094.py | 148 | 3.65625 | 4 | a = int(input())
b = input().split()
arr = []
for i in range(a):
arr.append(b[i])
arr.reverse()
for i in range(a):
print(arr[i], end=' ') |
060181bf0bc19b4413d6666bebf811c808bce39f | TheAlgorithms/Python | /other/h_index.py | 1,843 | 4.34375 | 4 | """
Task:
Given an array of integers citations where citations[i] is the number of
citations a researcher received for their ith paper, return compute the
researcher's h-index.
According to the definition of h-index on Wikipedia: A scientist has an
index h if h of their n papers have at least h citations each, and the... |
edbab93e91e368ea46f59df573aecf21cdd89745 | Colcothar/Stock-Cast | /testScaler.py | 629 | 3.578125 | 4 | import yfinance as yf
import lxml
import pandas
import numpy
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
def downloadStockData(stockTicker):
rawData=[]
stock = yf.Ticker(str(stockTicker)) #creates request
history = stock.history(period="max") #gets history
... |
3a5fd383173d1755733d8681eab5e3da91f58fc4 | Taras-code/basis | /Spider/V1.py | 387 | 3.5 | 4 | from urllib import request
if __name__ == '__main__':
url = 'https://translate.google.cn/'
wd = input("Input your keyword:")
rsp = urllib.request.urlopen(url)
print(type(rsp))
print(rsp)
print("URL:{0}".format(rsp.geturl()))
print("Info:{0}".format(rsp.info()))
print("Code:{0}".format... |
067cec12ca82e2cb46d4873c396fb310edbd85f0 | WeiYongqiang55/code_git | /19.py | 109 | 3.515625 | 4 | a = "OurWorldIsFullOfLOVE"
a=a.lower()
if a.__contains__("love"):
print("LOVE")
else:
print("single") |
dcb05c48b27817fce6fee462047826839d1fb710 | cooperfaber/Parallel-Programming | /hw1/part2/homework1_part2_skeleton.py | 6,175 | 3.703125 | 4 | import os
import argparse
# Top of C++ file with includes and namespaces
top_source_string = """
#include <iostream>
#include <assert.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
typedef double reduce_type;
"""
# The reference loop simply adds together all elements in the array
def referen... |
ee3d9b56de336ea2d52e94a8004d48958e6f671c | RenanVenancio/TabelaHash | /aluno.py | 359 | 3.546875 | 4 | class Aluno:
def __init__(self, matricula, nome, idade):
self.matricula = matricula
self.nome = nome
self.idade = idade
def printar(self):
print(self.matricula, self.nome, self.idade)
def __str__(self):
return 'MAT: ' + str(self.matricula) + ' - NOME: ' + str(self... |
012b06dd0a1c7f07a15c32a9525c2cc42e7efea0 | SorensenAndrew/DPW | /Python/day3.py | 457 | 3.640625 | 4 | class Student:
def __init__(self, n):
print "student created"
self.name = n
self.gender = ""
self.grades = []
def getAvg(self):
total = 0
for i in self.grades:
total += i
return total/len(self.grades)
john = Student("John")
john.grades = [70,... |
c528d32c8e660c0eb779b170bdfc60f9bc7595b5 | lsa-src/EXPython | /실습예제/Set.py | 1,031 | 4.21875 | 4 | '''
집합 set, 자료형으로 쓰기 보단 데이터 처리용으로 많이 사용, 데이터 중복없이 하나만 필요할 때..좀 더 프로그램을 편하게 하고자 할 때
컬렉션 데이터 타입은 for in
파이썬은 사람의 마인드와 유사...
'''
lst = [1,2,3]
st = {1,2,4}
print(type(lst))
print(type(st))
print(lst[0])
# print(st[0])
# print(st[0]), TypeError: 'set' object is not subscriptable, set은 인덱싱이 안됨 순서가 없음
lst... |
678d60190d77e5084c2f1ac7d3a820bc9452356b | lamasnicolas/PostgreSQL-comparator | /comparator.py | 2,594 | 3.71875 | 4 | import argparse
from db_checker import DbCompare, Parameters
parser = argparse.ArgumentParser(description='The program will check if two PostgreSQL databases contains the same '
'tables and same rows in each one. '
'Default beha... |
7e592fa59879156377769aba54192f3db05c7f86 | Azimusss/Azis | /Classes.py | 1,204 | 3.734375 | 4 | import math
class Vector:
def __init__(self, coords):
self.x = coords[0]
self.y = coords[1]
def get_len(self):
return math.sqrt(self.x**2 + self.y**2)
@property
def len(self):
return self.get_len()
def as_point(self):
return self.x, self.y
def rotate(... |
170dc08f997091bc689ce4ed85a303e7f4804b6f | Phillips1031/Clue-Less | /board/location.py | 1,898 | 4.125 | 4 | '''
Created on Oct 10, 2017
@author: Zack
'''
class Location(object):
'''
Areas of the game board that a character can occupy.
TODO: Start Locations?
'''
def __init__(self, name):
self.roomType = name
self.connectingLocations = set()
def add_connecting_locat... |
99eb0a7d4d0f9b20c45ca9923de7782cdff89c42 | JPTIZ/graph | /graph.py | 4,787 | 3.953125 | 4 | '''Defines graph structures.'''
import random
from typing import Set, TypeVar
K = TypeVar('K')
class Vertex:
'''A graph's vertex.'''
def __init__(self, key: K):
self.key = key
self.neighbours = set()
def degree(self) -> int:
'''Returns the vertex's degree.'''
return len(... |
afc9a71ac8558aa3ea6d89450c95496b89ea1730 | UW-ParksidePhysics/Bencs-Michael | /univariate_statistics.py | 1,393 | 3.859375 | 4 | from matplotlib.pyplot import *
from numpy import *
from statistics import stdev
def univariate_statistics(data):
#"Calculate statistical characteristics of a data set
# Module name:
# univariate_statistics
# Parameters:
# data: ndarray, shape(2, M)
# ... |
c99baf7b7ff6098ecacb9e87e85138662fa2d9cf | AKolumbic/Intro-Python | /src/dicts.py | 713 | 4.3125 | 4 | # Make an array of dictionaries. Each dictionary should have keys:
#
# lat: the latitude
# lon: the longitude
# name: the waypoint name
#
# Make up three entries of various values.
waypoints = [
{
"lat": 34.046145,
"lon": -118.345499,
"name": "Leo's Tacos"
},
{
"lat": 34.096... |
6f4b172cb917fa66f34179b97f5124cb7f1392ce | jerryyang747/SemiPy | /SemiPy/Plotting(decom)/Plotting.py | 2,333 | 3.546875 | 4 | """
Basic Plotting object
"""
import plotly.graph_objects as go
import numpy as np
class BasePlotlyPlot(object):
def __init__(self, *args, **kwargs):
self.fig = go.Figure()
@staticmethod
def _check_array(array):
array = np.array(array)
assert len(array.shape) == 2 or len(array.s... |
c93de6105a00387259bf38bb6c8dd026435c6e3c | jasonkrone/Infection | /utils.py | 1,588 | 4.1875 | 4 |
'''
By Jason Krone for Khan Academy
Implementation of subset sum Utils
'''
BASE_TUPLE = (True, 0, 0)
def subset_sum_within_range(nums, n, delta):
'''
returns a subset of the given numbers that sum within the given range
(n - delta, n + delta) if such a subset exists. Otherwise, returns None
'''
... |
f69130c73fafadbb549e76dbdff4710c7e8091cb | netka78087/lesson2 | /string-challenges.py | 80 | 3.96875 | 4 | word = "Архангельск"
print(word[-1])
print(word.lower().count('а'))
|
fb98f5d02cad394472b23186e5dbc4b42ae391c6 | tt-n-walters/saturday-advanced-python | /f.py | 750 | 4.3125 | 4 | # Recursion, or a recursive function, is a function that calls itself.
import sys
sys.setrecursionlimit(10000)
counter = 0
cache = {}
fib = int(input("What number in the Fibonacci sequence do you want to calculate?\n"))
def fibonacci(n):
global counter
# print("Calculating:", n)
if n in cache:
r... |
d08c01f1ff1794759a4ce0b327475e2e11bc402b | konstant-in/example1 | /p4.py | 1,405 | 4.09375 | 4 | '''
Использование декоратора, выполняющего необходимые вычисления
Если вернуться к исходному примеру,
то для подсчёта числа вызовов функции будет также может быть удобно использовать декораторы.
Это позволит в том числе и переиспользовать код.
При желании вы можете скомбинировать этот способ с каким-нибудь из описанн... |
e286b04458be9c0c645de176eb2f3525d35376fb | tonyshou015/python-homework | /作業5.py | 160 | 3.75 | 4 | year=eval(input("請輸入一個年份:"))
if (year%400 == 0) or ((year%4 == 0) and (year%100 != 0)):
print("閨年")
else:
print("平年")
|
8fc54278acf8731142acd51953f4a47e351ea6a6 | Hexexe/ML | /HighestSummit.py | 1,005 | 3.765625 | 4 | import math
import random
# generate random mountains
w = [.05, random.random()/3, random.random()/3]
h = [1.+math.sin(1+x/.6)*w[0]+math.sin(-.3+x/9.)*w[1]+math.sin(-.2+x/30.)*w[2] for x in range(100)]
def ... |
528b82b0494f06786ac7cc0aed0090234e8df36c | subham-dhakal/python-practice-files | /area.py | 192 | 4.40625 | 4 | #It prints the area of circle
r= float(input("Enter the radius of the circle\n"))
result=3.14*r*r
print("The area of the circle with radius {} is {} ".format(r,result))
print(50*'*')
|
b53ddce5170cd37973f00e7f9e8dc000f468af1f | gn0/sacsv | /sacsv/csvfindsortkey.py | 1,167 | 3.9375 | 4 | import argh
import csv
import sys
def is_ascending(iterable):
prev_value = None
for value in iterable:
if prev_value is not None and prev_value > value:
return False
prev_value = value
return True
def is_descending(iterable):
prev_value = None
for value in iterabl... |
ba750884bc4ab956934c4f6b824f1442dbacc7a6 | brandoneng000/LeetCode | /easy/2363.py | 743 | 3.703125 | 4 | from typing import List
class Solution:
def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:
items = {}
for value, weight in items1:
items[value] = items.get(value, 0) + weight
for value, weight in items2:
items[... |
4dcf7d760073da3776356f2c141e2fdde4deb551 | JeremiahZhang/gopython | /python-programming-an-introduction-to-CS/src/ch02/mass_convert.py | 395 | 4.15625 | 4 | # mass_convert.py
# A program to convert mass measured in kilogram to Pound
def main():
print("This is a program to convert mass measured")
print("in kilogram to pound.")
# input
kilogram = eval(input("Enter the mass measured in kilogram:_> "))
# process
pound = 2.20462 * kilogram
# outp... |
069740854d3f61f6de62b2ccfad00ecd5b09a5f8 | vrunda13/1BM17CS126 | /2a.py | 151 | 3.75 | 4 | bol=0
l=eval(input("enter the string"))
key=int(input("enter the key"))
if key in l:
bol=1
if(bol==1):
print("true")
else print("false")
|
64b2825459d6057edd48c001b30188b735b2a602 | DidiRaggio/python_blockchain_test | /main.py | 1,088 | 4.125 | 4 | # from block import Block
# # Create the blockchain that functions like a LinkedList.
# class Node():
# def __init__(self):
# self.data = 5
# self._next = None
# # In a linked list each node is linked to each other by the _next attribute, so they are nested one within the other.
# # In a ... |
30f9cc33f751c42cef2819306e00db4575db82e8 | MinaBasem/Basic-Projects | /BiggestNumber.py | 551 | 4.375 | 4 | # Biggest number
# Returns the biggest number from 3 user inoutted integers
import time
num1 = int(input("Please input the first number: "))
num2 = int(input("Please input the second number: "))
num3 = int(input("Please input the third number: "))
if (num1 > num2 and num1 > num3):
print("The largest number is %s... |
d87b42438a60275a9408caf80db48d03ebdb7968 | RhevanP/BlackJackGame | /inputUserCheck.py | 1,117 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 21:38:08 2020
@author: antho
"""
def inputUserCheck(drawUserValue) :
if (len(drawUserValue) > 1) :
while True :
userInput = input('Do you want to Draw (1) or Stop (2) ?')
try :
userInput = int(userInput)... |
5517b39e65edcc1fbad99755d1b3dd42380cd733 | alec-deason/ihme-python-course | /basic_python_exercises/topics/01_basic_syntax/03_strings/test_A.py | 467 | 3.984375 | 4 | from A import every_other_character, every_other_character_capitalized
def test_every_other_character():
for s in ['test', 'two words', 'a'*1000, '']:
assert every_other_character(s) == ''.join([c for i, c in enumerate(s) if i%2 != 0])
def test_every_other_character_capitalized():
for s in ['test', '... |
48fcb36b05b0c16ecf7ed0369882f2835372e8fe | florim14/projectEuler | /DigitFactorials/DigitFactorials.py | 394 | 3.671875 | 4 | import math
def digitFactorials():
result = 0
for i in range(10, 100000):
factorial = 0
for letter in str(i):
factorial += math.factorial(int(letter))
if i == factorial:
result += i
print(f'Number: {i} and his factorial is: {factorial}')
print(f... |
dd8eccfdfa5cdcf7141de52b5403cfa355bbb339 | NeonedOne/Basic-Python | /Second Lab (2)/17.3. Дни рождения – 2.py | 287 | 3.65625 | 4 | # Алексей Головлев, группа БСБО-07-19
birthday_calendar = [input().split() for _ in range(int(input()))]
birthday_calendar.sort(key=lambda x: (int(x[1]), x[0]))
for i in range(int(input())):
month = input()
print(*[f'{i[0]} {i[1]}' for i in birthday_calendar if i[2] == month])
|
9b927b15f4fe471b80c7c449b112584e7c2097fe | alsofro/GB_algorithms | /7/2.py | 1,145 | 3.96875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
import random
array_1 = [random.random() * 50 for i in range(10)]
def merge_sort(arr):... |
82091c0f366db45db0a7cb39896f74e1ac9a8875 | 8v10/eprussas | /1_LogicaDeProgramacao/0_Python/3_Python_Parte3/6 - Classes e Objetos/2.2 Pessoa - Métodos.py | 323 | 3.78125 | 4 | class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
def apresentacao(self):
print("Olá, meu nome é: " + self.nome)
print ("Tenho " , self.idade , "anos.\n")
p1 = Pessoa("Hugo", 26)
p2 = Pessoa("João", 18)
p2.idade=21
p1.apresentacao()
p2.apresentacao()
|
553ae4066bd9f6b6071c1d1110c449736547c11c | mthompson36/newstuff | /Exercise2.py | 207 | 4.34375 | 4 | #This program will return in your number is odd or even.
number = int(input("Please enter a number:"))
if (number % 2) == 0:
print(str(number) +" Can be divided by 2")
else:
print("This is an odd number") |
12c65dc7ddc74bdaaab9c6badf673b3d6e960ea5 | MadHypnofrog/cutting-rule-predictor | /datasets/stats_collector.py | 4,873 | 3.5 | 4 | import pandas as pd
import numpy as np
import os
from utils.html_builder import HTMLBuilder
from .stats_calculator import StatsCalculator
calc = StatsCalculator()
"""
A class that provides utility functions used to collect the statistics.
"""
"""
Collects the statistics on a single dataset and writes them t... |
41721542914420018b8d115320e8ae93dbc84930 | alexbalonperin/university-projects | /AI Programming/Natural Language Processing/src/MachineLearning/Classifier/ProbDistI.py | 3,661 | 3.984375 | 4 | '''
Created on Nov 23, 2011
@author: alex
'''
import random, warnings, math
_NINF = float('-1e300')
class ProbDistI(object):
"""
A probability distribution for the outcomes of an experiment. A
probability distribution specifies how likely it is that an
experiment will have any given outcome. For exa... |
8f18b62bda492bbf65c61fd420761637eb01015a | tylerdowney1337/Bacteria_Program | /Bacteria_Program.py | 12,560 | 4.3125 | 4 | # Bacteria Program
# Date: April 21st, 2021
# Authors: Tyler Downey, Troy Green, Wesley Squires, Ciaran Kelly
""" This program is used to track bacteria samples that are being used to test new medications."""
""" Key Features:
- Date entry box (current date as default)
- ID number of the bacterial culture
- Dropdown m... |
5402eb86778aebbfdc42f7e74b759a9e2aa63633 | maryoohhh/pythoncourse | /sort_print_list.gyp | 1,112 | 4.4375 | 4 | # Building three functions: sort, reverse sort, and print list
pizza_toppings = [
'Hawaiian',
'Champagne Ham & CheeseBeef & Onion',
'Pepperoni',
'Simply Cheese',
'Bacon & Mushroom',
'Italiano',
'The Deluxe',
'Ham, Egg & Hollandaise',
'Americano',
'Mr Wedge',
'BBQ Meatlovers'... |
f077d35368564785ad90ed067f7b20a2661418e9 | AminaAbdallah/Assignment-4 | /Looking_for_a_specificTopic.py | 1,591 | 3.796875 | 4 | import json
import pandas
import requests
#MyApiKey : 'b7de039e294740bb84d8dff8c2bbf97d'
# The headers for the authentification
print('NB : the result of this request will be found in the console or in the csv file that you choose its location in the code in the end')
print('Please, enter your Apikey for APInews or... |
9fbc579942a50a5f1c6e8f4f1cdeddef1c0b7e4e | DIVYAKHYANI/data_structures_with_python | /Delete_node(linked_list).py | 404 | 3.90625 | 4 |
def deleteNode(head, position):
current = head
# next will point to None if there is
# not another item in the list
if position == 0:
head = head.next
else:
# iterate to the right node
for i in range(position-1):
current = current.next
# and... |
38d424c1d811c8de0c8403996047f4fd75e99a73 | SThiara/learning-python | /full_speed_python/lists/even_squares_not_three.py | 177 | 3.890625 | 4 | def getSquare():
l1=[ x**2 for x in range(0, 21, 2) if x % 3 != 0]
#l1 = [num for num in [num**2 for num in range(0, 21, 2)] if (num % 3 != 0)]
return l1
print(getSquare()) |
b97e91d1cada52eda9505cd6925573068cf65699 | Rvioleck/python_noj_exmination | /noj_041佩尔数.py | 189 | 3.75 | 4 | def pell_number(n):
pell = [0, 1]
for i in range(2, n+1):
num = 2 * pell[i-1] + pell[i-2]
pell.append(num)
return pell[n]
n = int(input())
print(pell_number(n)) |
9332eee3c716dc325513c442ccbc8c3100df360f | DiyanKalaydzhiev23/fundamentals---python | /Final exam 3/Mirror Words.py | 622 | 3.859375 | 4 | import re
pattern = r"(@|#)(?P<word1>[a-zA-Z]{3,})\1\1(?P<word2>[A-Za-z]{3,})\1"
words = [el.groupdict() for el in re.finditer(pattern, input())]
if not words:
print("No word pairs found!")
print("No mirror words!")
else:
print(f"{len(words)} word pairs found!")
mirror_words = []
for el in words:
... |
18e5a47cd62dd44507f1ba4459774a86a03c4783 | DincerDogan/Data-Science-Learning-Path | /Data Scientist Career Path/3. Python Fundamentals/6. Python Loop/1. Intro to Loop/1. loop.py | 518 | 3.984375 | 4 | # Write 10 print() statements below!
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with loops!")
print("This can be so much easier with lo... |
d11db2e2e3bc1ff0856de20800259a9dd418bae6 | demonzyz/huice | /yearText.py | 239 | 3.84375 | 4 | # coding=utf-8
input_year = raw_input("请输入测试年份:")
year = int(input_year)
if ((year%4 == 0 and year%100 != 0) or (year%400 == 0)):
print('%d年是闰年!' % year)
else:
print('%d年是平年、不是闰年!' % year) |
89081f11fd2ae26e7d17551e3bed8c37bb16630b | katur/rc-warmups | /h02_tens.py | 714 | 4 | 4 | '''Write a function that takes a list of numbers and returns all adjacent
sublists that sum to 10. You can assume that all numbers are non-negative.
E.g.
tens([2, 3, 5, 5, 4, 1, 0, 9, 1])
-> [ [2,3,5], [5,5], [5,4,1], [5,4,1,0], [1,0,9], [0,9,1], [9,1]]
'''
TEN = 10
def tens(all_numbers):
start = 0
end = 1
... |
2be60e318e5396f52ef3e24cf69597f3eb71be27 | PrachiNayak89/Prachi-rampUp | /ticTacToeUserInput.py | 1,248 | 3.890625 | 4 | #!/usr/bin/python
#This program is to take the user input for the game
#default board
game=[[0,0,0],
[0,0,0],
[0,0,0]]
print game
count=1
#1 for player 1 and 2 for player 2
userInput1=None
userInput2=None
while True and userInput1!="exit" and userInput2!="exit":
if count%2!=0:
userInpu... |
aeb0329976587d6d5f1aa07ca94a58ddecfd7d23 | Italo-Neves/Python | /Curso-Em-Video/M2/ex42.py | 759 | 4 | 4 | # -*- coding: utf-8 -*-
r1 = float(input('Digite o valor da reta 01: '))
r2 = float(input('Digite o valor da reta 02: '))
r3 = float(input('Digite o valor da reta 03:'))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r2 + r1:
triangulo = True
print('Esse valores geram um triagunlo ')
else:
triagunlo = False
... |
288eb7d63c4456fd5fc3ce5dac26dc3dad4bc35b | Kvazar78/Skillbox | /11_float_round/dz/task_11.py | 1,992 | 4.125 | 4 | # В рамках разработки шахматного ИИ стоит новая задача. По заданным вещественным координатам
# коня и второй точки программа должна определить может ли конь ходить в эту точку. Используйте
# как можно меньше конструкций if и логических операторов. Обеспечьте контроль ввода.
#
# Пример:
#
# Введите местоположение коня:
... |
ffb7ea774a493d89a97da369540f52f90a85e877 | zeppertrek/my-python-sandpit | /python-training-courses/pfc-sample-programs/tuple_example_003.py | 580 | 4.28125 | 4 | #tuple_example_003.py
# Weird declarations of a tuple
# Python lets you do this
# Question is - Does it make sense ?
# Model your tuples on real world data
#
myTuple1 = ([],(),[], "a", 1, 1.6, 444555, "goosebumps", {1,2,3,4})
print (myTuple1)
x = 100
myTuple2 = ("aaabbbbbbbbcccccccccccc", type(myTupl... |
0c3f68f0e0623c4132a8a676555fcce6bf3a6746 | MrHamdulay/csc3-capstone | /examples/data/Assignment_1/bxxbub001/question3.py | 1,496 | 3.671875 | 4 | #B.Booi 3 march 2014
#spam msg
name = input ("Enter first name:\n")
last = input ("Enter last name:\n")
money = eval(input("Enter sum of money in USD:\n"))
country = input("Enter country name:\n")
print("")
print('Dearest ', name ,sep='')
print('It is with a heavy heart that I inform you of the death of my father,... |
ee644c00dc2b083aee9a4c56f0709bdc7b50f89d | Hidenver2016/Leetcode | /Python3.6/243-Py3-Shortest-Word-Distance.py | 2,026 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 17:44:03 2019
@author: hjiang
"""
"""
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 =... |
d7aead547d4e8e95ae181d76fada1c0fc73b572d | rhanmiano/100days-coding-challenge | /py/day4-multiples-3-5.py | 794 | 4.28125 | 4 | ##
# 100 Days Coding Challenge
#
# @author Rhan Miano
# @since November 6, 2018
#
# Pushing myself to do this 100 Days Coding Challenge.
##
# Day 4 Reverse a string
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
#
# ... |
7b14b3163b9e7b153d34548d248362cfddb468bb | EugenenZhou/leetcode | /nowcoder/jzoffer/Merge.py | 1,397 | 3.9375 | 4 | # -*- coding:utf-8 -*-
# 合并两个链表
# 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
#
######################################################################
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def ToListNode(l):
reason = ListNode(0)
list = reason
for num... |
50bada4376a1f366eb4a2e97e8944703297f4963 | parry1233/Pyrthon_practice | /pamdas_dataframe.py | 482 | 3.546875 | 4 | import pandas as pd
names = ['United States','Australia','Japan','India','Russia','Morocco','Egypt']
dr =[True,False,False,False,True,True,True]
cpc=[809,731,588,18,200,70,45]
cars_dict={'country':names,'drives_right':dr,'cars_per_capital':cpc}
print('Before dataframed:')
print(cars_dict)
print('After dataframed:')
... |
42ac00be509f5f5aed7e5469f6aa858a736a4664 | athul-santhosh/The-Daily-Byte | /gather n ary traversal.py | 681 | 3.625 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root : return []
cur = []
next = []
result = [... |
bf16a579749459eb2e5bf382ae4c22981b2ea0ca | imd8594/GroupMeTic-Tac-Toe | /groupme_tictactoe.py | 5,986 | 3.703125 | 4 | """
Ian Dansereau
groupme_tictactoe.py
April 5, 2016
Groupme tic tac toe game made using only a bot.
GroupyAPI docs here: http://groupy.readthedocs.org/en/master/
GroupMe Dev page: https://dev.groupme.com/
"""
from groupy import Bot, Group
#groupme constents
groupid = ""
bot_name = ""
bot = [bot for bot in B... |
9a2c91c655c7ba7daac34460e858802bcb0b8237 | Blackoutta/python_tutorials | /treehouse/object/instance.py | 345 | 3.609375 | 4 | my_list = ["apple", 5.2, "dog", 8, True, False]
def combiner(mlist):
words = ''
nums = 0
for i in mlist:
if isinstance(i, str):
words += i
elif i == True:
pass
elif isinstance(i, (int, float)):
nums += i
output = words + str(nums)
print(ou... |
9ec4e55c043c9b431d8995dc2ad5a52e233dbeaa | leogtzr/python-cookbook-code-snippets | /data_structures_and_algorithms/combining_multiple_mappings_into_single_mapping1.py | 473 | 3.859375 | 4 | from collections import ChainMap
# A ChainMap takes multiple mappings and makes them logically appear as one.
a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}
c = ChainMap(a, b)
for k, v in c.items():
print(c[k])
print('~~~~~~~~~~~~')
print(c['x'])
print(c['y'])
print(c['z'])
print('~~~~~~~~~~~~~~~~~~~~>')
for k i... |
dc2561155abaafd3b2e6dade63433c8777fe692d | Alice86/StatsProgramming | /20170929Start.py | 4,486 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
""" arithmetics """
print 2 + 2
print 50 - 5*6
print (50 - 5.0*6) / 4
print 8 / 5.0
print 8 / 5
# power **
5**2
""" floating vs int """
# operators with mixed type operands convert the integer operand to floating point
# int / int -> in... |
34b6045d7ed6a81051d3f57bdbdb177e9d64383d | sch0nik/python-project-lvl1 | /brain_games/games/even.py | 592 | 3.90625 | 4 | """Главный элемент игры чет-нечет."""
from random import randint
RULES_OF_THE_GAME = 'Answer "yes" if the number is even, otherwise answer "no".'
def generate_game_values():
"""
Сама игра.
Функция придумывает число, показывает пользователю,
и спрашивает ответ.
Returns:
Возвращает вопро... |
4ebca1ef89f7c234477f3b809e8be7d3bef6799b | Aliciaalexandriachew/python_practice | /P1/src/futval.py | 548 | 3.890625 | 4 | '''
Created on 20 Jul 2020
@author: Alicia
'''
'''
Study Unit 1 Activity 14:
'''
def main():
print("Calculate your future worth through compound interest:")
principal = int(input("Enter the amount of money in dollars: $"))
apr = float(input("Enter bank annual interest rate as decimal number: ")... |
5d2022720a315bfa4d5034ddf71065460396bb50 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2424/60619/243144.py | 273 | 3.671875 | 4 | t = int(input())
for index in range(t):
length = int(input())
numbers = input().split(" ")
exist = False
for n in numbers:
if numbers.count(n)%2 == 1:
print(n)
exist = True
break
if not exist:
print(0) |
46ce73a607f6a177c3dbb306d4247dbfd5573551 | dalexach/holbertonschool-machine_learning | /supervised_learning/0x06-keras/0-sequential.py | 1,332 | 3.703125 | 4 | #!/usr/bin/env python3
"""
Building a model with Keras
"""
import tensorflow.keras as K
def build_model(nx, layers, activations, lambtha, keep_prob):
"""
Function that that builds a neural network with the Keras library
Arguments:
- nx is the number of input features to the network
- layers is... |
b592eb6d84a9c8b4009b9fe1febbf4be581bd90f | BrandonNay/distributed-systems | /genetic-algorithms/src/population.py | 2,260 | 3.546875 | 4 | # Population Class | Genetic Algorithm
from random import randint
from random import choice
class Population:
class Member:
def __init__(self, lifespan=50, write_dna=True):
self.lifespan = lifespan
self.fitness = 0
self.directions = ["U", "D", "L", "R"]
if ... |
d867d0d88bc1eafefff32c27db6ace861a320f5e | elephantscale/emlp-labs-macys | /recommendations/code/knn-recommender/src/utils.py | 2,242 | 3.53125 | 4 | import numpy as np
import pandas as pd
from fuzzywuzzy import fuzz
def fuzzy_matching(mapper, fav_movie, verbose=True):
"""
return the closest match via fuzzy ratio. If no match found, return None
Parameters
----------
mapper: dict, map movie title name to index of the movie in data
f... |
6ae970c3b68ad461f4fe03fa9544bf06c9540860 | campbellmarianna/Rest-API-with-Flask-Course | /section-2-python-refresher/passing_functions.py | 546 | 4.15625 | 4 | def methodception(another):
return another()
def add_two_numbers():
return 35 + 77
# print(methodception(add_two_numbers))
# print(methodception(lambda: 35 + 77)) # a lambda function is an anonymous function - always one line
my_list = [13, 56, 77, 484]
def not_thirteen(x):
return x != 13
# filter th... |
9cdfa0d8ab4c04d3632cba11be364ff7743257a3 | tgtn007/DSAinPython | /Projects/project1_UnscrambleCSProblems/Task4.py | 1,406 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
listOfAllCallers = set()
for callers in calls:
listOfAllCallers.add(callers[0])
# Removing the numbers which re... |
893f4ab88dd20603cb9115498c9e46ab1d81061d | sandeep24789/Python | /Python/demo2.py | 148 | 4 | 4 | a=int(input("enter the number"))
if(a>10):
print("true")
print(a)
elif(a<8):
print("else if false")
print(a)
else:
print("end")
|
b253242888ac240d778687a0694ba12e7087c4e1 | mitsurukikkawa/Python | /DeepQNetwork/qlearning-ab.py | 2,482 | 3.921875 | 4 | '''
環境の状態は、'A'または'B'からなる長さ8の文字列で表され、
その文字列にはある法則により得点がつけられる。
プレイヤーはその法則についての知識を予め持たないが、
文字列中の任意の1文字を選んで'A'または'B'に置き換えることができ、
その結果、その操作による得点の変化量を報酬として受け取る。
https://zaburo-ch.github.io/post/q-learning/
'''
import numpy as np
import matplotlib.pyplot as plt
STR_LEN = 8
ALPHA = 0.1
GAMMA = 0.99
EPS = 0.1
... |
d398fade4929ed636bb4a78c7515eb376147e0ab | ferreret/python-bootcamp-udemy | /36-challenges/ex130.py | 636 | 4.375 | 4 | '''
three_odd_numbers([1,2,3,4,5]) # True
three_odd_numbers([0,-2,4,1,9,12,4,1,0]) # True
three_odd_numbers([5,2,1]) # False
three_odd_numbers([1,2,3,3,2]) # False
'''
def three_odd_numbers(numbers):
len_numbers = len(numbers)
for cursor in range(2, len_numbers):
sum_test = numbers[cursor - 2] + numbe... |
18fa511636b3030d52d0b8c5977a16172c63a2d2 | eric496/leetcode.py | /hash_table/974.subarray_sums_divisible_by_K.py | 758 | 3.734375 | 4 | """
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.
Example 1:
Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]... |
7e2514db4fddaf2e035f709a8f290c75101d192a | Plasmoxy/MaturitaInformatika2019 | /python/noob/pocet_9.py | 147 | 3.515625 | 4 |
x = int(input("Zadajte prir. c. : "))
c = 0
while x > 1:
if x % 10 == 9:
c += 1
x //= 10
print(f"Pocet cislic 9 v cisle je {c}") |
1f48e4b35006edee4231595aa8fb26e4f18f65a0 | FrenchBear/Python | /Learning/130_Fluent_Python/fp2-utf8/bloccode/example 6-12.py | 352 | 3.90625 | 4 | # Example 6-12. A simple class to illustrate the danger of a mutable default
class HauntedBus:
"""A bus model haunted by ghost passengers"""
def __init__(self, passengers=[]):
self.passengers = passengers
def pick(self, name):
self.passengers.append(name)
def drop(self, name):
... |
9f2ef944ebf7ed8fd6f377d68e2825e3b659bd54 | edu-athensoft/stem1401python_student | /py200913d_python2m4/day09_201108/global_scope_2.py | 236 | 3.546875 | 4 | """
global scope
global variable - A variable which is defined and takes effect in global scope
"""
x = 10
def foo():
"""
x does not change here
:return:
"""
print("x inside:", x+1)
foo()
print("x outside:", x) |
62a90aa794b1901327a1500d1ba8d995e85db44a | weilian1977/openmv-project | /openmv/6-10_find_outliers.py | 7,582 | 3.578125 | 4 | # Untitled - By: 黄惠泽 - 周四 6月 7 2018
import sensor, image, time
## Red Threshold in LAB color space for finding the largest blobs
red_threshold_LAB =(51, 75, 19, 84, -7, 70)
## Red Threshold in RGB color space for get_pixels() finding the right color
red_threshold_RGB= (200,256,0,160,0,180)
## Global variables for fin... |
62be4fa6944fe2bc709a4b6346d0bf58259d4814 | HalfMoonFatty/Interview-Questions | /680. Valid Palindrome II.py | 872 | 4.03125 | 4 | '''
Problem:
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase characters a-z. The maxi... |
9842673e1c18352b51157ed3aa4a9e706874966d | wiput1999/Python101 | /7 Extra 4/P.55 Part IV/9.py | 100 | 3.65625 | 4 | def leadingdigit(n):
t = str(n)
return t[0]
a = int(input("num : "))
print(leadingdigit(a)) |
bf05cc91e97097ef50442498af34b60411a58c92 | shivan-s/AutomateTheBoringStuff | /Chapter9/selectiveCopy.py | 1,192 | 3.640625 | 4 | #! python3
# selectiveCopy.py Program walks through folder tree and searches files ending with .pdf or .jpg into a new folder
# using ./SelectiveCopy/americanFiles as a test
import os, shutil
#function to copy
def copyFormat(folder,fileFormat):
folder = os.path.abspath(folder)
print('\nFOLDER to copy...\n %... |
74dcea2607f6d7d8f093ddc6a2e3e2058db2d628 | IlosvayAron/script-languages | /Lesson9/homework/own_solution/pages.py | 692 | 4.03125 | 4 | #!/usr/bin/env python3
def printable_pages(pages: list) -> list:
lst = pages.split(',')
res = []
for num in lst:
if '-' not in num:
res.append(int(num))
else:
interval = num.split('-')
lower = interval[0]
upper = interval[-1]
for i... |
6f6a0783512c5d2bee6e71e35459609bcc53d5bc | Wh1t3Fox/hackthissite | /programming/11.reverse_ascii/reverse.py | 255 | 3.546875 | 4 | #!/usr/bin/env python
import sys
if __name__ == '__main__':
string = '30,32,23,31,5,5,'
shift = -30
string = string.split(string[-1])
string.remove('')
output = ''.join([chr(int(c) - int(shift)) for c in string])
print output
|
61144b8c72a71c7b83ecaab4fd2c16c7610e8780 | goodsoul/learningpython | /03_absoult_value.py | 138 | 4.34375 | 4 | # print absolute value of an integer:
number=float(input('Please input a number'))
if number>=0:
print(number)
else:
print(-number) |
ea8abd8fcf8dd1ec8fb0cc4358f90756e1604482 | rometsch/sheep | /chprm.py | 1,529 | 3.515625 | 4 | #!/usr/bin/env python3
# Replace a parameter value in a text based config file.
# The only assumption is that the parameter name and the value
# are separated by whitespaces and followed by whitespaces or newlines.
import re
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("i... |
1523aa56dfd7a16abca579587fe462d0e5b499b6 | Napster56/Sandbox | /factorial_recursively.py | 727 | 4.28125 | 4 | """
Function that calculates the factorial of n and prints the result.
"""
def main():
n = factorial(1)
print(n) # print result for first function
# n = factorial_2(0)
# print(n) # prints result for second function
def factorial(n):
""" Recursive factorial. """
i... |
976190cc72fa7e453d4190434bce3eb75fb49a71 | duylamasd/basic-algorithms | /prim-mst.py | 2,770 | 3.8125 | 4 | import sys
MAX_INT = sys.maxsize
class Graph:
def __init__(self, num_of_vertices):
self.num_of_vertices = num_of_vertices
self.adjecency_matrix = []
def add_dist(self, distances):
self.adjecency_matrix.append(distances)
def min_key(self, key, mst_set):
"""
A uti... |
4cc2333fbd702019a2700e771e1a734bcdf97db6 | MachFour/info1110 | /week2/T14B/intro-things.py | 2,024 | 4.46875 | 4 |
############################
# Some introductory things #
############################
#
# Datatypes:
# These should be familiar! What is the type of each variable?
count = 10
name = "Alexander the Great"
ratio = 2.3
cost = count*ratio # what datatype is the product of these two variables?
# A new datatype: Bool... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.