blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6e4f9d575ab7f653b9fc1d6bad0eab3f8d6e2ff0 | Rafaelbarr/100DaysOfCodeChallenge | /day024/001_linear_regresion.py | 2,651 | 4.125 | 4 | # -*- coding: utf-8 -*-
def run():
# List creation for data storage and variables
x_values = []
y_values = []
summation_of_y_times_n = 0
sum_of_y_values = 0
summation_of_n = 0
summation_of_n_pow_2 = 0
summation_of_n_powered_by_2 = 0
slope = 0
average_of_y = 0
av... |
1946dae4dda1f63c4079f72e1059ad5bfd649e71 | 2SEHI/Python-Programming-Test | /programmers/weekly5.py | 474 | 3.765625 | 4 | ## 문제 풀이 : https://2sehi.github.io/programming%20test/54_Programming_Test/
def solution(word):
alphabet = ['A', 'E', 'I', 'O', 'U']
word_dict = []
from itertools import product
for i in range(1, len(alphabet)+1):
result = list(map(lambda x: ''.join(x), list(product(alphabet, repeat=i))))
... |
92b5c22d747b362841fdb9c72b61b6fec9acb3d1 | ynigoreyes/Parser | /Scanner.py | 5,523 | 3.546875 | 4 | from BadTokenExpection import BadTokenExpection
class Scanner:
@staticmethod
def scan(content: str):
"""
Will take a string and tell you what the tokens are
and what the token values are
"""
tokens = []
tokenValues = []
position = 0
while positi... |
e987a43990aa12acacef73256bd353ba17d5c5c6 | danvb112/introducaoPython | /capitulo 5/exercicio 5.4.py | 99 | 4.09375 | 4 | fim = int( input( "Insira seu número aqui: "))
x = 1
while x <= fim:
print (x)
x = x + 2
|
5b851ba90b1818a9165495badf89edcf14744e87 | Dogeuzman/Stack-Using-Python | /Stack-Implementation-(Python).py | 866 | 3.890625 | 4 | class Stack():
def __init__(self, stack_size):
self.stack_arr = []
self.stack_size = stack_size
def isEmpty(self):
return len(self.stack_arr) == 0
def isFull(self):
return len(self.stack_arr) == self.stack_size
def pushStack(self, item):
if(self.isF... |
145164c42c85c5cfe1818ee52bc694250b7f796d | nekoTheShadow/algorithm-and-data-structure | /ch09/q_09_01.py | 2,485 | 4.09375 | 4 | class Node(object):
def __init__(self, value, next):
self.value = value
self.next = next
class LinkedList(object):
def __init__(self):
self.node = None
self.size = 0
def add(self, value):
self.size += 1
if self.node is None:
self.node = Node... |
bdf59e27e1c1042a45a9d63926b0149601d4619a | jedzej/tietopythontraining-basic | /students/synowiec_krzysztof/lesson_01_basics/school_desks.py | 333 | 3.5 | 4 | import math
def minDeskNumber(numberOfStudents):
return math.ceil(numberOfStudents/2)
def main():
aClassDesks = minDeskNumber(int(input()))
bClassDesks = minDeskNumber(int(input()))
cClassDesks = minDeskNumber(int(input()))
print(aClassDesks + bClassDesks + cClassDesks)
if __name__ == '__main__'... |
91f7b7df88bf4d315f4d32932b7f3d810f3178d3 | lacra-oloeriu/learn-python | /ex21.py | 698 | 3.984375 | 4 | def add(a, b):
print(f"ADDING {a}+{b}")
return a + b
def subtract(a, b ):
print (f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a , b ):
print (f"MULTIPLYING {a} * {b}")
return a * b
def divide (a ,b ):
print(f"DiVIDING {a} / {b}")
return a / b
print("Let's do some math whit j... |
e5bf3801cff9ad2d0ecaef70699dd63d9d7bd8f2 | nasingfaund/contact-book | /contactbook/view.py | 3,940 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from PyInquirer import prompt
from tabulate import tabulate
# A list of prompts used when adding a new contact or updating one.
CONTACT_FIELDS = [
{
'type': 'input',
'name': 'first_name',
... |
ccb4107864a9755fd329cc91fa8be7f43649d05f | cocvu99/head-first-python | /chapter1/page15and16.py | 245 | 3.84375 | 4 |
movies = ["The Holy Grail", "The Life of Brian", "The Meaning of Life"]
for each_item in movies:
print(each_item)
print("----------")
count = 0
while count < len(movies):
print(movies[count])
count = count + 1
print("----------")
|
aeaec5931a4eb757027f541e51990cd09ad688ac | PierreVieira/Python_Examples | /Fibonacci memorizado.py | 296 | 3.96875 | 4 | from functools import lru_cache
@lru_cache(maxsize=50000)
def fibonacci(n):
if n == 1 or n == 2:
return 1
try:
return fibonacci(n - 1) + fibonacci(n - 2)
except RecursionError:
print(f'Erro de recursão para n = {n}')
exit(1)
print(fibonacci(500))
|
774f66b6a48413dbdb3d8691e5a5e576e759d977 | raun/Ceasar-Cipher | /findBestShift.py | 565 | 3.984375 | 4 | import string
def findBestShift(wordList, text):
"""
Finds a shift key that can decrypt the encoded text.
text: string
returns: 0 <= int < 26
"""
noWords=0
bestShift=0
Shift=0
while Shift<26:
decodedMessage = applyShift(text,Shift)
words = decodedMessage.split(" ")
... |
e7a929c69062dd3ac36be9b56d9006b067398d93 | goodboyhu/pythonrep | /02_Python面向对象2/文件和目录的常用管理操作.py | 664 | 3.5 | 4 | # 在 Python 中,如果希望通过程序实现上述功能,需要导入 os 模块
'''
文件操作
序号 方法名 说明 示例
01 rename 重命名文件 os.rename(源文件名, 目标文件名)
02 remove 删除文件 os.remove(文件名)
'''
# 提示:文件或者目录操作都支持 相对路径 和 绝对路径
'''
目录操作
序号 方法名 说明 示例
01 listdir 目录列表 os.listdir(目录名)
02 mkdir 创建目录 os.mkdir(目录名)
03 rmdir 删除目录 os.rmdir(目录名)
04 getcwd 获取当前目录 os.getcwd()
05 chdir 修改工作目录 o... |
02b4dc5754e897754af42972949c4201f3cd7903 | mebsahle/ICPC_Solved- | /Herman.py | 129 | 3.8125 | 4 | import math
R = int(input())
Area = math.pi*(R**2)
taxicab = R**2+R**2
print('{:f}'.format(Area))
print('{:f}'.format(taxicab))
|
4e8b6f19b749d7a1e85c360cf7c7f228c2a3905e | s-m-j/01_prog_python | /e1_2_25.py | 577 | 4.09375 | 4 | """
Проверка порядка. Составьте программу, получающую в аргументах ко
мандной строки три значения, х, у и z типа float, а выводящую True, если
значения расположены в порядке возрастания или убывания (х < у < z)
или (х > у > z), и False в противном случае.
"""
import sys
x = float(sys.argv[1])
y = float(sys.argv[2])
z... |
3f7a93a9ffc22bbef0c3e65426cd08cdd382a1e4 | cforrest96/prac_05 | /do_from_scratch.py | 292 | 3.65625 | 4 | user_str = str(input("Enter a string"))
a = user_str.split()
b = dict()
for word in a:
if word in b:
b[word] += 1
else:
b[word] = 1
for key, value in b.items():
print("{} {}".format(key, value))
for key in sorted(b):
print("{:13}: {}".format(key, b[key]))
|
0187d5aec84b5d3f07421bcdbd48f2f46d848025 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_203/473.py | 1,625 | 3.703125 | 4 | def solution(cake):
result = []
empty = "?" * len(cake[0])
current_line = empty
num_times = 1
for i in range(len(cake)):
if cake[i] == empty and current_line == empty:
num_times += 1
elif cake[i] == empty:
result.append(current_line)
else:
... |
ddbf0570ef48981a0f85a13b25e586dfa3085d40 | MatosOliveira/curso-cc-python | /exercicios/fatorial.py | 182 | 3.890625 | 4 | n = int(input("Digite o valor de n: "))
fatorial = 1
i = 1
if(n == 0):
print(fatorial)
else:
while(i <= n):
fatorial = fatorial * i
i = i + 1
print(fatorial) |
bc5fa8c2c77f1bf3625441ab336411c1499c2c9d | plus4u/python | /ml_python_basic.py | 2,890 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 5 19:01:26 2019
print(123 + 1)
print(10)
print(0o10)
type(10)
type(0o10)
4.2
type(4.2)
4.2e-4
print("I am a string.")
type("I am a string.")
print('foo\tbar')
type(True)
abs(-10.7)
any([1, 2, 3, 0])
eval('1+2')
eval("'hi' ... |
f25ce17ade3f07786b4b20e029f55c30c0d0a0dd | nelly-hateva/python-homeworks | /Homeworks/05/solution.py | 4,698 | 3.515625 | 4 | REPOSITORY = 'https://github.com/nelly-hateva/python-homeworks/tree/master/Homeworks'
# Двадесет неща, които научих:
#
# 1. Научих, че обекти, които не се изменят (като списъкът от интервалите
# за зодиакалните знаци в първа задача или като почти всички обекти от
# задачата за Морския шах), е добре да бъдат ... |
98f764d123d000e90d1ae670f263b777bd95a898 | rawrgulmuffins/ProjectEuler | /Question9.py | 341 | 3.671875 | 4 | #!/usr/bin/env python3.2
import math
def ProduceC(A, B):
C = A**2 + B**2
return math.sqrt(C)
def FindTriplet(target):
for A in range(1, target):
for B in range(A + 1, target):
C = ProduceC(A, B)
if C + A + B == target:
return A, B, C
return None
prin... |
5fb7cff27979fa0a31d91b1704fb62e51ccccb7f | Rarlegend/AcademicArbiter | /academicarbiter/algorithm.py | 5,488 | 3.765625 | 4 | #defines the actual algorithm
import course
class algorithm:
#your info
isemester = []
myCourseNames = []
iconcentration = ""
iyear = ""
#fall or spring semester
semNum = 0
#data set
students = []
#these are dictionaries
#the key is the name of the course or concentration
... |
88a188a4113ea1a6b5ec6f0e02bfc764e0ca87eb | serpherino/Cs-practicals | /6.py | 1,242 | 3.6875 | 4 | import csv
f=open(r"C:\Users\Samridh Girdhar\Documents\Python files\placement.csv","r+")
l=csv.reader(f)
l2=[]
cc=0
for i in l:
if cc==0:
cc=1
continue
else:
l2.append(i)
l=l2
del l2
del cc
while True:
f.seek(0)
x=input("enter question part letter : ")... |
e1633bba428e6041b864f489245258858fb54a8f | thomalm/project-euler | /problem-solutions/src/problem_22.py | 408 | 3.5 | 4 | """
Problem 22 - Names scores
"""
from string import ascii_uppercase
from collections import OrderedDict
alphabet = OrderedDict((ch, idx) for idx, ch in enumerate(ascii_uppercase, 1))
with open('Resources/p022_names.txt') as f:
data = f.readlines()
names = sorted(data[0].replace('"', '').split(','))
s = 0
for... |
24b59f476a73f3149685b8d52a29c4a2ba81986e | ishworii/LeetCode | /design_linked_list.py | 4,481 | 4.53125 | 5 | '''
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.
If you want to use the doubly linked list, you will ne... |
f050ae54a43ebdd85a0f60247e3448c3f71e9681 | gabriellaec/desoft-analise-exercicios | /backup/user_010/ch75_2020_04_10_23_13_47_088461.py | 726 | 3.609375 | 4 | def verifica_primos (lista):
dic={}
for numero in lista:
if numero==1:
dic[numero]=False
elif numero==2 or numero==3:
dic[numero]=True
else:
termos=numero-2
contador=[0]*termos
contador[0]=3
if numero%2==0:
... |
20a244c2092085746812d4ba4091f34be6a05832 | UieLinux/bookly | /areas/catalog/models/isbn.py | 2,093 | 3.671875 | 4 | import re
from wtforms import ValidationError
from flask import flash
isbn_pattern = re.compile('^(?:ISBN[-:]? ?)?(?:(?:\d+[- ]?){3}[\dX]|(?:\d+[- ]?){4}\d)$', re.I)
def extract_digits_from_value(value):
"""
Creates a list with all the digits found inside value.
"""
digits = [int(char) for char in va... |
906749c77fb8023238dd6b7e674f06f0f335b2c1 | tramsy/Snake-Game- | /snake.py | 3,719 | 3.53125 | 4 | import turtle
import random
import time
#score variables
score = 0
high_score = 0
#setup the screen
widow = turtle.Screen()
widow.title("Snake Game")
widow.bgcolor("Black")
widow.setup(width=600, height=600)
widow.tracer(0)
snake = turtle.Turtle()
snake.speed(0)
snake.shape("square")
snake.color("B... |
2f691c0beae17c3b5a137961acae48c696f08cb0 | MSAChowdhury/Python | /Prb4.py | 110 | 3.8125 | 4 | hour = input("Enter hour: ")
rate = input("Enter rate: ")
pay = (int(hour) * float(rate))
print("Pay: ", pay)
|
7746554fa1c3389e1615fb611585c018744a34de | michelleweii/Leetcode | /03_树与二叉树/222-完全二叉树的节点个数.py | 662 | 3.59375 | 4 | """
middle 2021-12-27 递归遍历
# 层次遍历记录节点变量++
# 后序遍历,与LC104二叉树深度类似
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:return 0
... |
ff8457b1e211a5e5340b2977294d5225fa2b337c | samuel112233/C100 | /C100.py | 559 | 3.5 | 4 | class Car(object):
def __init__(self,model,color,company,speedLimit):
self.model=model
self.color=color
self.company=company
self.speedLimit=speedLimit
def start(self):
print('started')
def stop(self):
print('stopped')
def accelarate(se... |
fa732030b50ccee42cfc2942ac39b2680e28ac9a | Mohitgupta94/Python-game | /code.py | 1,035 | 4.09375 | 4 | from random import randint
board=[]
new_row=['-','-']
position=[]
def add_row(n,new_row,board,position): #adds n rows
for i in range(n):
a=randint(0,1)
position.append(a)
board.append(new_row)
def print_board(board):
for row in board:
print " ".join(row)
def play(board,position,new_row):
user_guess=inp... |
2dbd4c7c9bd8c5f83d14e3535c0afc2bd10408d6 | wharward/CourseWork | /Python/Tutorial/Python in a day/ch10 - functions.py | 689 | 4.03125 | 4 | someValue = 10
def letsAdd (x,y):
addition = x+y
return addition
print letsAdd(3,5)
print someValue
#Make a function called subtraction
def subtraction(x,y):
#Make subtract variable equal to x
subtract = x-y
#Retrun subtract variable
return subtract
print subtraction(10,4)
def moreSu... |
115bc38c5ff33b0e4447c4e745e59f44e415fe91 | tcglezen/funExperiment | /trollingAshley/emailScramble.py | 813 | 3.875 | 4 | import random
import sys
fileName = sys.argv[1]
try:
file = open(fileName, "r")
except:
print("invalid input file, program is going to terminate")
sys.exit()
lineList = [line.rstrip('\n') for line in file]
#The entire email would ideally be a single string at this point
emailTxt = ''.join(line... |
e0c1c815da5cc38b4db8e6062cc53c50cec2fc92 | Sueda-gul/Pyhton | /02_karar_yapilari/0206_lab_pratikleri.py | 2,496 | 3.65625 | 4 | #region ornek_1
"""
bavulAgirligi = int(input('Lütfen Bavul Ağırlını Giriniz : '))
biletFiyat = float(input("Lütfen Bilet Fİyatını Giriniz : "))
if bavulAgirligi > 15:
fark = bavulAgirligi - 15
biletFiyat += fark*5
print(f"güncel bilet fiyatı {round(biletFiyat*1.18, 2)} TL.")
"""
#endregion
#region ornek_2
""... |
c79c884fad423f26a1648675d219bc7ec1fd1672 | toporny/ditflight | /dit_price.py | 7,203 | 3.953125 | 4 | import math
import sys
import itertools
class Price():
def __init__(self, app):
# initializes all data
self.__app = app
self.__aTravelPoints = []
def __checkInputData(self, sAairports):
""" checks input format data """
""" expected format data is: DUB,GDA,LON """
good_data_format = True
self.__aT... |
a8dfacd4bb3db3dfb0dc293e7753248e1fa7ab6d | onfire10/AdventOfCode | /Day3/main.py | 990 | 3.734375 | 4 | FILE_LENGTH = 323
A = [None] * FILE_LENGTH
TREE = "#"
def readFromFile(filename):
file = open(filename, "r")
for i, line in enumerate(file):
A[i] = line.rstrip('\n')
file.close()
def readArray(right, down):
lineLength = len(A[0])
treesCount = 0
j = right
for i in range(down, i... |
3a676316a2d6163101cdfebf50048bcd5cac9e31 | ElenaDolganova/Python-lesson-1 | /lesson3/hometask1.py | 397 | 3.875 | 4 | def calc_divide(num, denom):
try:
result = num / denom
return result
except ZeroDivisionError:
print("divide by zero, try again")
num1 = float(input("Введите первое число"))
while True:
num2 = float(input("Введите второе число"))
a = calc_divide(num1, num2)
if a is not None... |
e7640230c393b24997dfe3ab2fa2e661b368e28a | sishijing/general_coding_challenges | /findMaxSubarray.py | 2,015 | 4.125 | 4 | """
find the maximum sum of subarrays of an input array
If the input array has all positive elements, then the maximum
will be the sum of whole array. If it has negative values, the maximum
will be the sum of one certain subarray.
The following approach uses the idea that the sum of an subarray
starting from i-th ele... |
5402d12e01ba5922941aba2107c3988162f14fa3 | ihuei801/leetcode | /MyLeetCode/python/Min Stack.py | 1,197 | 3.71875 | 4 | ###
# Stack
# Push: O(1)
# Pop: O(1)
# Top: O(1)
# getMin: O(1)
# Space: O(n)
###
#class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.min_st = []
self.st = []
def push(self, x):
"""
:type x: int
... |
3cb3c97fc57030c57cd20e0c0c55ec81a25382a3 | vakulenkoannag/gloss | /class/словари 4.py | 628 | 3.8125 | 4 | import collections
d = {2: 'He', 3: 'Li', 4: 'Be'}
d[1] = 'H'
print('Случайный порядок')
for k, v in d.items():
print(k,v)
print('Упорядочено по ключам')
for k in sorted(d):
print(k, d[k])
print('Упорядочено по значениям')
for k in sorted(d, key=d.get):
print(k, d[k])
ordered_dict = co... |
c75fde359772f6d2b47363d54d8b7966fe9731b3 | saralynn80/movie-recommendations | /system-testing/make_recommendations.py | 2,152 | 3.546875 | 4 | import numpy as np
import pandas as pd
import matrix_factorization_utilities
# Load user ratings
raw_dataset_df = pd.read_csv('movie_ratings_data_set.csv')
# Load movie titles and genres
movies_df = pd.read_csv('movies.csv', index_col='movie_id')
# Convert the running list of user ratings into a matrix
ratings_df = ... |
3f60c1a5673965dbadf990833bb6de54dcf8f714 | bionictruck/python_class | /Week5/pay.py | 330 | 3.953125 | 4 | try:
hrs = raw_input("Enter Hours:")
h = float(hrs)
rate = raw_input("Enter Rate:")
r = float(rate)
except:
print "Please enter a numeric number"
quit()
def computepay(h,r):
if h <= 40:
pay = h * r
else:
pay = 40 * r + (h - 40) * (r * 1.5)
return pay
print compu... |
6b49a4b02f45af95f6ef73159ee0273cc66f14b9 | subreto-roy/Python | /centered_avg.py | 465 | 3.71875 | 4 | """
def centered_average(some_list):
sum=0
count=0
temp_list=some_list.sort()
for i in range(1,len(some_list)-1):
sum=sum+some_list[i]
count=count+1
return sum/count
a=[1,2,3,4,5]
print(centered_average(a))
import copy as cp
s=[10,20]
s.append(60)
n=cp.copy(s)
... |
d057f618c6a611f993ad823fd965dc273dc719e8 | BibekMagar99/Hacker-Rank-Python-challenges-solutions- | /Input().py | 204 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 30 14:34:48 2021
@author: bibek
"""
x, k = map(int,(input().split()))
P = input()
if k == eval(P):
print("True")
else:
print("False")
|
e8e514b3de231d166e148a6c026e77e7cae944bd | green-fox-academy/ilcsikbalazs | /week-03/day-3/02exercise.py | 422 | 3.875 | 4 | from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# draw a box that has different colored lines on each edge.
box = canvas.create_rectangle(50,50,250,250, fill = "yellow")
green_line = canvas.create_line(50,50,250,50, fill = "green")
red_line = canvas.create_line(50,50,... |
10b1d7e982c6639d1e1d17e2173cb546d30cdb26 | henrygarrett/Project-Euler | /1st 10/Problem 5.0.py | 1,371 | 3.5625 | 4 | #complete
import math
def primefac(n):#returns list of prime factors with correct cardinality
divisor = [n]
again = True
def divisors(x):
check = math.floor(math.sqrt(x))
while check > 1:
if x%check == 0:
return check
else:
check -= 1
... |
ed27cf2cf056b0c1355184d38a641a02fb0d8c57 | satyam-seth-learnings/python_learning | /Python Built-in Modules/Python Collections Module/7.dequeue/7.reverse_And_rotate_Methods.py | 129 | 3.671875 | 4 | from collections import deque
de=deque([1,2,3,4])
print(de)
de.reverse()
print(de)
de.rotate(2)
print(de)
de.rotate(-2)
print(de) |
adccc49a5754677fb17a98aef83766683f181eb0 | zerodayz/dailycoding | /Data Structures and Algorithms/Binary_Tree.py | 1,963 | 4.1875 | 4 | # Binary Tree #1 First attempt
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def search(self, find_val):
"""
BFS - Level Orde... |
338bd87bd0bf018c37cf89d363f073c5dee5ad3c | JuliyShulaeva/TPG | /1sem/1_laba_a/11.py | 874 | 3.5 | 4 | import turtle
turtle.color("red")
turtle.penup()# Поднимаем курсор
turtle.goto(125, 135)# Переходим по нужным координатам
turtle.pendown()# Опускаем курсор
turtle.right(45)
turtle.forward(70)
turtle.color("black")# Устанавливаем цвет черепашки
turtle.penup()# Поднимаем курсор
turtle.goto(0, -25)# Переходим... |
6f91cd930fbe4c688edb4855978717dee24f5cf4 | ovasquezz/python | /Practica 5/ejer 1.py | 316 | 3.890625 | 4 | for i in range(10):
print(i+1)
print("------------------")
for i in range(10):
print(i+i+2)
print("------------------")
for i in range(10):
print(i+i+20)
print("------------------")
for i in range(6):
print(i*4+10)
print("------------------")
for i in range(9):
print(-i*5+40)
|
8e3836714c1ed116fb3d18ea4e2cd689538c7150 | shunyooo/bitcoin_bot | /learner/polynomial.py | 1,152 | 4.0625 | 4 | # 1次元の多項式による近似曲線を求めるもの。
import numpy as np
from logger import get_module_logger
logger = get_module_logger(__name__)
def polyfit(x, y, deg):
"""
Summary: 近似曲線と、その勾配のコールバックを返却。
Attributes:
@param (x):np.array
@param (y):np.array
@param (deg):近似多項式の次数
Returns: poly, grad
"""... |
0d1c082b5ee170f6fd9bc5e35dd97e789e5d3147 | SaraBenShabbat/Python-Scripts | /strings2.py | 1,162 | 4 | 4 | parrot = "Norwegian Blue"
print(parrot)
print(parrot[3])
print(parrot[4])
print(parrot[9])
print(parrot[3])
print(parrot[6])
print(parrot[8])
print()
print(parrot[-1])
print(parrot[-14])
print()
print(parrot[3 - 14])
print(parrot[4 - 14])
print(parrot[9 - 14])
print(parrot[3 - 14])
print(parrot[6 - 14])
print(par... |
720d26fa75d1f0b853ad4a8027e28f120d3e8416 | fadi721994/AI_2 | /step.py | 733 | 3.578125 | 4 | import utils
from direction import Direction
class Step:
def __init__(self, name, direction, amount):
if direction == 'U':
direction = Direction.UP
elif direction == 'D':
direction = Direction.DOWN
elif direction == 'R':
direction = Direction.RIGHT
... |
53ac9c04c5ac8a384cc3d9a00f96644c041ef687 | waseemakhtar/python | /string_manipulation/pig_latin.py | 607 | 4.15625 | 4 | '''
pig latin is the output for the given word which moves the
starting alphabet of the word to the end and appends 'ay'
at the end.
For example, if the word is 'hello', the pig latin output
is 'ellohay'
'''
input_letter = input("Enter the string:")
#return the letter at the location 0
first_letter = in... |
8194192c7e4d4fff0dae459ea6ab63eef208bdb5 | Harshill/Plaython | /Challenges/Checkio/hamming_distance.py | 683 | 3.9375 | 4 | # Hamming Distance = sum of the bit differences between two integers in binary
from math import floor
def count(num1, num2):
return len([char1 for char1, char2 in zip(num1,num2) if char1 is not char2])
def hamming(n, m):
num1 = str(bin(n))[2:]
num2 = str(bin(m))[2:]
diff = len(num1)-len(num2)
... |
e1b62fc03a093f3cb9e0113e271f486d668d34ae | Newbie-learn/Python- | /Love Calculator.py | 868 | 4.03125 | 4 | print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# Love Calculator Using Name
final_score = name1 + name2
lower_case_string = final_score.lower()
#TRUE LOVE COUNT
t = lower_case_string.count("t")
u = lower_case_string.count("r")
r =... |
50663da0f6777d2e8b928ea558403e3a7ff1e3fb | ErlangZ/projecteuler | /34.py | 1,070 | 3.5625 | 4 | # coding:utf8
#from __future__ import print_function
import operator
# Waring:0的阶乘是1
X = [1]+[reduce(operator.mul, xrange(1, i+1)) for i in xrange(1,10)]
#method1
#任何一个8位数,它的数字阶乘和最多只有7位 9!*8,那么这是搜索的上限
# ca, 11s就跑完了
def digit_factorials_sum(x):
return sum([X[int(i)] for i in str(x)])
large = 8*X[9]
print [i for i in x... |
7c9f49f4056f0b54b4166ae2555b84a33461444c | TKzizo/Py_Lab | /project3/4_rock_paper_scisor.py | 383 | 3.78125 | 4 | #!/usr/bin/python
import random
def play():
player = input("chose rock(r),scisor(s),paper(p): ")
me = random.choice(["r","s","p"])
if player == me:
return "Oooh it's a tie !! "
if win(player,me):
return "you won"
print("yaaay i won !!!")
def win(p,o):
if ( p == "r" and o == "s") or ( p == "s" and o == "... |
0f1a4f119dfd64ec8928c68008ffe64fa430ca6d | Hoon94/Algorithm | /Leetcode/74. Search a 2D Matrix.py | 901 | 3.65625 | 4 | from typing import List
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix:
return 0
m, n = len(matrix), len(matrix[0])
if not n:
return 0
r, r1, r2 = -1, 0, m - 1
while r1 <= r2:
mid = ... |
2918984010ce421340892d875f4aedfd6bbac615 | zzy1120716/my-nine-chapter | /ch05/0901-closest-binary-search-tree-value-ii.py | 3,892 | 3.671875 | 4 | """
901. Closest Binary Permutation Tree Value II
Given a non-empty binary search tree and a target value,
find k values in the BST that are closest to the target.
样例
Given root = {1}, target = 0.000000, k = 1, return [1].
挑战
Assume that the BST is balanced, could you solve it in
less than O(n) runtime (where n = t... |
717b23ff838111b084901ebcaa871126a164df0a | haidar145kahs/python | /HQ9+.py | 258 | 3.75 | 4 | prog = input()
tmp = ''
for i in range(len(prog)):
if prog[i]=='Q'or prog[i]=='H'or prog[i]=='9':
tmp = 'YES'
#print(tmp)
break
else:
tmp = 'NO'
break
#print(tmp)
print(tmp) |
d5fd0cffbd08ce87d14f3485e0c16924979d2d0a | ASIMER/Logika | /python_pro/while_loop/task_19.py | 347 | 4.5 | 4 | """
Программа, считающая цифры.
Пользователь вводит целое число.
Напиши программу, которая считает и выводит количество цифр в этом числе.
"""
n = int(input())
decimals = 1
while n // (10 ** decimals):
decimals += 1
print(decimals) |
fe2467cd9d4a82ed4982723a3c5536c98e1bd9aa | xiefei0117/USDA-census-data-extraction-tool | /process_USDA_Chapter2_02282020.py | 11,853 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 14:53:33 2019
Retreve value from specific table based on whether county listed as row or column
Examples:
print(california.retreve_value_county_as_column('Table 2', 'Tulare', 'Cattle and calves', '$1,000, 2017'))
print(california.retreve_value_county_as_c... |
a568880514a6d837642da41854ea5332ce38c03e | Gackle/leetcode_practice | /108.py | 1,219 | 3.734375 | 4 | # coding: utf-8
""" 108. 将有序数组转换为二叉搜索树
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
"""
from typing import List
from tree_util import TreeNode, initial_tree
cl... |
3b1af1ab209ccc65b6e07a98fbe99e87ab0abb61 | marinaoliveira96/python-exercises | /curso_em_video/0054.py | 363 | 3.921875 | 4 | from datetime import date
atual = date.today().year
maiores = 0
menores = 0
ano = 0
for c in range(1, 8):
ano = int(input(f'Em que ano a {c}° pessoa nasceu? '))
if atual - ano >= 18:
maiores += 1
else:
menores += 1
print(f'''Ao todos tivemos {maiores} pessoas maiores de idade
E também tivemo... |
ef161b2c594be5873432cb08963f8ac56597c45e | noahhancock/python_portfoilo_2022 | /tic_tac_toe.py | 4,488 | 3.921875 | 4 | #noah hancock
# Tic Tac Toe
# 11/11/19
#Global constants
X="X"
O="O"
NUM_SQUARS= 9
TIE= "TIE"
EMPTY= " "
#working
def instructions():
"""Display game instructions"""
print(
"""
Welcome to the game called Tic-Tac-Toe.
you will make your move by entering a number, 1-9. The num... |
6c3b89d6f3e0ba3b8aaf638b57d63b16831e3755 | AlyoshaS/codes | /startingPoint/Inicial/13.py | 197 | 3.984375 | 4 | # Leia um ângulo em radianos e apresente-o convertido em graus
P = int(input("Digite aqui com comprimento em polegadas: "))
C = (P * 2.54)
print ("O comprimento em centímetros é:",C,"cm")
|
19ced3176be4c7ad3465d55ec05a525e22f8c36d | JC6/coursera-py4e-assignments | /chapter_02/assignment_2_3.py | 88 | 3.859375 | 4 | hrs = input("Enter Hours:")
rate = input("Enter Rate:")
print(float(hrs) * float(rate))
|
5290ebb34dfdb512da69684d16370a7ca1ad1d16 | caibacord6/Programming-2020B | /proveedores.py | 2,812 | 3.515625 | 4 | import os
from logueo import *
Proveedores = []
def proveedores ():
os.system('clear')
print(":::: MENU PROVEEDORES ::::")
print("[1.] INGRESAR NUEVO PROVEEDOR")
print("[2.] LISTAR PROVEEDORES")
print("[3.] BUECAR PROVEEDOR")
print("[4.] MODIFICAR PROVEEDOR")
print("[5.] ELIMINAR PROVEEDOR")
print("[6.... |
83bf4705f16a8f0d5ee0aa4b3713831e9e3ef917 | clevercoderjoy/Competitive-Coding | /LC_Sentence Similarity III.py | 1,953 | 3.890625 | 4 | # 1813. Sentence Similarity III
# Medium
# A sentence is a list of words that are separated by a single space with no leading or trailing spaces.
# For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words consist of only uppercase and lowercase English letters.
# Two sentences sentence1... |
2eaabf0193d7f9d7ab96105a1ec7bc0b3f7a075f | forzen-fish/python-excel | /获取列表.py | 1,249 | 3.609375 | 4 | """
1:获取大表名字列表√
2:获取小表名字位置√
3:比对大小表名字是否相同√
4:如果大表内有小表的名字,删除小表内的名字√
"""
import xlrd
from xlutils.copy import copy
import os
#获取大表名字,形成列表,并整理
#打开文件
dabiao = xlrd.open_workbook("经管(913).xls")
sheet_dabiao = dabiao.sheets()[0]#实例化对象
namelist_1 = sheet_dabiao.col_values(3) #取姓名列表
#删除列表中第一个‘姓名’,与最后一个空,从而获得一个可以遍历的列表
del n... |
e96ce7d154d73462a1f90b23028ea4882341ff40 | PREDEEPKUMAR/python-level-1 | /Functions/Function.py | 2,466 | 4.25 | 4 | # Function -- Returns a Value (None or Real) based on the given argument.
# Arguments -- Fixed Length & Variable Length
# Variable function arguments or Non-Keyword Arguments
# Python Default arguments
# Python Keyword arguments
# Python Arbitrary arguments
#Non-Keyword Arguments
def sample(a,b):
resu... |
69fa75a94356b18846b61ace586f2de08e0a41ce | Vutov/SideProjects | /Udacity-Nanodegree-Machine-Learning/3. P1 Predicting Boston Housing Prices/AverageMedals121.py | 728 | 3.9375 | 4 | from DataFrame71 import create_dataframe
import numpy
from pandas import DataFrame, Series
def avg_medal_count():
"""
Using the dataframe's apply method, create a new Series called
avg_medal_count that indicates the average number of gold, silver,
and bronze medals earned amongst countries who earned ... |
6d1067f3abed236b718630e103254742c5caa82b | a-meijer/csc464-a1 | /producers-consumers.py | 2,204 | 3.84375 | 4 | '''
NAME: producers-consumers.py
AUTHOR: Andrew Meijer V00805554
This program is based on the threading code found here:
https://www.tutorialspoint.com/python3/python_multithreading.htm
'''
#!/usr/bin/python3
import queue
import threading
import time
import os
import psutil
exitFlag = 0
startFlag = 0
# Pseudocode fo... |
06b57696b456f2800b24553a503ae3edfb91f766 | zhou-jia-ming/leetcode-py | /problem_1248.py | 1,360 | 3.609375 | 4 | # coding:utf-8
# Created by: Jiaming
# Created at: 2020-04-21
# 给你一个整数数组 nums 和一个整数 k。
#
# 如果某个 连续 子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。
#
# 请返回这个数组中「优美子数组」的数目。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/count-number-of-nice-subarrays
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import *
class Solut... |
9d8984394ebeb3adb1b75335d74f4e6293a50617 | PabloAballe/Python-facil-y-practico | /dados.py | 1,603 | 3.765625 | 4 | #juego de dados para dos jugadores
#importamos la random
from random import randrange
#Mensaje de bienvenida
print("Bienvenido a Dados Python")
#determinamos un ganador
ganador=0
bot_ganador=0
nombre_ganador=""
numero_bot=0
n_bots=0
#pedimos el numero de jugadores
n_jugadores=int(input("¿Cuantos jugadores human... |
390a1eaad9cd7d932c3edae1957b8421da52a049 | Laxmivadekar/lucky | /harshad no. 1 to 100.py | 176 | 3.578125 | 4 | num=1
while num<=100:
sum=0
temp=num
while temp>0:
rem=temp%10
sum=sum+rem
temp=temp//10
if num%sum==0:
print(num)
num=num+1 |
fd8439266b352fe540a14fe271d1a2be2ae06ea9 | hit-joseph/lexical-paraphrase-extraction | /spider/summary.py | 1,917 | 3.65625 | 4 | # coding:utf-8
# 命令行参数传递,例如输入: python <文件名>.py -help
# 这个结果就会打印help
# sys.argv[0]代表"文件名",第一个参数是sys.argv[1]
import sys
import json
def load_json(json_file):
with open(json_file, "r")as load_f:
data = json.load(load_f)
return data
def store(data, outfile):
with open(outfile, 'w'... |
e69b3472b1c29fae605ea561ae0b8db55536f164 | ashish717744/infyTQ | /problem12.py | 612 | 4.09375 | 4 |
#Write a Python function which accepts a string and returns a string made of the first 2 and the last 2 characters of the given string.
#If the string length is less than 2, return -1.
#Note: If the string length is equal to 2, consider the 2 characters to be the first as well as the last two characters.
#Sa... |
e29be068c3a3450961948306b8404630a1f1014f | Arnukk/DAA | /Hmw3/Q2_2.py | 2,499 | 3.703125 | 4 | __author__ = 'akarapetyan'
# A simple function for reading the file and checking whether the data is compatible with the input rules
def checkMe(function):
#Loading the input file
try:
f = open("test.in", 'r')
firstLine = f.readline().split()
n = int(firstLine[0])
newweights = ... |
03f0de1adff9f4dfc7ac116341ebfa12294a940d | huangdehui2013/Grenchmeter | /Cmeter/utils/Timing.py | 1,194 | 3.703125 | 4 | """
A module that helps to inject time profiling code
in other modules to measures actual execution times
of blocks of code.
"""
__author__ = "Anand B. Pillai"
__version__ = "0.1"
import time
def timeprofile():
""" A factory function to return an instance of TimeProfiler """
return TimeProfi... |
32707a33c9c8c7afd455aa326fbe43cbc2da56c1 | aboutroots/AoC2020 | /day16.py | 3,106 | 3.75 | 4 | import re
from collections import namedtuple
from typing import Dict, List
Rule = namedtuple("Rule", "min1 max1 min2 max2")
RulesDict = Dict[str, Rule]
Ticket = List[int]
TicketList = List[Ticket]
def parse_input(filename: str) -> (RulesDict, Ticket, TicketList):
with open(filename, "r") as file:
conte... |
d0eb89020622658d420adffbe26e1c465b628ae2 | YDrall/laboratory | /python/lpthw/fib_hints.py | 369 | 3.875 | 4 | prev = {0: 0, 1: 1}
def fibonacci(n):
if prev.has_key(n):
return prev[n]
else:
new_value = fibonacci(n-1) + fibonacci(n-2)
prev[n] = new_value
return new_value
if __name__ == "__main__":
from sys import argv
if len(argv) != 2:
print "usage: %s range" %(argv[0])
... |
879a6ff6bfc9928c5cf591068dea5d659f2f0e10 | Anjali1409/Python-Programming | /Player/reverse string.py | 42 | 3.515625 | 4 | a=input()
a=''.join(reversed(a))
print(a)
|
ebb0740d0b08263a0a8540d36a3a88af1c1dd38d | sankhaMukherjee/RLalgos | /src/lib/agents/randomActor.py | 1,008 | 4.03125 | 4 |
import numpy as np
class randomDiscreteActor():
def __init__(self, stateShape, numActions):
'''a random discrete actor
A discrete action space is one where the actor will return
an integer which will represent one of n actions. This actor
will return a random action independent of the state the
enviro... |
fa4fb7227e57658df1e896c07b3669f04aee04c1 | niteshreddy/euler | /p7.py | 544 | 4.1875 | 4 | '''
Given n, determine the nth prime number.
'''
'''
Function that determins if a given number is prime or not.
'''
def isprime(n):
if n == 1: return False
for i in range(2,int(n**0.5)+1):
if n%i == 0:
return False
return True
'''
Determines the nth prime number.
'''
... |
911c361c497be6c76fd97bb850fc1ad671942218 | girdhar64/Machine_learning | /Regression/decison_tree_regression.py | 826 | 3.734375 | 4 | # Decision Tree Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
# Fitting Decision Tree Regression to the datase... |
c3281330b4995069d10ebbca6d8fdabfb552f239 | mantydze/knapsack-problem-py | /naive_recursive.py | 1,241 | 3.765625 | 4 | """
Knapsack problem.
Naive recursive implementation. Try all combinations (Bad idea)
Complexity is exponential (2^n) where n is number of items.
"""
def ks(capacity_left, n, weights, values):
"""
capacity_left (int): remaining storage capacity of a bag
n (int): current item position
weig... |
7404fd770598e19291c43eb94a350432a1c68306 | lindo-zy/leetcode | /备考/1209.py | 477 | 3.71875 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
from collections import defaultdict
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
ds = defaultdict(int)
for i in s:
ds[i] += 1
if ds[i] == k:
del ds[i]
return ''.join(ds.keys())
if __na... |
bd6e1eda28da599afc7d22575f3292e0319f1c14 | Guiyaugusto/Facilitador-de-Troco | /Facilitador/facilitador_troco.py | 1,337 | 3.734375 | 4 | print("Virgulas ou pontos nao sao necessarios. Os ultimos 2 algarismos sao obrigatoriamente centavos. Exemplo:\n1234 sao equivalentes a 12 reais e 34 centavos.")
Valor_conta = int(input("Valor da conta: "))
Valor_recebido = int(input("Valor dado pelo clinte: "))
Valor_troca = Valor_conta - Valor_recebido
if Valor_troca... |
94b210cd25b12d890022d4b2e2914ed141c22358 | daniel-reich/ubiquitous-fiesta | /ZwmfET5azpvBTWoQT_24.py | 261 | 3.75 | 4 |
def valid_word_nest(word, nest):
while len(nest) > len(word):
if nest.count(word) == 1:
index = nest.index(word)
else:
return False
nest = nest[ : index] + nest[index + len(word) : ]
return word == nest
|
f03cd12b4863a450d759905ccf552ead3663ebbe | lishulongVI/leetcode | /python3/221.Maximal Square(最大正方形).py | 1,109 | 3.765625 | 4 | """
<p>Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.</p>
<p><strong>Example:</strong></p>
<pre>
<strong>Input:
</strong>
1 0 1 0 0
1 0 <font color="red">1</font> <font color="red">1</font> 1
1 1 <font color="red">1</font> <font color="r... |
325f973604539763fa31d75b1c54446e54f46bb9 | StavrGeek/Lesson_1 | /Task_3.py | 275 | 3.609375 | 4 | user_value = input("Введите число: ")
double_value = user_value + user_value
triple_value = user_value + user_value + user_value
print(f"Сумма {user_value}+{double_value}+{triple_value} равна : {int(user_value)+int(double_value)+int(triple_value)}")
|
3f35c0551a8f555ab3c8d6ec6cfb828964538808 | sjbarag/CS260-Programming-Assignments | /pa1/p5-3.py | 5,030 | 3.5 | 4 | from timeit import Timer
class Node:
def __init__(self):
self.cargo = None
self.nxt = None
def __str__(self):
return str(self.cargo)
class myList:
def __init__(self):
self.head = None
self.cur = None
# clear list
def MAKENULL() :
temp = myList()
return temp
# return head of list
def FIRST(lst) ... |
7f77bfeaf99ef72feae46e9b9966b58ba026ec89 | ProfessorJas/Python_100_days | /day_031/class_combination.py | 2,214 | 3.96875 | 4 | class Person(object): # Define a Person class
def __init__(self, name, age, gender, birthday, address, contact):
self.name = name
self.age = age
self.gender = gender
self.birthday = birthday
self.address = address
self.contact = contact
def printBaseInf... |
a63fcbfe512c72c3edd858c628e66350fa0f3360 | GabrielANM/Meus-projetos | /binomial.py | 726 | 3.75 | 4 | def fatorial (numero):
n = numero
fatorial = 1
passagem = False
conta = numero * (numero - 1)
n = n - 1
if numero < 0:
return 0
if numero == 2:
return conta
else:
while not passagem:
if numero == 0 or numero == 1:
return ... |
334448ac7271147bfa79912095450a20adb49744 | iamworthy/Beginner-Projects | /Basic_Calculator.py | 1,229 | 4.28125 | 4 | # test code for simple calculator
#def functions
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
#start
print('Select one of the following operations')
print('1 Add')
print('2 subtract')
print('3 ... |
dc92dd75f7373d59e28635a25c915a74a4b6158e | onkarj-98/Data_structures_and_Algorithms | /DP/canConstruct.py | 376 | 3.671875 | 4 | import string
def canConstruct(target, wordBank):
if target == "":
return True
for word in wordBank:
if target.index(word) == 0:
length = len(word)
suffix = target[length:]
if canConstruct(suffix, wordBank):
return True
return False
print(canC... |
ce3ead5799154a83503d608c60701960508737f4 | Santkey/KoW | /a-15.py | 466 | 3.703125 | 4 | # słownik kolekcja -dictionary
slownik = {1: "Poniedziałek", 2: "Wtorek", 3: "Środa", 4: "Czwartek", 5: "Piątek"}
slownik[6] = "Sobota"
print(slownik)
slownik["a"] = 1
print(slownik["a"])
print(slownik)
#print(slownik[8])
print(slownik.get(8, " Inny dzień"))
#for l in slownik: #iterowanie po kl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.