blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ecd0bdf41d7f5b405836b5ce0ab72aaeabae620e | iYashodhan/Sudoku-Solver | /sudokuSolver.py | 2,296 | 3.9375 | 4 | import running
import random
def printBoard(board):
for i in range(len(board)):
if i % 3 == 0:
print('- - - - - - - - - - - - -')
for j in range(len(board[i])):
if j % 3 == 0:
print('| ' + str(board[i][j]) + ' ', end='')
elif j =... |
330ae8063a8c0ae3ac09b6760883dfaa30c4a281 | MikeyBeez/deme-app | /tests/hexadecimal_test.py | 739 | 3.5625 | 4 | def hexadecimal(number: int):
"""
"""
print("Converting integer...")
pocus = hex(number)
print(str(pocus))
def test_hexadecimal():
"""
"""
number = 9
assert hex(number) == "0x9", "Should be 0x9"
print("Initializing test! (1/1)")
try:
print("")
print(hexadecimal(9))
... |
512743a1367c1d88b07839e1d39e556e5da3a4ce | ptrebert/creepiest | /crplib/numalg/iterators.py | 719 | 3.515625 | 4 | # coding=utf-8
"""
Convenience module holding "custom" iterators for generic data structures
like masked arrays
"""
def iter_consecutive_blocks(positions):
""" Find consecutive blocks in a series of positions,
i.e. array indices, and return start:end tuples s.t.
access to the array returns all values in ... |
51cc1a269a7e84e8a946d4fea06693c9f5d99a0f | kaikim98/Computing-for-data-science | /HW3/P8.py | 774 | 4.0625 | 4 | """
Practical programming Chapter 9 Exercise 8
**Instruction**
You are given two lists, rat_1 and rat_2, that contain the daily weights of
two rats over a period of ten days. Assume the rats never have exactly
the same weight.
Complete P8 function to return True if the weight of rat 1 is greater than rat2 on d... |
791329e2a41f23a02ab894ca79b5cc363cbbb469 | zhosoft/python_learn | /lesson001/sort.py | 418 | 3.5625 | 4 | list = [1, 5, 3, 6, 10, 24, 99, 54]
def sortport(list):
for i in range(len(list) - 1):
for j in range(len(list) - 1 - i):
if list[j] > list[j + 1]:
temp = list[j]
list[j]=list[j+1]
list[j+1] = temp
# [1, 3, 5, 6, 10, 24, 54, 99]
... |
9640b0828450f2c15138db6931f88b833f7b331f | Aasthaengg/IBMdataset | /Python_codes/p02713/s321590132.py | 184 | 3.578125 | 4 | from math import gcd
k=int(input())
ans = 0
for a in range(1,k+1):
for b in range(1,k+1):
gab=gcd(a,b)
for c in range(1,k+1):
ans+=gcd(gab,c)
print(ans) |
6221db89efa5fe44948eb1dc8dd123fa4a5d8df1 | chrisglencross/advent-of-code | /aoc2015/day25/day25_unoptimized.py | 942 | 3.53125 | 4 | #!/usr/bin/python3
# Advent of code 2015 day 25
# See https://adventofcode.com/2015/day/25
from itertools import count
def get_cell_number(row, col):
# Almost certainly a better way to calculate this with some arithmetic and properties of triangular numbers
# ...but this only takes a couple of seconds.
x ... |
3c27b4d17fd98fc51ec456a765a4c1dcd531ce5a | kilala-mega/coding-pattern | /palindrome-linked-list.py | 993 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
1 2 3
"""
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head:
return True
walker, runner = head, head.next
... |
98a304f30646bc3f19aad4e2523282caae464a0a | gistable/gistable | /all-gists/3979518/snippet.py | 4,091 | 3.609375 | 4 | import random
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
... |
7e8061cfa721d3ea1625afaa95e8489714776d85 | outboxltd/python4thepeople | /09072019/star/ex01/ex01.py | 411 | 4.03125 | 4 | # Write a method that gets a list and returns the sum of it. Validate you’re only summing the numeric elements (not
# strings, dictionaries etc.)
demo_list = [1,2,3,8,"gilad"]
for x in demo_list:
if type(x) != int:
demo_list.remove(x)
print(demo_list)
list_in_int = [int(i) for i in demo_list]
print(list... |
59f0571312dda08882174cc296560115d585b4a7 | wangzhifengemc/Pied | /switch.py | 1,086 | 3.765625 | 4 | #!/usr/bin/env python
import RPi.GPIO as GPIO
import time
LedPin = 26 # pin26
def Switch_setup():
# GPIO.setmode(GPIO.BCM) # Numbers pins by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set pin mode as output
GPIO.output(LedPin, GPIO.HIGH) # Set pin to high(+3.3V) to off the led
def Swi... |
ba287a7cfa6c6844216a2c1dd50315127b68f421 | SafiBelim/TestPrj | /ArrInput.py | 347 | 3.96875 | 4 | # Program for insert and search array
from array import *
arr=array('i',[])
n=int(input("Enter length of the array"))
for i in range(n):
x=int(input("Enter the next value"))
arr.append(x)
print(arr)
val=int(input("Enter the value for search"))
k=0
for e in arr:
if e==val:
print(k)
break
... |
bb6c30f4a60d1b8c499c3159c647dff615fb6284 | soorya1991/Academics | /Interview_Prep/questions/find_min_max.py | 2,023 | 3.578125 | 4 | #!/usr/bin/python
"""
Implementation of find min and max using less number of comparisons
find_min_max --> compare in pairs
find_min_max_tournament --> divide and conquer approach(tournament method)
"""
import sys
def find_min_max(a):
if not len(a) > 1:
return "Invalid input",None
if len(a) == 2:
... |
e1b8ef065fa77967a1434c26a4c58b03a54608fe | hj424/bril | /tasks/t2/lvn/util.py | 757 | 4.0625 | 4 | # Helper functions
import itertools
def form_instr_dict(file_name):
# open the file
f_ptr = open(file_name, "r")
if (not f_ptr):
print("! Can't open file: "+file_name)
instr_list = {}
line = f_ptr.readline()
while line:
instr_list.append(line)
# read new line
line = f_ptr.readline()
# ... |
0fb77a1587924ed21f9e2704a4c38eacf477267a | Dripstylish/p1-projekt | /calculate_price.py | 5,342 | 3.5625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import math_methods as mm
csv_file_path = "home/HOME.csv"
def import_csv_file(csv = csv_file_path):
csv_file = pd.read_csv(csv, delimiter=';')
return csv_file
def create_test_train(dataframe):
amount = int(len(dataframe)/6)
subset_train = dataframe... |
855b3ac7b3cca4c5ab52121cbb0ac647ddcba1bf | geeveekee/100_days_of_Code | /d29/d29.py | 769 | 3.859375 | 4 | from tkinter import *
window = Tk()
window.title("Miles to Km Converter")
window.geometry('300x150')
window.configure(bg='#FB7AFC', padx=30, pady=20)
def convert():
mile = my_input.get()
mile = float(mile)
km = mile * 1.6093
print(km)
answer.configure(text=km)
my_input = Entry()
miles = Label(... |
e2021811a0c8f67d9f25a434d3771aa1ff4e96e4 | DimaSamoz/blackjack-python | /Hand.py | 851 | 3.78125 | 4 | class Hand(object):
def __init__(self, cards):
self.cards = cards
self.value = 0 # If multiple values are possible (i.e. hand contains an ace), value is the lower of the two
def add(self, card):
self.cards.append(card)
def eval_hand(self):
aces_count = 0
self.valu... |
e2b433c74472ff0bda908cca0ba566a0baaf2b51 | khannasangya1/programpractise | /searchinsert/solution.py | 757 | 3.90625 | 4 | class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for x in range(len(nums)-1,-1,-1):
if nums[x] == target:
element_removed = nums.pop(x)
return x
... |
b6f6f643ea7cfe2940ff23dac1505322f7526a4b | liuqing121/git_remote | /merge.py | 756 | 3.5 | 4 | class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
#先排序,遍历list,判断重合,若重合则更新区间,不重合则直接算入结果
res=[]
if len(intervals) < 2:
return intervals
intervals.sort()
left ... |
7c9e9c827302f541f45f67ab8271ab838e365894 | SubhamPanigrahi/Python_Programming | /student_data.py | 519 | 3.796875 | 4 | # student data and exception handling
class Student:
def __init__(self, name, roll_number):
self._name = name
self._roll_number = roll_number
def display(self):
print("The name of the student is: ", self._name)
print("The roll number of the student is: ", self._roll_number)
tr... |
372ebd449317a08b78fbc64087ddcf6da3efeb10 | MartinMwiti/Python-Data-Structure-and-Algorithms | /Algorithm/3. Calculate String Length.py | 354 | 3.65625 | 4 | input_str = 'LucidProgramming'
print(len(input_str))
def iterative_str_len(input_str):
count = 0
for i in range (len(input_str)):
count +=1
return count
iterative_str_len(input_str)
def recursive_str_len(input_str):
if input_str=='':
return 0
return 1+recursive_str_len(input_str[... |
5d3ad8c879da527e6c4cee33cf582f9379f9808b | BensonMuriithi/python | /practicepython/strbase.py | 378 | 3.640625 | 4 | from string import uppercase
dig_to_chr = lambda num: str(num) if num < 10 else uppercase[num - 10]
def strbase(number, base):
if not 2 <= base <= 36:
raise ValueError("Base to convert to must be >= 2 and <= 36")
if number < 0:
return "-" + strbase(-number, base)
d, m = divmod(number, base)
if d:
return... |
56a3475cfa349ca30b5b089309312b931991b196 | woonglae/udemy_Django | /exercise/11_Python_1/simpleGame.py | 1,543 | 4.21875 | 4 | ###########################
## PART 10: Simple Game ###
### --- CODEBREAKER --- ###
## --Nope--Close--Match-- ##
###########################
# It's time to actually make a simple command line game so put together everything
# you've learned so far about Python. The game goes like this:
# 1. The computer will think o... |
15e395c7125d0c7a33db712e969b3becd2a444cd | IlyasAzeem/PRs_project | /Models/MultiClass_Examples/dt.py | 780 | 3.515625 | 4 | # importing necessary libraries
from sklearn import datasets
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
# loading the iris dataset
iris = datasets.load_iris()
# X -> features, y -> label
X = iris.data
y = iris.target
# dividing X, y into train and test data
X_tr... |
af2c48643041917b25ca6e55e4e42194bc0210c9 | MHenderson1988/simplepass | /main/password_generator.py | 2,797 | 4.09375 | 4 | import random
import secrets
import string
list_of_ascii_chars = ''.join(string.ascii_letters + string.punctuation + string.digits)
"""
This function generates a random combination of ascii characters to the length specified by user input. The input
must be an integer between 4 and 20. The output is a string of asc... |
8b8e5bbd0baa78497e6e5129c6c9b519ed06c997 | TalgatAitpayev/pythonProject | /задача4.py | 154 | 3.734375 | 4 | numbers=[1,5,3,7,4]#как сделать input массива?
a=[]
for x in range(1,len(numbers)+1):
if [x-1]<[x]:
a.append(x)
print(len(a)) |
6dcb901c0864b6dcfdcb12f9096e988e9da46867 | dreamsmasher/L2CE1 | /conversions/__init__.py | 2,178 | 4.28125 | 4 | """Creates a Conversions object. The convert method takes a value, \
an optional SI prefix string to convert from, and an \
SI suffix string to convert to."""
class Conversions:
def __init__(self):
prefixes = [
"y",
"z",
"a",
"... |
aa89fda5f4683126b9d2b53dce05d50e095c00a3 | KayleighPerera/COM411 | /main.py | 641 | 3.875 | 4 | # create list
def fruits():
fruits = ["orange", "pear", "banana"]
# add fruits to list
fruits.append("grapes")
fruits[1] = "grapefruit"
fruits[2] = "kiwi"
# return function
return fruits
# run the list
def run():
print(fruits())
# access a text file
# import the file type
import csv
#open the f... |
1d2b0d179bf3a212d005ca18cc13045e5e2922d9 | Gabrielcarvfer/Introducao-a-Ciencia-da-Computacao-UnB | /aulas/aula3/4.py | 179 | 4.03125 | 4 | n = int(input("Digite numero"))
x = 1
fat = 1
while x <= n:
fat = fat*x
x = x + 1
print("fat=",fat)
print("x=",x)
print("O fatorial de ",n," é ", fat)
|
7d005f960f548847749f1898d6874faf0163af98 | Allyn69/python4kids | /ifstatement.py | 234 | 4.09375 | 4 | name = input("Enter your name: ")
print("Hello {}. Nice to meet you".format(name))
age = int(input("How old are you?: "))
if age > 11:
print("You are old!")
else:
print("I guess you are a pupil in the school!")
|
337c9a0ddf2ce0b8aad827dfa98cefbbc0939d06 | AndrewB4y/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/rectangle.py | 3,131 | 3.515625 | 4 | #!/usr/bin/python3
""" rectangle module """
from models.base import Base
class Rectangle(Base):
""" Rectangle class """
def __init__(self, width, height, x=0, y=0, id=None):
""" __init__ function for class Rectangle """
self.width = width
self.height = height
self.x = x
... |
7c9bf7aaa919ff4c790e076a1d3b8ecdfbd7dc0e | zb14755456464/pandas_note | /快速入门/pandas_类别型.py | 327 | 3.75 | 4 | import pandas as pd
df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "raw_grade": ['a', 'b', 'b', 'a', 'a', 'e']})
# 将 grade 的原生数据转换为类别型数据:
df["grade"] = df["raw_grade"].astype("category")
print(df["grade"])
df["grade"].cat.categories = ["very good", "good", "very bad"]
print(df["grade"])
|
d92d9504d6a63a2b0664767e40cf0253050f4672 | shivanikatiyar/The_joy_of_computing_using_Python_NPTEL | /swapString.py | 268 | 4.0625 | 4 | def swap_case(s):
t="" # empty string taken
for l in s:
if(l.isupper()):
t+=l.lower()
else :
t+=l.upper()
return t;
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result) |
da1e429f34cb3c7ad801b7b5c59423d76f6e1a24 | abloskas/Flask_projects | /python_class/hello.py | 1,108 | 4.15625 | 4 | # # define a function that says hello to the name provided
# # this starts a new block
# def say_hello(name):
# #these lines are indented therefore part of the function
# name = "ash"
# if name:
# print 'Hello, ' + name + 'from inside the function'
# else:
# print 'No name'
# # now we're unindented and ha... |
60e475c388e27b6f914baf149b58870dae4bfed6 | leandro-matos/python-scripts | /aula05/ex32.py | 177 | 4.125 | 4 | numero = int(input('Digite um número: '))
if (numero <0):
print('Número negativo')
elif ((numero %2) == 0 ):
print('Número Par')
else:
print('Número Impar') |
bed5fa8cf0c9b5a24a36b798851e9068c05780b5 | 8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions | /Chapter03/0017_itertools_chain_from_iterable.py | 447 | 4.0625 | 4 | """
Listing 3.17
If the iterables to be combined are not all know in advance, or if they
need to be evaluated lazily, chain.from_iterable() can be used to
construct the chain instead
"""
import itertools
def make_iterables_to_chain():
yield [1, 2, 3]
yield ["a", "b", "c"]
def main():
for i in itertools... |
9e5b499d99f49afb53251f9d77d15ea1e4077ec4 | etshiwot/Algorithms-in-Python | /BinarySearch.py | 471 | 4.0625 | 4 | '''
@author : utkarsh
'''
def binary_search_function(item_list, item):
first = 0
last = len(item_list) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
if item_list[mid] == item:
found = True
else:
if item < item_list[mid]... |
2375343964902a8b87d9678e87fc76760d5af2b4 | Andreusd/coursera-iccpp1 | /l2ex4.py | 120 | 4.15625 | 4 | numero = int(input("Insira um numero:"))
if(numero%3==0 and numero%5==0):
print("FizzBuzz")
else:
print(numero)
|
6f1bbad2c2c3392f0940899e227e17407f2cb999 | gabriellaec/desoft-analise-exercicios | /backup/user_160/ch72_2019_06_07_03_20_35_448457.py | 136 | 3.625 | 4 | def lista_caracteres (n):
lista = []
for i in n:
if i is not in n:
lista.append (i)
return lista |
14a3d85fcd349f923d0a7ff01ab5fdc8f1f763a6 | ehedaoo/Practice-Python | /Basic2.py | 207 | 3.5 | 4 | # Write a Python program to get the Python version you are using.
# Write a Python program to display the current date and time.
import datetime
import sys
print(sys.version)
print(datetime.datetime.now()) |
8fcd71d4c1cea1bbc3bd052c300d399dead0c93d | alex329657/PythonCore | /lesson03/hw03-task3.py | 779 | 4.09375 | 4 | """
Task 3: Shortest Word
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
Examples
"bitcoin take over the world maybe who knows perhaps" --> 3)
"turns out random test cases are easier than writing out basic ... |
910adf0950939dd211abdd704cffedaf2f9243bf | MarKus-del/entendendo-algoritmos-em-python | /cap-04/exercicio.py | 424 | 3.53125 | 4 | # pag 77
# 4.2
# def lentgh(lista):
# if len(lista) == 1:
# return 1
# lista.pop()
# return 1 + lentgh(lista)
# print(lentgh(['', '', '', 5, 78, 6.5]))
# 4.3
def maxValueInList(lista, maxValue = 0):
if len(lista) == 1:
return lista[0] if lista[0] >= maxValue else maxValue
item = lista.pop()
sub_max = max... |
919b938fc384b85580b56eceb6b27c39cbff24a8 | sebaek42/baekjoon | /programmers/dartgame.py | 955 | 3.5625 | 4 | def solution(dartResult):
answer = 0
cnt = 0
CHANCE = 3
score = []
dartResult = list(dartResult)
while cnt < CHANCE:
token = dartResult.pop(0)
if token == '1' and dartResult[0] == '0':
token = token + dartResult.pop(0)
score.append(int(token))
token = ... |
91c29ccdf4449e62e124b725e9fca4a23fc3b55d | ibirdman/TensorflowExercise | /interview/test11.py | 133 | 3.796875 | 4 | """
a = list([1,2,3]);
print(a);"""
b = tuple([1,2,3]);
print(b);
c = list("abc");
print(c);
s2 = """hello,
world""";
print(s2); |
720551d6f4d71ec1a831e4eeb1e6034ba228cac4 | Praveenstein/numpy_pandasProject | /solutions/vector_product_q2.py | 2,720 | 4.59375 | 5 | # -*- coding: utf-8 -*-
"""
Dot Product Of All Given Vectors
====================================
Module to Find the Dot Product Of all Given Vectors
This script requires the following modules be installed in the python environment
* logging - to perform logging operations
This script contains the following func... |
bcceff6848368b121c1b4fcdd599d35794028cb0 | stenioaraujo/cracking-interview | /chapter1/007/main.py | 1,170 | 4.125 | 4 | def main():
matrix = [
[1,1,1,1],
[2,2,2,2],
[3,3,3,3],
[4,4,4,4]
]
print_matrix(matrix)
matrix = [
[1,1,1],
[2,2,2],
[3,3,3]
]
print_matrix(matrix)
matrix = [
[1,1],
[2,2]
]
print_matrix(matrix)
matrix = ... |
c19945b4603076e94402dbf0aa4d96b2a9ca53f5 | myhappyporcupine/pyjects | /list.py | 364 | 3.984375 | 4 | the_list = ['first thing']
def print_list():
print('The list now contains:')
for thing in the_list:
print(thing)
print()
print_list()
while True:
try:
new_thing = input('Append to the list (or press Ctrl-C to exit): ')
the_list.append(new_thing)
print_list(... |
2b0b102b2add45af162ddb38835bdcc9b3fedfd9 | psiionik/CodingProblems | /LeetCode/DailyPractice/repeatedstringmatch.py | 364 | 3.75 | 4 | import math
def repeatedStringMatch(A, B):
if(len(A) == 0 or len(B) == 0):
return -1
maxratio = math.ceil(len(B)/len(A)) + 1
if(B in A*maxratio):
return maxratio
if(B in A*(maxratio + 1)):
return maxratio + 1
return -1
def main():
A = "abcd"
B = "cdabcdab"
x = r... |
7146a77b3df6dcad47002cf0701bf8f121b99f21 | chandhukogila/Pattern-Package | /Numbers/zero.py | 738 | 4.1875 | 4 | def for_zero():
"""We are creating user defined function for numerical pattern of zero with "*" symbol"""
row=7
col=5
for i in range(row):
for j in range(col):
if ((i==0 or i==6)and j%4!=0) or ((i==1 or i==2 or i==4 or i==5 or i==3)and j%4==0) or i+j==5:
print("*",en... |
bc5c1b5739c55b9a6ef41f379f01603cf2275acd | oliveiralecca/cursoemvideo-python3 | /arquivos-py/CursoEmVideo_Python3_DESAFIOS/desafio71.py | 773 | 3.65625 | 4 | print('-=-=-=-= DESAFIO 71 -=-=-=-=')
print()
print('='*40)
print('{:^40}'.format('BANCO CEV'))
print('='*40)
valor = int(input('Que valor você quer sacar? R$'))
total = valor
cedula = 100
totcedula = 0
while True:
if total >= cedula:
total -= cedula
totcedula += 1
else:
if totcedula >... |
796a4c8c4ee318c868003a1620b1d94c22af9be5 | charanreddy0/While-Loop | /6.py | 274 | 3.796875 | 4 | #star pattern
i=0
num=int(input("Enter the number of rows to print:"))
while i<=num:
print(" "*(i),end='')
if num%2!=0:
print("1"*(((num*2)-(i*2)-1)%2!=0),end='')
else:
print("0"*(((num*2)-(i*2)-1)%2==0),end='')
print('')
i+=1
|
fb121fad1485389c27cbf9e64ad958116637da51 | wnwoghd22/NTHU_HW_All | /Python/SC14_2.py | 2,176 | 3.625 | 4 | import tkinter
import random
ROCK,SCISSORS,PAPER = (chr(0x270a),chr(0x270c),chr(0x270b))
D = {0:ROCK,1:SCISSORS,2:PAPER}
computers_hand = ' '
players_hand = ' '
_status = ' '
_flag = True
root = tkinter.Tk()
f = tkinter.Frame(root, borderwidth = 7)
l0_str = tkinter.StringVar()
l1_str = tkinter.StringVar()
l2_str = ... |
af7b44227aa09ec046a0084f9618bbf661892d9d | dachen123/algorithm_training_homework | /week1/verifyPostorder.py | 2,000 | 3.5 | 4 | #训练场题目8,二叉搜索树的后序遍历序列
#思路 :1.将后序遍历序列进行排序得到中序序列
# 2.利用中序和后序可得到二叉树的思想,检查这两个序列是否可以顺利构建二叉树,从而得出结论
class Solution:
def checkTree(self,inorder,inorder_begin,inorder_end,postorder,postorder_begin,postorder_end,result):
if postorder_begin > postorder_end:
return
node_val = postorder[postord... |
0c1c67736399dde4548591fe2a4eb998efb8d797 | soumasish/leetcodely | /python/outliers/longest_subsequence_less_than_target.py | 620 | 3.90625 | 4 | """Find the length of longest contiguous subsequence in an array which has a sum less than or equal to a given target
Ex- 1:
arr = [8, 3, 7, 4, 1, 6, 5], target = 16
In this case the answer is 4
3, 7, 4, 1 and 4, 1, 6, 5 both satisfy the condition and both are 4 elements long.
"""
def longest_subsequence(arr, targ... |
1f8ab7bc04f955ddd627274ee78ee461675f0ad2 | sanchezolivos-unprg/t06_sanchez | /sanchez/multiple06.py | 590 | 3.796875 | 4 | import os
# AREA DEL RECTANGULO
# MOSTRAR VALORES
largo=0.0
ancho=0.0
# INPUT
largo=float(os.sys.argv[1])
ancho=float(os.sys.argv[2])
# PRECESSING
area=(largo*ancho)
# OUTPUT
print(largo)
print(ancho)
print("el area es", area)
# CONDICION SIMPLE
# si el area del rectangulo son menores o mayores que los argumentos d... |
3659930c88448b3087dd89b59f49aebbec84f70d | aguinaldolorandi/Python_exercicios_oficial | /Lista de Exercícios nº 08 Python Oficial/Lista_08_Exercicio10.py | 1,458 | 4.03125 | 4 | # EXERCÍCIO 10 - LISTA 08 - CLASSES
print('Classe Bomba de Combustível')
print('###########################')
print()
class Bomba_Combustivel():
def __init__(self,tipo,valor_litro,qtde):
self.tipo = tipo
self.valor_litro = valor_litro
self.qtde = round(float(qtde),3)
def abastecer_valor... |
e98a33166b1518b0e428f300fa5eb1ba1a9096c3 | amymhaddad/cs_and_programming_using_python | /week_2_study_problems/enumeration.py | 1,708 | 4.25 | 4 | # x = int(input("Enter an integer: "))
# ans = 0
# #setup comparison and test statement in while loop
# #the while loop is generating guesses
# while ans**3 < x:
# #increment by 1
# ans = ans + 1
# #The while loop keeps generating guesses until it gets to the right thing OR it's gone too far
# #Then, I check ... |
c88b3269108be691ae26376a7495d726b6ae96d8 | wdwoodee/LearningPython | /Exception/exception.py | 934 | 4.1875 | 4 | while 1:
try:
x = int(input("Input a number:"))
y = int(input("Input a number:"))
z = x/y
except ValueError as ev:
'''第一个参数是异常的类型,第二
个参数用于接收异常发生时生成的值,异常是否有这个参数及参数的类型
如何,由异常的类型决定。'''
print("That is a invalid number", ev)
except ZeroDivisionError as ez:
print("... |
fb6e30edfb1c07222bac3ab64b0e01ff92ada19c | kdvuong/291Project1 | /Db.py | 12,401 | 3.734375 | 4 | import sqlite3
import datetime
from User import User
import array
# Class to represent database
class Db:
def __init__(self):
self.conn = None
# Function to setup the connection with the database
def setup(self):
dbName = input("Enter db name: ")
self.conn = sqlite3.connect(dbNam... |
c0a162dc718ce848f65e16ec7784e8d3fa5e6c2b | lusmoura/CompetitiveProgramming | /Solutions/Codeforces/102/B - Sum of Digits.py | 186 | 3.8125 | 4 | def digitSum(x):
string_x = str(x)
total = 0
for char in string_x:
total += int(char)
return total
a = input()
ans = 0
while(int(a) > 9):
a = digitSum(a)
ans += 1
print(ans)
|
98b1c15086a1b9052c730d0b951c27ba864d52e4 | nanochess/basic-computer-games | /13 Bounce/python/bounce.py | 2,641 | 3.5 | 4 | """
BOUNCE
A physics simulation
Ported by Dave LeCompte
"""
PAGE_WIDTH = 64
def print_centered(msg):
spaces = " " * ((PAGE_WIDTH - len(msg)) // 2)
print(spaces + msg)
def print_header(title):
print_centered(title)
print_centered("CREATIVE COMPUTING MORRISTOWN, NEW JERSEY")
print()
print... |
c46d256c4aeb7a98a57e5eef41c94d6c3fb07255 | AtinAvi/Python | /binary_search.py | 436 | 3.875 | 4 | import math
def binary_search(list,item):
high = len(list)
low = 0
while low <= high:
mid = math.floor((high+low)/2)
guess = list[mid]
if guess==item:
print(mid)
return mid
if guess > item:
high = mid-1
else:
low = mi... |
9f66fa9acf793372d8fd8e343b575bc1d8fd7509 | YuanXianguo/Python-Interview-Master | /LeetCode/242有效的字母异位词.py | 405 | 3.65625 | 4 | """
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
"""
def isAnagram(s, t):
def get_u(u):
return u.encode()
return sorted(s, key=get_u) == sorted(t, key=get_u)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
if __name__ == '__main__':
print(isAn... |
7bcdca48a67a171cfd66ff0d83d4283eeb552f48 | maranemil/howto | /datamining/machine_learning_py_scripts/classifiers_ipynb2py/CNN-transfer-learning.ipynb.py | 14,372 | 3.796875 | 4 |
# coding: utf-8
# # Transfer Learning for Image Classification Using CNN
# - [Introduction](#intro)
# - [Part 1: Feature Extraction Using VGGNet](#part1)
# - [Part 2: Neural Net Building and Training](#part2)
# - [Part 3: Neural Net Testing](#part3)
# <a id='intro'></a>
# ## Introduction
#
# In this project, I'll s... |
bf9bad40f2eee0f5505b2cbeb8de0c82d9ca70b4 | gregbaker/dynmodel-models | /gigi.py | 9,535 | 3.640625 | 4 | import dynmodel
import random
# input number of helpers, number of energy/maturity states each helper has, and total time in months
n_helpers = 3
helper_states = 37
#tmax = 30*12/3
tmax = 3
# this is the terminal fitness function (phi)
def phi(e, p, *helpers):
if p > 0:
# can't be pregnant at menopause
... |
4fe2d4541e323dec1bb31b4caa6000e7904d5791 | klknet/geeks4geeks | /algorithm/mathematical/count_num_without_3.py | 345 | 4.15625 | 4 | """
Count numbers that don't contain 3
"""
def count(n):
if n < 3:
return n
if n == 3:
return 2
if 3 < n < 10:
return n - 1
msd = 0
d = 0
t = n
while t // 10 != 0:
t = t // 10
msd = t % 10
d += 1
return count(n-msd*(10**d)) + count(msd)*(... |
5fbf8fb5497c0748bfdedf08eaa90500d43f0812 | Fenrisulvur/College-Python-Assignments | /Class Assignments/CodeHS/Text Games/Mastermind.py | 3,508 | 4.03125 | 4 | """
Corey Fults.
Assignment:
A 4 digit numerical code will be generated.
You must guess this code, you will receive hints by the codes RED, WHITE, BLACK.
RED == Correct Digit in the correct spot. WHITE == Correct Digit in the wrong spot, BLACK = Incorrect digit.
The hints will be shuffled to make it ha... |
105f2b756ca312b9f5b44ed0abfd206a65eba636 | Aryaman1706/Python_Beginner | /sets&sorting.py | 630 | 3.9375 | 4 | def belt_count(dictionary):
belts=list(dictionary.values())
# for belt in belts:
for belt in set(belts):
num=belts.count(belt)
print(f'there are {num} {belt} belts ')
def ninja_intro(dictionary):
for key, val in dictionary.items():
print(f'i am {key} and i am a {val} belt')
nin... |
df683c5785ed2139031f875aaa174070f1274579 | diegoasanch/Programacion-I-Trabajos-Practicos | /TP8 Tuplas, Conj, Dic/TP8.2 Fecha en Palabras.py | 921 | 4.21875 | 4 | '''
Escribir una función que reciba como parámetro una tupla conteniendo una
fecha (día,mes,año) y devuelva una cadena de caracteres con la misma fecha
expresada en formato extendido. Por ejemplo, para (12,10,17) devuelve
"12 de Octubre de 2017". Escribir también un programa para verificar su
comportamiento.
'''
from... |
38b44ac5fe18a96274ec5ae7a12891d95d5a1ce6 | Rivarrl/leetcode_python | /leetcode/offer/11.py | 852 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 11.py
# @Time : 2020/4/21 14:26
# @Author : Rivarrl
# ======================================
# [面试题11. 旋转数组的最小数字](https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/)
from algorithm_utils import *
class Solution:... |
e15debab93c465671a40f7fc8e3f1c1ce42dd298 | liupeiyu/LeetCode | /stringexercise/string_20_Valid_Parentheses.py | 1,236 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# @date: 2019-11-25 23:20
# @name: string_20
# @author:peiyu
'''
Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same ... |
6ae45199351028def0333eb4082b7a21f2c3c5da | Ragulranjith/python-programming | /posrneg.py | 174 | 3.890625 | 4 | n = float(input("Input a number: "))
if(1<= n <= 100000):
print("It is positive number")
elif n == 0:
print("It is Zero")
else:
print("It is a negative number")
|
4783c81215e8076db439f48712093f2dfa4bb71a | phamhailongg/C4T9 | /minihack2/Part 2/l9.py | 197 | 3.921875 | 4 | # make a list
n = input("Enter a list of numbers, separated by ‘ ‘ : ")
n = n.split(' ')
ln = []
for i in n :
i = int(i)
ln.append(i)
print("Sum of all entered numbers: ", sum(ln))
|
a04a95a762e0f2c04fd3732cebaea28712bf4d23 | Lolita05/python_homework | /6.functions/6.7.py | 206 | 3.53125 | 4 | #Функция, берущую указанный элемент из коллекции
def myget(d, k, v=None):
try: return d[k]
except KeyError: return v
d = [1, 2, 15, 36]
k = 2
print(myget(d, k))
|
594c7399a71d4e34b2f07e52af63617de9097240 | muduolin/hello_tensor | /hello_ml.py | 3,677 | 3.53125 | 4 | import tensorflow as tf
import numpy as np
import sys
NUM_STEPS = 500
MINIBATCH_SIZE = 100
TRAIN_CURRENT_BATCH = -1
""" Read Tensorflow MNIST test datasets
x_train, x_test are arrays of 28x28 2-d images, I need to convert them into arrays of vectors (size 784)
y_train, y_test are arrays of result,I need to ... |
7d9170add4262a49983a63cd3f4ea1524cafd6a7 | Birgirisar/Gagnaskipan | /timi_4.py | 454 | 3.640625 | 4 |
def power(base, exp):
if exp == 0:
return 1
return base * power(base,exp-1)
def multiply(a,b):
if a == 0:
return 0
elif a == 1:
return b
else:
return b + multiply(a-1, b)
def factorial(n):
if n == 0:
return 1
else:
return n * (factorial(n-... |
d2cbc4a324713cd57c311a6301604c50f4385ad8 | nnekasandra/My-lifestyle | /tutorial.py | 285 | 3.90625 | 4 | name=input( 'name:\n')
department=input('department:\n')
registration_no=input('registration_no:\n')
print(name)
print(department)
print(registration_no)
message=f"my name is {name}, I am in the department of {department} and my registration number is {registration_no}"
print(message) |
09e2c05f331c600039880357eda3bb8c6835b935 | jxx/uio-inf1100 | /sum9_4dice.py | 2,777 | 3.765625 | 4 | """
Exercise 8.8: sum 9, 4 dice
Decides if a dice game is fair.
You pay c euro and are allowed to throw four dice.
If the sum of the eyes on the dice is less than w, you win r euros, otherwise you lose your investment.
Should you play this game when
w = 9, r = 10, c = 1
Command line arguments:
--r Get this ... |
cca4b9d342523b85a5afe606608c3e401f7aacda | duythanh2k/Git-Demo | /someOtherFiles/other.py | 111 | 3.828125 | 4 | def HelloWorld:
for i in range(0, 10):
if i % 2 == 0:
print("even")
else:
print("odd")
HelloWorld() |
1edc06030942832b17154e9c24d918700b06f2c7 | computerteach/CSE | /school_Lunches.py | 476 | 4.3125 | 4 | #Create a program to ask the students about their lunch habits
from tkinter.messagebox import YES
eat_lunch_out = input("Do you eat lunch out during school? yes or no ")
if (eat_lunch_out =="yes"):
eat_lunch_out_choice = True
eat_lunch_out = input("Do you eat at Wendys, McDonalds, Burger King, Subway, Littl... |
9cccc0495fa093d98d19ecc76d733dddfd10b014 | R083rtKr01/PythonBasic | /P60.py | 385 | 3.59375 | 4 | from math import sqrt
def calculateDistance(x,y): #liczenie na płaszczyźnie
return round(sqrt(pow(y[0]-x[0],2)+pow(y[1]-x[1],2)),2)
p1=[1,1]
p2=[-2,-12]
print(calculateDistance(p2,p1))
def calculateDistance3D(p1,p2): #wersja trzy dy
return round(sqrt(pow(p2[0]-p1[0],2)+pow(p2[1]-p1[1],2)+pow(p2[2]-p1[2],2))... |
dab83fb674cf30122b6cd4fb34828ed8a4f67305 | Vishwajeetbamane/StarPrinter | /StarPrinter1.py | 322 | 4.21875 | 4 | print("Welcome to STAR PRINTING Program!\n")
ptype = input("How you want to print?\n 1 for Low to High\n 2 for High to low\n")
n = int(input("How many rows you want to Print?\n"))
if ptype == "2":
a = n
while a > 0:
print("*"*a)
a = a - 1
if ptype == "1":
a = n
for j in range(a+1):
print("*"*j)
a = a +1... |
5d9abed92a0af6f62b30ae36e89c50a8e54f9427 | pandongwei/traffic_road_classification | /kalman_filter.py | 2,610 | 3.59375 | 4 | '''
kalman filter
'''
import numpy as np
class KalmanFilter(object):
def __init__(self):
"""
Initialize variable used by Kalman Filter class
"""
#self.dt = 0.005 # delta time
self.H = np.eye(4) # matrix in observation equations
self.x_e = np.zeros([4,1]) # prev... |
a8fbdbc079da2010eb577f77f87c9c434958f6e6 | arnabs542/Data-Structures-And-Algorithms | /Graph/Construction Cost.py | 2,276 | 3.921875 | 4 | """
Construction Cost
Problem Description
Given a graph with A nodes and C weighted edges. Cost of constructing the graph is the sum of weights of all the edges in the graph.
Find the minimum cost of constructing the graph by selecting some given edges such that we can reach every other node from the 1st node.
NOTE... |
32e298962fd4e3c34cbfd9f666c833c5b9fe3f0d | bingli8802/leetcode | /0025_Reverse_Nodes_in_k-Group.py | 1,206 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
# 东哥思路
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
... |
514909bc967ddd8634e7cb454d904217094cc8a6 | Manekineko-mk1/Python-Algorithmic-Trading | /Python-for-finance-6.py | 2,284 | 3.53125 | 4 | import bs4 as bs # beautifulSoup
import pickle # serialize python objects (ex save S&P 500 list table)
import requests
import datetime as dt
import os # uses to create new directory
import pandas as pd
import pandas_datareader.data as web
# This demonstrates how to grab the pricing data from Yahoo, with the tickers... |
b67362d309f6b593d0c64c304fd5caf1ad7fa9dd | FishRedLeaf/my_code | /leetcode/探索中级算法/5排序和搜索/1颜色分类.py | 1,800 | 3.890625 | 4 | '''
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
'''
class Solution(object):
... |
789cf1dd8eaeb941e30290c070b135a8da83086f | Allan-Barbosa/respostas-beecrowd | /1828.py | 593 | 3.5 | 4 | n = int(input())
for i in range(1, n+1):
s, h = input().split(' ')
if s == 'tesoura' and h == 'papel' or s == 'papel' and h == 'pedra' or s == 'pedra' and h == 'lagarto' or s == 'lagarto' and h == 'Spock' or s == 'Spock' and h == 'tesoura' or s == 'tesoura' and h == 'lagarto' or s == 'lagarto' and h == 'papel' ... |
3de7a35db0ff58abeae9ca327e18d57c5d5c14e7 | rodrigocamargo854/Some_codes_python | /EQUACAO2GRAU.py | 1,428 | 4.1875 | 4 | titulo= "FORMAÇÃO DE UMA EQUAÇÃO DO 2º GRAU"
soma = 0
print("==" *40)
print(titulo.center(70))
print("==" *40)
while True:
print(" Digite os coeficientes a,b e c com respectivos\n sinais para formar uma equação do 2º grau\n\n")
a = input(" coeficiente a :")
b = input(" coeficiente b :... |
3a2d8ecc680d96bafc9be899c8d20a6d50080540 | Daria-Lytvynenko/homework6 | /homework6.py | 892 | 4 | 4 | if __name__ == '__main__':
# Task 2. Create a function which takes as input two dicts with structure mentioned above,
# then computes and returns the total price of stock.
stock = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3}
total_pric... |
029ce47824cfe1d704a9715aea241c68408dc0f8 | tonper19/PythonDemos | /costurero/pytest/test_math.py | 234 | 3.734375 | 4 | def add(x, y):
return x + y
def subtract(x, y):
return x - y
def inc(x):
return x + 1
def test_add():
assert add(1, 2) == 3
def test_subtract():
assert subtract(2, 1) == 1
def test_inc():
assert inc(1) == 2
|
53ed32797710dd560468574e21d869cad863b98e | CKMaxwell/Python_online_challenge | /edabit/4_Hard/Oddly_or_Evenly_Positioned.py | 723 | 3.75 | 4 | # 20201006 - Oddly or Evenly Positioned
# 其他人的答案有一行寫法
def char_at_pos(r, s):
if type(r) == list:
ans = []
if s == "even":
for i in range(1, len(r), 2):
ans.append(r[i])
if s == "odd":
for i in range(0, len(r), 2):
ans.append(r[i])
... |
25e1b646e8cd467cb117c68d8a3600d45679bb36 | Nastmi/adventOfCode2020 | /day2/password.py | 579 | 3.53125 | 4 | passwords = list(map(str.strip, open("day2/input.txt")))
#part 1
valid = 0
for password in passwords:
sep = password.split()
ocur = sep[2].count(sep[1][:1])
allowed = sep[0].split("-")
if(int(allowed[1]) >= ocur >= int(allowed[0])):
valid += 1
print(valid)
#part 2
valid = 0
for password in pass... |
e633b9436a2a050ecaa61ef8ade0ab684feb1255 | vkp3012/Python | /marksheet.py | 1,416 | 3.890625 | 4 |
# python program to print the student mark sheet
subjects = ["Chemistry", "C Programming", "Mathematics",
"Environment", "Electrical & Electronics", "Machine Engineering"]
subjcode = ["CH-102", "CS-102", "MA-111", "CS-107", "EE-101", "ME-101"]
midmarks = []
semmarks = []
count = MTotal = 0
name... |
009f496b3fbcc40570d94cedc8f2206a95d72ba1 | viralimehta/Python-part-1 | /21.py | 255 | 4.25 | 4 | ''' Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.'''
a=int(input("enter the number="))
if(a%2==0):
print("number is even.")
else:
print("number is odd") |
867780ce61e5b101d4565fb5203fb178bfa1a8b1 | bgwilf/PyCon2019 | /Accessory_Examples/potentiometer_neopixel_strip.py | 1,219 | 3.546875 | 4 | """This example requires a potentiometer and a NeoPixel strip. Talk to the team to get one of each!
Connect the blue clip on the potentiometer to pad A0.
Connect the black clip to a GND pad.
Connect the red clip to a 3.3v pad.
Connect the white clip on the NeoPixel strip to pad A7.
Connect the black clip on the NeoPi... |
1dba505d32dd7fd03301de1a78111623ce9a73ba | niushencheng/learn-py | /datamining/chapter4/06_principal_components_analyze.py | 483 | 3.609375 | 4 | """
主成分分析代码
"""
import pandas as pd
if __name__ == '__main__' :
input_file = '../resources/chapter4/demo/data/principal_component.xls'
data = pd.read_excel(input_file)
from sklearn.decomposition import PCA
pca = PCA()
pca.fit(data)
# 返回模型的各个特征向量
print(pca.components_)
print('-------... |
a12e068fa33bfd79d90dc690349544f212c50cfe | larserikgk/euler | /problem_3.py | 442 | 3.671875 | 4 | def get_largest_prime_factor(number):
primes = [x for x in range(10000) if is_prime(x)]
for x in reversed(primes):
if is_prime(x) and number % x == 0:
return x
def is_prime(number):
if number == 0 or number == 1:
return False
for x in range(2, number):
if number % x... |
8bbbf4f15161f3f410f799e167f3be79239027c6 | vojtechjelinek/strategy-games-simulations | /simulation/game.py | 1,644 | 3.703125 | 4 | # -*- coding: utf-8 -*-
from simulation.rules import Rules
class Game:
def __init__(self, player1, player2, n_rounds, rules):
self.player1 = player1
self.player2 = player2
self.n_rounds = n_rounds
self.rules = rules
def play(self, verbose):
for current_round in range(... |
fba3bd24bc18bfad8f7c98fda053556552faaf23 | PreranaPandit/Lab_Exercises3 | /Lab4/List/eight.py | 185 | 4.03125 | 4 | '''
8. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements
'''
list=[1,'hey',5,'dear',8,9,4,6]
list.pop(0)
list.pop(4)
list.pop(5)
print(list) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.