blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
1265124f1ed0f4b106e6543cda4d0a193c40938b | tristaaa/lcproblems | /twosumii.py | 569 | 3.625 | 4 | class Solution:
def twoSum(self, numbers, target):
"""
find the index(not zore-based) tuple where
the corresponding numbers add up to target number
:type numbers: List[int], a sorted arrray
:type target: int
:rtype: List[int]
"""
... |
dd462226f16e05633d1e7627310f29769d0638d1 | mghenry/csci-102-labs-mhenry | /cs102labs/Week4A-chess.py | 976 | 3.796875 | 4 | # Maggie Henry
# CSCI 102 – Section G
# Week 4 - Lab A - Missing Chess Pieces
# References: none
# Time: 20 minutes
king = int(input('KINGS>'))
queen = int(input('QUEENS>'))
rook = int(input('ROOKS>'))
bishop = int(input('BISHOPS>'))
knight = int(input('KNIGHTS>'))
pawn = int(input('PAWNS>'))
if king != 1:... |
1002468272b658efe5030f764aaafe9d3547c0d9 | silas-ss/aprendendo_python | /lista_exercicios_1/questao05.py | 346 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding:latin-1 -*-
preco_mercadoria = float(input('Preço da mercadoria: '))
desconto = float(input('Percentual de desconto: '))
valor_desconto = preco_mercadoria * (desconto / 100)
novo_preco = preco_mercadoria - valor_desconto
print ('- Valor do desconto: %.2f\n= Preço a pagar: %.2f' %(valor... |
32f8e47b3e70686ab6cc098ad2e70e8d96bf7c0a | aminul788/NSL-RAShip-Programm | /Deep-Learning-Guide/OpenCV/opencv04_shapes_and_texts.py | 796 | 3.640625 | 4 | '''
Date : 10/12/2020
Day : Thursday
Author : Md. Aminul Islam
E-mail : aminulbrur8@gmail.com
Subject: Deep Learning
Links : https://www.youtube.com/watch?v=WQeoO7MI0Bs
GitHub : https://github.com/murtazahassan/OpenCV-Python-Tutorials-and-Projects
Topic : OpenCV (Chapter-04): Shap... |
3f1ec3299b5cbdcdf6a31e743aa4365b196ba6fa | immortalmin/csk | /day5/xml模块.py | 1,604 | 3.578125 | 4 | #Author:immortal luo
# -*-coding:utf-8 -*-
import xml.etree.ElementTree as ET
#读取xml内容:
# tree = ET.parse('test.xml')
# root = tree.getroot()
# print(root.tag)
# # 一个节点有tag、attrib、text三个值
# # tag是标签的名字
# # text是标签的内容
# # attrib是标签属性的字典,通过字典的get('key')来获取对应的属性的值
# # 直接for chile in parent 来遍历节点下的子节点
# for child in root:... |
5af552d940a9f3c94c1b8de3da08269d28035508 | kimhyunkwang/algorithm-study-02 | /8주차/김현광/4주차_가로세로 숫자 퍼즐.py | 1,217 | 3.6875 | 4 | import sys
n = int(input())
matrix = []
for i in range(n):
matrix.append(list(map(int, sys.stdin.readline().split())))
def vertical(x, y):
if x + 3 <= n - 1:
result = 1
for i in range(4):
result *= matrix[x][y]
x += 1
return result
else:
return 0
de... |
361aaf44f0078ce022ac48c0f6496f010c69d70e | CharmingCheol/python-algorithm | /백준/그래프/2668(숫자고르기).py | 589 | 3.546875 | 4 | import sys
# 사이클 문제
def DFS(start, current):
# 현재 위치가 1인 경우
if visited[current]:
# 시작값과 현재값이 같은 경우(사이클인 경우)
if start == current:
result.append(start)
else:
visited[current] = 1
DFS(start, nums[current])
size = int(sys.stdin.readline())
nums = [0] + [int(sys.st... |
6fc28f080cae6bd522093df60c92150e9a139747 | sumeyaali/Code_Challenges | /Intro/evenDigitsOnly.py | 170 | 3.875 | 4 | def evenDigitsOnly(n):
n = str(n)
print(n)
for num in n:
print(num)
if int(num) % 2 != 0:
return False
return True
|
69da5aa9b4fc18bed883e84a3a0622f1f5768de0 | ArthurSilvaRodrigues/-infosatc-lp-avaliativo-01 | /Ativi-02-30.py | 192 | 3.875 | 4 | r = float(input('Digite quantos reais você tem na carteira: '))
d = float(input('Digite quantos esta a cotação do dolar: '))
print('Com {:.2f} reais você tem {:.2f} dolares'.format(r,r/d)) |
1202196945e57d177136295dd2f5c464c261d745 | Stachowiak27/Przyk-ad-1 | /PYTHON/Podstawy Python/KAT_PYT_W_04_Podstawy_Python-master/1_Zadania/Dzien_2/4_Moduły/math.tools/functions.py | 126 | 3.71875 | 4 |
def quadratic_function(a,b,c):
x = 2
result = (a*x)**2 + b*x + c
return result
print(quadratic_function(1,2,3)) |
612556ed6c44de8f6d64e9aa42cc0c3aaec374ef | rohitn12/Algorithms | /binarySearch.py | 766 | 3.828125 | 4 | def binarySearch(array , X, first , last ):
if(first <= last):
midPoint = (first + last)//2
if(array[midPoint] == X):
return midPoint
elif(array[midPoint] > X):
return binarySearch(array ,X , 0 , (midPoint-1))
else:
return binarySearch(array , X , ... |
7d05afce4800e027970c6523cb3f83abf677a020 | mihaivalentistoica/Python-Fundamentals | /python-fundamentals-master/09-flow-control/while-loop-exercise.py | 1,012 | 4.3125 | 4 | user_input = ""
# b. If the input is equal to “exit”, program terminates printing out provided input and “Done.”.
while user_input != "exit":
# a. Asks user for an input in a loop and prints it out.
user_input = input("Provide input: ")
# c. If the input is equal to “exit-no-print”, program terminates with... |
0c08cb9f945a80cfd02e9bd2288f7dea8e4d05ab | sharvan-sharma/Image-to-Text-Converter | /Ascii converter/ascii text to image converter/asciitexttoimg1.py | 3,548 | 3.625 | 4 | #import
import math
import os
from PIL import Image
#conversion of unicode text into image
def pixeltuple(c):
R = ord(c[0]);G = ord(c[1]);B = ord(c[2]);rgb=()
rgb=rgb+(int(R),int(G),int(B))
return rgb
#function to generate height and width
def imghw(fsize):
hwtuple=()
#if square root of file size is... |
1c5e37bbee88ffb059e3c1f35f160ced3ee0748e | devonzuegel/Project_Euler | /test runs (C, Java, & Python)/test2.py | 675 | 4.03125 | 4 | # define the Vehicle class
class Vehicle:
name = ""
kind = "car"
color = ""w
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
return desc_str
# test code
car1 = Vehicle()
car2 = Vehicle()
car1.name = "Fer"
car2.name = "Jump... |
fc72e851397d653283203f87961ab1d016254a76 | LaloValle/HOC5 | /Programa.py | 8,312 | 3.6875 | 4 | # -*- coding: utf-8 -*-
#@author: Lalo Valle
import Recursos as recursos
class Interprete:
def __init__(self):
self._indicePila = 0 # Indice de la siguiente casilla disponible
self._pila = [] # Pila utilizada en la ejecución del intérprete
def push(self,dato):
if type(dato) != Dato:
recursos.imprimirEr... |
6eda7f4712c80e6eb657a4d05478a2dc233f8cf4 | vicious-lu/python_learningTheBasics | /4 loops/printNumbers.py | 180 | 3.765625 | 4 | # 1 - 10
counter = 1
while counter <= 10:
print(counter)
counter += 1
print('\n\n') #separator
# 5 - 1
counter = 5
while counter != 0:
print(counter)
counter -= 1 |
911460ce6ee834ea696bb690a79c2dc7cce2f6ac | tanvi-arora/datasecurity | /code/portscanner.py | 1,134 | 3.875 | 4 | #################################
# create a simple Python-based port scanner. Using the socket library, you will create a script that iterates through a
# IP addresses, and will identify the active ports available for that IP address. At least ports
# corresponding to telnet, ftp SSH, smtp, http, imap, and https servi... |
1bd18a0a99ac3fd67bf6e53f5c40fa23b75b3769 | Akashutreja/Movie_website | /media.py | 835 | 3.625 | 4 | import webbrowser
class Movie():
"""This class store movie related information"""
def __init__(self, title, story_line, poster, movie_trailer, review):
"""this function will be called when a movie object is created
keyword argument:
self -- as a reference which called the constructor
... |
bd079d013163d1822247b583c74b63608b773d11 | LightingTom/LearnPython | /Multithread.py | 2,266 | 4.15625 | 4 | import time, threading
# 新线程执行的代码:
# threading.current_thread() will return an instance for the current thread
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
... |
711bb2972931ff20df473ded1375dbc929f963f6 | Rowing0914/TF2_RL | /tf_rl/env/cartpole_pixel.py | 2,168 | 3.515625 | 4 | from threading import Event, Thread
class RenderThread(Thread):
"""
Original Code:
https://github.com/tqjxlm/Simple-DQN-Pytorch/blob/master/Pytorch-DQN-CartPole-Raw-Pixels.ipynb
Data:
- Observation: 3 x 400 x 600
Usage:
1. call env.step() or env.reset() to update env state
... |
677e6ec7dec0a2e80112d2d5d5529b829507bd5a | GraceDurham/city_college_python_turtles | /week15_day1_classes_ellipse_quiz.py | 1,376 | 4.125 | 4 | import math
# Question 6
# Write a Python class to represent an Ellipse centered at the origin. An ellipse located at the point (0,0) in the Cartesian coordinate system can be uniquely identified by its semi-major, a and semi-minor axis, b. In your class include the following:
# an initializer
# all the accessors... |
d832cf2604328d1d6f5dc451edc29f663ac168a1 | kgautam2103/Python-Codes | /ListlengthFinder.py | 250 | 4 | 4 | #! /usr/bin/env python
__author__ = 'egamkar'
def ListLengthFinder():
input = raw_input("please input the list")
input_list = input.split()
count = 0
for char in input_list:
count += 1
print count
ListLengthFinder()
|
15ba5186feab1146dd141b8e4385c613cee01fa2 | Wisetorsk/BioSim | /biosim_project/biosim/animals.py | 8,084 | 3.609375 | 4 | # -*- coding: Utf-8 -*-
import numpy as np
import math
"""
Animals module
"""
__author__ = 'Marius Kristiansen, Kristian Frafjord'
__email__ = 'mariukri@nmbu.no, krfr@nmbu.no'
class Animal(object):
"""
Superclass "Animal" for herbivores and carnivores
"""
params = None
def __init__(self, weig... |
538b325ebdd069578eaf15516fd7158c9aad24aa | simran2508/Automatic_teller_machine | /ATM2.py | 2,954 | 3.96875 | 4 | print('WELCOME TO ATM')
restart=('Y')
chances=3
balance=999.12
while chances>=0:
pin = int(input('Please enter your 4 digit pin:'))
if pin==(4567):
print('you entered your pin correctly')
print('Please Press 1 For Your Balance Enquiry')
print('Please Press 2 To Make a Withdrawl')
... |
e5a23610217a5d02edf6096b3ced9cc39aeb4140 | madhuri-majety/IK | /IK-Class/Arrays/shuffle_a_deck_of_cards.py | 1,546 | 4.46875 | 4 | """
Given an array, write a program to generate a random permutation of array elements.
This question is also asked as shuffle a deck of cards or randomize a given array.
Here shuffle means that every permutation of array element should equally likely.
The solution that this API should provide should follow an uniform... |
4840b463387685709fece90fbe44bf4f2cbd7a34 | innoventurist/Neural-Networks-Deep-Learning | /Logistic_Regression_with_Neural_Network.py | 20,373 | 4.15625 | 4 |
# coding: utf-8
### Logistic Regression with a Neural Network mindset ###
#
# Goal: to build a logistic regression classifier to recognize cats.
# This shows how to do this with a Neural Network mindset, and will also hone intuitions about deep learning.
#
### Import Packages ###
#
import numpy as np
import matplo... |
c8f7b42821166efc4f6f2cfd13d2ffb3fe89ab38 | soumasish/leetcodely | /python/car_fleet.py | 1,100 | 4.21875 | 4 | """N cars are going to the same destination along a one lane road. The destination is target miles away.
Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the
target along the road.
A car can never pass another car ahead of it, but it can catch up to it, and d... |
eb45963823df035b4609e2d98eba691d2fe322c4 | Confucius-hui/LeetCode | /53. 最大子序和.py | 1,009 | 3.578125 | 4 | class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.maxSubRec(nums,0,len(nums)-1)
def maxSubRec(self,nums,start,end):
if start==end:
return nums[start]
mid = (start+end)//2
left = s... |
2251cfd7fa6b87db1e42c8495f5e329029927af6 | topherCantrell/class-IntroPython | /Topics/02_Variables_Functions/EX2_Conversions/miles_meters.py | 239 | 4.09375 | 4 | # Input and conversion in one step
feet = float(input('Number of feet: '))
miles = feet/5280 # 5,280 feet per mile
print(feet,'feet is',miles,'miles')
meters = feet * 0.3048 # Found this on the web
print(feet,'feet is',meters,'meters') |
f214b7c12d6e1dc1c369bf216b8c4a98d943942e | eguaaby/Exercises | /ex12.py | 197 | 3.828125 | 4 | # takes a list of numbers and makes a new list
# containing only first and last elements of the list
def getElements():
a = [5, 10, 15, 20, 25]
b = [a[0], a[-1]]
print b
getElements() |
56b67ce46d51a9202fc386df2d87c03f480e4c97 | theksenia/hm5 | /4.py | 255 | 3.734375 | 4 | import random
s = set()
for _ in range(0, 10) : s.add(random.randint(0, 100))
for i in s: print(i, end=" ")
print("\n")
a = int(input("Enter A: "))
is_found = False
for item in s:
if item == a:
is_found = True
break
print(is_found) |
748343acc1d82fe1eaba8958f8c9c16565f0d9bf | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/nDruP/lesson02/series.py | 4,337 | 4.1875 | 4 | import timeit
def fibonacci_recursive(n):
"""
Recursively compute the nth Fibonacci number (where n>1).
The 0th fibonacci number is 0
The 1st fibonacci number is 1
The nth fibonacci number is the (n-2)th - (n-1)th fibonacci number.
"""
if n == 0:
return 0
elif n == 1:
r... |
9abf3f8eecd6b09645ff30ace6eb0deeab8ddbed | pawansingh10/PracticeDemo | /InterviewQ/GCD.py | 623 | 3.9375 | 4 |
def gcd1(a,b):
"""Euclid Formula """
while b>0:
temp=a
a=b
b=temp%a
return a
def gcd2(a,b):
'''
if a<b:
small=a
else:
small=b
for i in range(1,small+1):
if a%i==0 and b%i==0:
gcd=i
return gcd
'''
#Best as complexi... |
6677d1e0eaa637e8ae9f79e21e841ed875f2255c | JenZhen/LC | /lc_ladder/Basic_Algo/dp/Unique_Path_II.py | 3,471 | 3.953125 | 4 | #!/usr/bin/python
# http://lintcode.com/en/problem/unique-paths-ii/
# Follow up for "Unique Paths":
# Now consider if some obstacles are added to the grids. How many unique paths would there be?
# An obstacle and empty space is marked as 1 and 0 respectively in the grid.
#
# Example
# [
# [0,0,0],
# [0,1,0],
# [... |
b19ff3d84fb3a23dd198170c0346e258950aff05 | cmorgantywls/pythonCalculator | /pythonATM.py | 3,030 | 4.03125 | 4 | import math
import random
useATM = False
balance=random.randint(100,100000)
def setPIN():
# to add later - make sure that PIN must be a four digit numeric value.
# either do some fancy string stuff or just make sure it falls between 1000 and 9999 IDK!
thePIN=int(input("Set your ATM PIN to access your acc... |
c9ca897e330a405a6ee84cc8695d0ad847fd2364 | bhagyashrishitole/coding-challenges | /LeetCode31DaysChallenge/Week1/cousins_in_binary_tree.py | 2,546 | 3.84375 | 4 | """
Problem Statement
Cousins in Binary Tree
Solution
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the va... |
714afc7faefc5964d008bb73515f5290ef97d7d3 | Daoudii/INFO-S2 | /TP/TP2/Exo1.py | 246 | 3.859375 | 4 | #Somme des entiers impaires inferieurs a N
n=int(input('Entrez un entier n : '))
#initialisation de s et de i
s=0
i=1
for i in range(1,n):
if i%2!=0:
s=s+i
print('la somme des entiers impaires inferieurs à n s=',s)
input()
|
672e5e938be4b6ee78260c9257800aa8e5a9a2ea | kanjansreekar/Linear-Regression | /Linear_Regression_math.py | 853 | 3.671875 | 4 |
# coding: utf-8
# In[6]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
get_ipython().magic(u'matplotlib inline')
dataset = pd.read_csv('C:\Users\Sreekar\Desktop\Linear_Regreesion_Salary_Data.csv')
print(dataset.describe())
# In[7]:
x = dataset['Salary'].values
y =... |
25b8f3ff709ba99696d9000e90541c17beef98d3 | lcsm29/project-euler | /py/py_0162_hexadecimal_numbers.py | 1,130 | 3.671875 | 4 | # Solution of;
# Project Euler Problem 162: Hexadecimal numbers
# https://projecteuler.net/problem=162
#
# In the hexadecimal number system numbers are represented using 16 different
# digits:0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,FThe hexadecimal number AF when written
# in the decimal number system equals 10x16+15=175. In ... |
8c66cf2901f476f09c9923323049a4efca495890 | scperkins/martyr2_Mega_Project_List | /gradebook/student.py | 1,276 | 4 | 4 | class Student(object):
def __init__(self, firstName, lastName, year, gpa):
self.firstName = firstName
self.lastName = lastName
self.year = year
self.hw_scores = []
self.test_scores = []
self.gpa = gpa
def add_hw_score(self, hw_score):
self.hw_scores.appe... |
a1a994f526c4b6d096608817b4c5297b5178d063 | AndrewAct/DataCamp_Python | /Preprocessing for Machine Learning in Python/Selecting Features for Modeling/03_Exploring_Text_Vectors_Part_I.py | 1,186 | 3.9375 | 4 | # # 6/25/2020
# Let's expand on the text vector exploration method we just learned about, using the volunteer dataset's title tf/idf vectors. In this first part of text vector exploration, we're going to add to that function we learned about in the slides. We'll return a list of numbers with the function. In the next e... |
67b8d03b5667d1a339a23723dcaf6de0083a4188 | BlakeBagwell/week_one | /list_exercises/mult_vector.py | 155 | 3.609375 | 4 | #multiply vectors
given1 = [2, 4, 5]
given2 = [2, 3, 6]
newList = []
for i in range(len(given1)):
newList.append(given1[i] * given2[i])
print newList
|
bfe9ae116d2c30d72492da4115ec3db200af3fba | AdamZhouSE/pythonHomework | /Code/CodeRecords/2744/60825/298992.py | 444 | 3.65625 | 4 | t=""
while True:
try:
ts=input()
t+=ts
t+="#"
except:
break
if t=='3sss' or t=='1s':
print('''a''')
elif t=='4#2 aa#3 aba#5 aabaa#6 bababa#':
print('''4''')
elif t.startswith('6#2 aa#3 aba#3 aaa#6 abaaba#5 aaaaa#4 abba#'):
print('''14''')
elif t.startswith('3... |
2027eca03e0175db0df97a30878d44b54a4a3b12 | lucaspenney/project-euler | /python/5.py | 442 | 3.765625 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def isDivisible(num):
for n in range(1,20):
if num % n != 0:
return False
return num
number = 0
result... |
a9b3198ebca87aea3034468c591ba8baabce4548 | eugene-liyai/Andelabs | /find_max_min.py | 720 | 3.703125 | 4 | def find_min_max(num_list):
# setting varibales
seen = set()
num_list.sort()
sorted_output = []
output = []
#iteration through sorted list
for n in num_list:
if n not in seen:
seen.add(n)
sorted_output.append(n)
else:
pass
... |
21b6e08fcdf02f2d277a063d00d4548d8b6950a6 | skensell/project-euler | /problems/problem-025.py | 932 | 4.0625 | 4 | #25. Find the first term of the Fibonacci sequence to have 1000 digits.
from math import sqrt
from math import floor
from math import log10
fibonacci = {}
def fib(n):
if n in fibonacci:
return fibonacci[n]
elif n ==1 or n==2:
fibonacci[n] = 1
return 1
else:
a = fib(n-1) +... |
84c01bf04a471f1bfef8252a4c22f0f1a4079f7d | dukemiller/download-youtube-videos | /src/tools.py | 276 | 3.703125 | 4 | def format_filename(name: str) -> str:
illegal_characters = ['*', '!', '"', "|", "?", ":", "/", "\\", "<", ">"]
return ''.join(char for char in name if char not in illegal_characters)
def remove_extension(path: str) -> str:
return ".".join(path.split(".")[:-1])
|
221c0deaf2fc2898ade53bbd6be5d3bfbfd881e4 | wan-catherine/Leetcode | /problems/N1089_Duplicate_zeros.py | 958 | 3.671875 | 4 | from collections import deque
class Solution(object):
def duplicateZeros_my_solution(self, arr):
"""
:type arr: List[int]
:rtype: None Do not return anything, modify arr in-place instead.
"""
if not arr:
return arr
i = 0
arr_len = len(arr)
... |
4ba5bfe2d9e24ae8d3f4e7d8b46057f4ef98605b | manasRK/algorithms-practice | /hackerrank/repeated-strings.py | 392 | 3.734375 | 4 | """
https://www.hackerrank.com/challenges/repeated-string
Lilah has a string, "a" , of lowercase English letters that she repeated infinitely many times.
Given an integer, n, find and print the number of letter a's in the first letters of Lilah's infinite string.
"""
s = raw_input().strip()
n = long(raw_input().st... |
f7e774c57b617c52107ed94427982611a9d31604 | Rhange/BOJ_PS | /01.IO/10991.py | 349 | 3.78125 | 4 | def step_by_step_tree(n, init_n):
blank_n = init_n - n
if n == 1:
print(f"{' '*blank_n}*")
return 1
else:
step_by_step_tree(n-1, init_n)
print(f"{' '*blank_n}", end='')
for i in range(n):
if i == n-1:
print('*')
else:
print('* ', end='')
n = int(input())
init_n = n... |
5c05542a6feb9d75d997168e897c12a1877a0029 | stephfz/taller-python-set18 | /vicky_ubaldo/bloq1-volumen.py | 178 | 3.71875 | 4 | ##Calcular el volumen de una esfera.
##4/3*pi*radioelevadoala3
import math
r = 8
r= float(r)
vol= 4/3*math.pi*(8**3)
print("El valor de volumen de una esfera es: " +str(vol)) |
674585a8c5bd8181f7432d7f4d927acf83963f10 | filip-michalsky/Algorithms_and_Data_Structures | /Interview_problems_solutions/Tree_problems (BFS,DFS)/list_of_depths.py | 3,796 | 3.703125 | 4 | from time import time
from utils import BST, LL, Node
import gc
'''
Given a binary tree, design an algorithm which creates a linked list
of all the nodes at each depth (e.g., if you have a tree with depth D, you will have D linked lists)
'''
class BST_value_getter(BST):
def getValues(self,counter=0,depth=0,a... |
5ab2d5d817b79aba24dffd8e6483ad0949b8e425 | sineundong/python_minecraft | /chapter1-setup/test2.py | 428 | 3.546875 | 4 | from turtle import *
import time
for i in range(4):
print(i)
forward(100)
time.sleep(1)
left(90)
#===============================================================================
# time.sleep(1)
# forward(100)
# time.sleep(1)
# left(90)
# time.sleep(1)
# forward(100)
# time.sleep(1)
# left(90)
# t... |
5aa630312f0ac033b2368040a2d87bfd50a62a88 | PythonAlan/my-job | /递归副本.py | 328 | 3.65625 | 4 | #!/usr/bin/env python3
#antuor:Alan
'''斐波那契数列,最后一个数等于前两个数只和'''
def func(arg1,arg2,stop):
if arg1 == 0:
print(arg1,arg2)
arg3 = arg1 + arg2
print(arg3)
if arg3<stop: #必须明确规定结束条件,称为递归出口
func(arg2,arg3,stop)
func(0,1,30) |
8361d410141220e9d9faf9e96fee30de468c1265 | itsrbpandit/fuck-coding-interviews | /problems/fibonacci_number.py | 607 | 3.890625 | 4 | # coding: utf-8
"""
https://leetcode.com/problems/fibonacci-number/
"""
from functools import lru_cache
class Solution:
@lru_cache()
def fib(self, N: int) -> int:
if N <= 1:
return N
return self.fib(N - 1) + self.fib(N - 2)
class Solution2:
caches = {}
def fib(self, N: ... |
78aba5f6f7f5f43d432b14d45fe9154712be17f2 | mjkloeckner/py-repo | /lists.py | 244 | 3.96875 | 4 |
myList = ["Martin", 21, True]
names = ["Veronica" , "Martin", "Malena", "Paula"]
ages = [23, 21, 19, 16]
print(myList[1])
print(names)
print(names[-1])
print(names[2:])
print(names[1:2])
print(ages)
myList [0] = "Javier"
print(myList)
|
c367185ae68ee795badaf97cb8466d2af764a35c | ChenhaoWu18/kataTDD_python | /primes/primes.py | 2,087 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 2 11:28:47 2018
@author: Chen
"""
###############
# Section 3.3 errorful code
#####################
def is_prime(number):
"""Return True if *number* is prime."""
for element in range(number):
if number % element == 0:
return False... |
b08ec68ca4a229fbf57d387ec42b12c607c84bd4 | edu-athensoft/ceit4101python | /stem1400_modules/module_2_basics/c5_datatype/numeric_float/float_accuracy_2.py | 363 | 3.796875 | 4 | # accuracy of float
# method 2: using decimal module
# from decimal import *
from decimal import Decimal
from decimal import getcontext
getcontext().prec = 6
a = Decimal(1) / Decimal(7)
print(a)
getcontext().prec = 28
b = Decimal(1) / Decimal(7)
print(b)
getcontext().prec = 2
print(Decimal('3.00'))
print(Decimal(3... |
6d38729e1f096a250cd6dce54e59fb5927ab8952 | Jadatravu/Tutorials | /pr_euler_sol/problem_38/sol_38.py | 1,163 | 3.6875 | 4 | def check_duplicates(num):
str_num = str(num)
return len(str_num) == len(set(str_num))
def main():
"""
https://projecteuler.net/problem=38
"""
count = 1
while True:
if check_duplicates(count) == False:
count += 1
continue
st_r=''
n_count = 1
fl... |
6f7878a326b1d1b6a2d51ac34319ce58608e8c12 | GGL12/myStudy | /leetcode/leetcode/1095.山脉数组中寻找目标值.py | 1,133 | 3.5 | 4 | class Solution:
def findInMountainArray(self, target, mountain_arr):
left, right = 0, mountain_arr.length() - 1
# 找到山顶的索引
while left < right:
mid = (left + right) // 2
if mountain_arr.get(mid) < mountain_arr.get(mid + 1):
left = mid + 1
els... |
61d3fdaa1cd1f8b9cf359cd09fca65ec14213fc7 | kklook/leetcode | /113PathSumII.py | 857 | 3.703125 | 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 countsum(self,root,t,sum_i,result):
t.append(root.val)
if root.left!=None:
self.countsum(... |
d24c17f6ba05f79ac9b07e7b07347af799bf29f2 | deffener/OHJ1_bits | /Vertical_bar.py | 624 | 3.53125 | 4 | import random
def main():
a = [2, 5, 4, 3, 0 ,2 ,3, 4,7,10]
b =[ random.randint(0,15) for x in range(15)]
a.extend(b)
print(b)
highest = max(a)
base = 0
print()
for x in range(highest, 0, -1):
rivi = str(x).rjust(len(str(highest))+1)+" "
base = len(rivi)
for y in... |
ed7af58cc5d989b11b3c45ea0b6df959cf567d9a | strollinghome/class | /61a/Labs/streams.py | 1,522 | 3.859375 | 4 | class Stream(object):
class empty(object):
def __repr__(self):
return 'Stream.empty'
empty = empty()
def __init__(self, first, compute_rest, empty= False):
self.first = first
self._compute_rest = compute_rest
self.empty = empty
self._rest = None
... |
6b7f2b688b7006c7600e6a0f3d1c3e60d46e3cca | jextrevor/space_server | /module.py | 1,430 | 3.5 | 4 | class Module:
def __init__(self):
#Initialize the 3 dictionaries needed to store data.
self.refs = {}
self.uses = {}
self.rems = {}
def onattach(self,name):
pass
def attach(self,module,name):
#Initialize the module under the given name.
self.refs[name]... |
ec00bf49f17c5c8619e3731497671971346f1d95 | hwet-j/Python | /python_basic/pack2/Question2.py | 616 | 3.53125 | 4 | # 2번문제
# https://cafe.daum.net/flowlife/RUrO/24
# 2. 클래스의 상속관계 연습문제 - 다형성
class ElecProduct:
volume = 0
def volumeControl(self, volume):
pass
class ElecTv(ElecProduct):
def volumeControl(self, volume):
print('ElecTv의 volume :', volume)
class ElecRa... |
2d1addefbfd67bc52cea42c4e5a5e4a6312b9af1 | hakansaglam29/codewars | /032_permutations.py | 302 | 3.875 | 4 | # daily-python-challenge
# Define a “function” to calculate permutation of 2 numbers.
# Reminder: P(n,r) = n!/(n-r)!
# Clue: Defining a function that calculates factorial of given number, may be helpful.
from itertools import permutations
def P(n,r):
return len(list(permutations(range(n),r))) |
a34a5cf032f82720848d4adaef67d135ad941e4c | pradyotpsahoo/P342_A1 | /A1_Q2.py | 500 | 4.46875 | 4 | # find the factorial of a number provided by the user.
# taking the input from the user.
num = int(input("Enter the number : "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Factorial does not exist for negative numbers. Enter the positive number.")
elif num == 0:
... |
48b9f994896045e023827106dd997189bbe2f648 | Lucas-Guimaraes/Reddit-Daily-Programmer | /Easy Problems/301-310/306easy.py | 2,605 | 3.953125 | 4 | #https://www.reddit.com/r/dailyprogrammer/comments/5z4f3z/20170313_challenge_306_easy_pandigital_roman/
#int to roman
def int_to_Roman(num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L... |
6299ae3438ab1ff9c2ca1831ad9aa9d762371c1e | EstherOA/PythonNDataScience | /files/q1.py | 387 | 3.6875 | 4 |
user_in = input('Enter some text and END to quit:')
try:
f = open('userInput.txt', 'a')
while user_in != 'END':
f.write(user_in + '\n')
user_in = input('Enter some text and END to quit:')
finally:
f.close()
try:
fr = open('userInput.txt', 'r')
i = 0
for line in fr:
... |
d669cbe95ee2bc99e73d2f995cf1006079bf3461 | KApilBD/python | /basiccomfundamental/List2.py | 361 | 3.84375 | 4 | aList = [0,1,2,3,4,5]
bList = aList
aList[2] = 'hello'
print(aList == bList)
print(aList is bList)
print(aList)
print(bList)
cList = [6,5,4,3,2]
dList = []
for num in cList:
dList.append(num)
print(cList == dList) #validate the contain only
print(cList is dList) #validate address
cLis... |
a9d38b874c1043dfcfa925ecf548f1e53e071364 | shaikhAbuzar/basicprograms | /fitting.py | 1,954 | 3.796875 | 4 | jobs=[]#Book's Blocks
cand=[]#Book's Jobs
temp=[]
best=[]
first=[]
worst=[]
print(">>>>>>>>>>>>PROGRAM FOR BEST, FIRST, WORST FIT<<<<<<<<<<<<")
#USER INPUT
nj=int(input('Enter the No. of Blocks: '))
nc=int(input('Enter the No. of Jobs: '))
print("\nValue For Jobs")
for i in range(nc):
print("Job No.",... |
2da51f3757a9a776b3ab4289aded923c385e806f | hasantayyar/learn-python | /lesson1/step4_hi2.py | 1,139 | 3.71875 | 4 | #!/usr/bin/python
# look down for %r, %d, %s usage
print "more formatting"
student="cow"
lesson = 1
step = 4
#########
print "Hi %s, this is lesson %d and step%d" %(
student,lesson,step)
print "\nI said\n"
print "Hi {0}, this is lesson {1} and step{2}".format(student,lesson,step)
#########
#########
x="hell this ... |
ccab30f64c7af7613c9ca8919d75b56b37a7e549 | zettaittenani/nlp100_impl | /src/00-09/python/08.py | 629 | 3.90625 | 4 | # 08. 暗号文
# 与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
#
# 英小文字ならば(219 - 文字コード)の文字に置換
# その他の文字はそのまま出力
# この関数を用い,英語のメッセージを暗号化・復号化せよ.
def solve(s):
splitted = s.split()
strs = []
for spl in splitted:
strs.append(
''.join([*map(lambda c:
chr(219 - ord(c)) if c.islowe... |
f87cceaac4fd34ba560ef797bf071386cbecd408 | Vaibhav3007/Python_Mathematical_Codes | /SI.py | 287 | 3.828125 | 4 | p = float(input("Enter principal amount- "))
r = float(input("Enter rate of interest- "))
t = float(input("Enter time period in years- "))
si = (p*r*t)/100
a = p+si
print("Simple Interest for ",p," for ",t," years,calculated @ ",r,"% per annum is ",si,sep="")
print("Total amount-",a)
|
dcc97672181cd0a5795aba4d279012538be01620 | svkrisshna/Python | /redundant.py | 475 | 3.71875 | 4 | def Redundant(string):
lis = []
for i in string:
if i == ')':
dif = lis.pop()
ins = 0
while dif != '(':
ins += 1
dif = lis.pop()
if ins <= 1:
return True
else:
... |
c1d4b5c42fdc79fe41368f41af894b444db319b2 | JKafka97/Projects | /practise/try_while.py | 2,383 | 3.71875 | 4 |
character=input("Write character: ").lower()
list=["Adéla", "Adam", "Adriana", "Adrian", "Agáta", "Albert", "Alena", "Aleš",
"Alexandra", "Alex", "Alice", "Alexander", "Alžběta", "Alexandr", "Amálie",
"Andrej", "Amélie", "Antonín", "Andrea", "Benjamin", "Aneta", "Dalibor",
"Anežka", "Damián", "Anna"... |
77246c792cd7d28c4e802df2670d4f2e825fe70a | almaaskhatri/RatRace3 | /a2.py | 6,498 | 4.0625 | 4 |
# Do not import any modules. If you do, the tester may reject your submission.
# Constants for the contents of the maze.
# The visual representation of a wall.
WALL = '#'
# The visual representation of a hallway.
HALL = '.'
# The visual representation of a brussels sprout.
SPROUT = '@'
# Constants for the direct... |
4485d57818e3b671668b2afae8bea859c72e60d1 | nramdial/securityCamera | /photoresistor.py | 874 | 3.5 | 4 | #!/usr/local/bin/python
import time
import RPi.GPIO as GPIO
def rc_time(input_pin):
count = 0
# Output on the pin for
GPIO.setup(input_pin, GPIO.OUT)
GPIO.output(input_pin, GPIO.LOW)
time.sleep(0.1)
# Change the pin back to input
GPIO.setup(input_pin, GPIO.IN)
# Count until the pin... |
341c47a233d427b6031ea7a00c86eea58eeea3f2 | elenaborisova/Python-Basics | /13. Exam Prep Questions/01. SoftUni Past Exams/05. Movie Ratings.py | 635 | 4.28125 | 4 | import sys
movies = int(input())
highest_rating = -sys.maxsize
lowest_rating = sys.maxsize
total_rating = 0
winner_name = ""
loser_name = ""
for movie in range(movies):
movie_name = input()
rating = float(input())
total_rating += rating
if rating > highest_rating:
highest_rating = rating
... |
b525aa275d2ec4f078329cf1ca805bdcf409cde5 | Nyapal/spd24 | /grid.py | 779 | 3.9375 | 4 | # Given an array of values you need to map the values on to a grid.
# Return an array of objects containing the original value, and a row and col that would represent the position of where the object would map on the grid.
# Assume the length of the original array is always a square e.g. 4, 9, 16 etc. Assume the grid... |
2be7585fc699027cd79c6769d5d2c63b8df70541 | amberhappy/-offer | /43-左旋转字符串.py | 277 | 3.75 | 4 | #对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。
# 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”
class Solution:
def LeftRotateString(self, s, n):
return s[n:]+s[:n] |
08c6e80d9609e188e4e2fd35c564ce7009b25c7b | zeqiguo/ds | /recursion/move_tower.py | 223 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def move_t(n, a, b, c):
if n == 1:
print(a, " -----> ", c)
else:
move_t(n-1, a, c, b)
print(a, " -----> ", c)
move_t(n-1, b, a, c)
move_t(10, "a", "b", "c") |
cc11dad3e21ef149f6a3506d34d03eeb7ade09e2 | gh-develop/coding-test-kw | /gyuhyeon/프로그래머스/stack,queue/괄호검사.py | 1,865 | 4 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
new_node = Node(data)
new_node.next = self.top
self.top = new_node
def pop(self):
pop_object = N... |
b49547f8f58a5e88356096639c47f1ec8e8298e7 | saenuruki/Codility | /TimeComplexity/frogJmp.py | 1,512 | 4.28125 | 4 | #A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
#
#Count the minimal number of jumps that the small frog must perform to reach its target.
#
#Write a function... |
dc96eea52bfb81950004392b4d313c0a8619d30a | AhmetHamzaEmra/Project-Euler | /10001st_prime.py | 499 | 3.765625 | 4 | #!/bin/python3
import sys
def IsPrime(n):
if n==1 or n%2==0:
return False
else:
i=3
while i*i<=n:
if n%i==0:
return False
break
i+=2
return True
t = int(input().strip())
ar=[]
primes=[2]
for a0 in range(t):
n = i... |
1a4cd139890ee602a67f99103cda0a54ef21b903 | RhuanAlndr/CursoemVideo_Python | /ex091 - Aula 19.py | 1,249 | 3.515625 | 4 | from random import randint
from time import sleep
from operator import itemgetter
'''p = dict()
l = list()
ls = list()
print('Valores sorteados:')
for j in range(0, 4):
p['Jogador'] = j + 1
p['Jogada'] = randint(1, 6)
l.append(p.copy())
print(f' O jogador {l[j]["Jogador"]} tirou {l[j]["Jogada"]}')
... |
f371e820544c45ba446f4ef6ed6e917d64289604 | mavega998/python-mintic-2022 | /TALLER2/utilidad.py | 282 | 3.984375 | 4 | meses = int(input("Ingrese tiempo (meses): "))
anios = meses / 12
print("Utilidad")
if anios < 1:
print("5%")
elif anios >= 1 and anios < 2:
print("7%")
elif anios >= 2 and anios < 5:
print("10%")
elif anios >= 5 and anios < 10:
print("15%")
else:
print("20%")
|
aab674eacfafebcfccf899c384235df6823df0d8 | ren-curry/u3s1_sprint_challenge | /modules/acme_report.py | 1,918 | 3.59375 | 4 | """
Part 4 - Class Report: Generate Products and report on them
"""
import random
from acme import Product
# Variable Definitions for use throughout code
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(number... |
fa2624f565e1e69b918439c8d14c53ff494a90d0 | cemalsenel/pythonQuestions | /day07.py | 498 | 3.984375 | 4 | text = "Merhaba yeni dunya sana da"
print(text.replace("e", "eee").upper())
print(text.swapcase())
print(text.capitalize())
print(text.upper())
print(text.lower())
print(text.title())
print(text.replace("a","bbbbbb",1))
print(text.replace("a","bbbbbb",-1))
text1 = "Ali ata bak"
print(text1.strip("Ak"))
text2=" Ali "... |
992028db02820162c8e5a9b04a2f5b0db704e321 | Parsnipss/Ceballos_Story | /popQuiz.py | 1,210 | 4.15625 | 4 | # 1. Print out a random number bewteen -5 and 5
import random
print ("A random number bewteen -5 and 5 would be: " + str(random.randint(-5, 5)))
# 2. Print out a random integer between 0 and 100, 50 times
for i in range(500):
print (random.randint(0, 100))
# 3. Print a random number and determin if it is even... |
5eaf6884a83264d11ebf70d85ef856e60bfac4e1 | CannonStealth/Notes | /Python/dictionaries/usage/except.py | 107 | 3.5 | 4 | map = {
"Spain": "Without the S"
}
try:
print(map["USA"])
except KeyError:
print("NO USA") |
95becd3ec3944461a553b341867a6f4eb65547a1 | MarkMoretto/project-euler | /incomplete/problem_358.py | 4,200 | 3.671875 | 4 |
"""
Purpose: Project Euler exercises
Date created: 2020-06-25
Problen Number: 358
Name: Cyclic numbers
URL: https://projecteuler.net/problem=358
Contributor(s):
Mark M.
Description:
A cyclic number with n digits has a very interesting property:
When it is mmultiplied by 1, 2, 3, 4, ... n, all the produc... |
8b6afe6f6304f11695f756cec3c63a6650bdf991 | GilzinBR/random_team | /random_list_generator.py | 939 | 4.25 | 4 | # The plan is:
# 1- I have a list of teams and a empty list
# 2- I will pick one random position of the team list
# 3- The team that is in this position I will add on the empty list
# 4- The team that was in this position now will change to 'Check'. This way I dont pick this position again
# 5- Now the empty list is a ... |
352d1ce732914580ec876c6cdcbaa64ccceef126 | sripathyfication/bugfree-octo-dangerzone | /python/leetcode/guess.py | 681 | 3.9375 | 4 | #!/usr/bin/env python
import random
import math
user_input = 0
def guess(g):
if g is user_input:
return 0
elif g < user_input:
return -1
elif g > user_input:
return 1
def guessNum(n):
my_g = random.random(1,n)
while r is not 0:
r = guess(my_g)
if r > 0:
... |
851d1688016ebbded700ba59e731e524cb0a8901 | ioanzicu/python_for_informatics | /ch_15_sqlite/ch_15_sqlite.py | 747 | 3.734375 | 4 | import sqlite3
# connect
conn = sqlite3.connect('ch_14_sqlite/music.sqlite3')
# obtain cursor
cursor = conn.cursor()
# run commands
cursor.execute('DROP TABLE IF EXISTS Tracks')
cursor.execute('CREATE TABLE Tracks (title TEXT, plays INTEGER)')
cursor.execute('INSERT INTO Tracks (title, plays) VALUES ( ?, ? )',
... |
4c98de9380eba70b40f0f14ad1a12e57c784aa30 | yunlum/Directions-Application-with-MapQuest-API | /P3_class.py | 7,757 | 3.53125 | 4 | # YUNLU MA ID: 28072206
class LATLONG:
'''
This class is used to get the useful data of LATLONG from the dictionary named "data_base"
and make some adjustments to let the data match the format of output requirements.
Finally, return a list of required data
'''
def __init__(self):
... |
72e83afbbdce12b1426ca6c9d840f9270cc851a2 | Wheeler1711/misc | /card_shuffle/card_shuffle.py | 4,266 | 3.828125 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Program to shuffle cards as a human might
# Acient proverb if you shuffle 7 times the cards are completely randomized
# Here we think of how a human shuffles cards.
# Step 1 split the deck in two not always perfect decks
# they miss getting split halveway in two ... |
11a9617ebb3a2d4adc66cff8198f5cbf9b661704 | neldis93/Validate-Login | /validate-login/user.py | 755 | 3.640625 | 4 | class UserValid:
errors=[]
def length(self,username):
if len(username) < 6:
self.errors.append('Username must contain at least 6 characters')
return False
elif len(username) > 12:
self.errors.append('Username must contain max 12 charactere... |
eeb56e2c52376f681096bffb0943b880b93116ef | Justinnn07/python-basics | /main.py | 285 | 3.53125 | 4 | import calendar
print(calendar.weekheader(3))
print(calendar.firstweekday())
print(calendar.month(2020, 11, w=3))
print(calendar.monthcalendar(2020, 11))
a = calendar.weekday(2020, 11, 2)
print(a)
b = calendar.isleap(2020)
print(b)
k = calendar.leapdays(2000, 2020)
print(k) |
dbf2424ff914e6bea66bc39907614e2ed3050d66 | Neryfms/Tarea2-Semana2 | /Tarea2-Semana2.py | 169 | 4.03125 | 4 | from math import isfinite
print ("Area Circulo")
pi = 3.14
radio = int(input("Ingresa el valor del radio: "))
area = (radio ** 2) * pi
print ("El area es ", area,)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.