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 |
|---|---|---|---|---|---|---|
ecc3558c9e4efab2601815bd0d758ee8de254feb | venky5522/venky | /programs/hyphen_separated_string.py | 132 | 3.953125 | 4 | string = "green-red-yellow-black-white"
string=string.split('-')
string.sort()
string = '-'.join(string)
print(string)
|
4eecc7eea02458b9cd16fd85ec9bddedab86e483 | Munijp/dji-asdk-to-python | /dji_asdk_to_python/flight_controller/attitude.py | 390 | 3.609375 | 4 | class Attitude:
"""
This is a structure for presenting the attitude, pitch, roll, yaw.
"""
def __init__(self, pitch, roll, yaw):
"""
Args:
pitch ([float]): Pitch in degrees
roll ([float]): Roll in degrees
yaw ([float]): Yaw in meters
"""
... |
4a64742a51a07af775b2dfeafc641a6bce651df9 | CaptainTec/OJ | /1007最大子串和-python实现 | 1,268 | 3.546875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# 最大子列和,同时输出第一个和最后一个元素
def MaxSubseqSum(seq):
'''(list of number) -> None
问题:最大子列和问题,同时输出最大子列的第一个和最后一个元素
解决方法:在线处理
时间复杂度:O(n)
>>> seq = [-2, 11, -4, 13, -5, -2]
>>> MaxSubseqSum(seq)
The first value is: 11
The last value is: 13
20
... |
9731771ddfe4963840eba90f48443ca1a4fa80a1 | mucheniski/curso-em-video-python | /Mundo2/003EstruturasDeRepeticao/055MaiorMenorPeso.py | 523 | 4.03125 | 4 | # Exercício Python 55: Faça um programa que leia o peso de cinco pessoas.
# No final, mostre qual foi o maior e o menor peso lidos.
maiorPeso = 0
menorPeso = 0
for i in range(1,6):
peso = float(input('Informe o {}º peso: '.format(i)))
if i == 1:
maiorPeso = peso
menorPeso = peso
e... |
335bdb58b748317abdacaf5f5c9b6ad6181c40c8 | zdyxry/LeetCode | /greedy/1221_split_a_string_in_balanced_strings/1221_split_a_string_in_balanced_strings.py | 367 | 3.578125 | 4 |
class Solution:
def balancedStringSplit(self, s: str) -> int:
split = 0
unbalance = 0
for i in s:
unbalance += 1 if i == 'R' else -1 # 'R' = +1, 'L' = -1
if not unbalance: # if unbalance == 0
split += 1
return split
s = "RLRRLLRLRL"
res... |
51c57b83326cce637aa40701ba9ecbe997f5e20e | ISnxwNick/GeekBrains_PythonBasics_hw | /4less/4_2.py | 983 | 3.90625 | 4 | """
2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых
больше предыдущего элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования
списка использовать генератор.
Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
Ре... |
6562fcbd9abb54b8476f6fec80bc6eb5fcc27a91 | bitcsdby/Codes-for-leetcode | /py/Palindrome Number.py | 620 | 3.59375 | 4 | class Solution:
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False;
if x < 10:
return True
digit_num = 1
while x / digit_num >= 10:
digit_num = digit_num * 10;
if x == ... |
a62403d66baa3dcb7c8ccb22c001ee29769d1c4d | posborne/learning-python | /part8-outer-layers/p8ch27ex5.py | 2,612 | 3.671875 | 4 | #!/usr/bin/env python
############################################################
# This is a basic shell... Note that my implementation is
# very similar to Lutz' because I ended up getting stuck
# and following his code
############################################################
import cmd, os, sys, shutil
class... |
bc32a384e416808e7588ad62a0b886517e0007f5 | LucasGVallejos/Master-en-MachineLearning-y-RedesNeuronales | /03-Pandas/04-AccediendoACSV.py | 2,883 | 3.546875 | 4 | import pandas as pd
#La mayoria de los datasets vienen en archivos de texto
#Vamos a leer el contenido de movies.csv, le indicamos el separador del csv y formara un dataframe
movies = pd.read_csv('movielens/movies.csv',sep=',')
tags = pd.read_csv('movielens/tags.csv',sep=',')
ratings = pd.read_csv('movielens/ratings.... |
546427944b24c895461c83379023bc50bd5039f2 | renatogcruz/python | /poo_py/s_3_fila.py | 531 | 3.5 | 4 | import heapq
class FilaDePrioridade:
def __init__(self):
self.fila = []
self.indice = 0
def inserir(self, item, prioridade):
heapq.heappush(self.fila,(-prioridade, self.indice, item))
def remover(self):
return heapq.heappop(self.fila)[-1]
class Item:
def __init__(self, nome):
self.n... |
e80a639d7289567b79ede10f3b869623ba09a5b7 | TheDUZER/challenges | /02 - Temperature Converter.py | 1,872 | 4.25 | 4 | #Temperature Converter by Ian Guitard
def tempConvert():
try:
x = input("Enter the original temperature number immediately followed by a 'C' for Celsius, 'F' for Farenheit, or 'K' for Kelvin.\n Example: 100.243C\n")
#Convert Kelvin to Celsius or Farenheit
if x[-1] == 'K' or x[-1] == 'k':... |
b63bc60dcfd6ceedc8dd1ce672026da3adc4b740 | dlopezg/leetcode | /medium/findNthDigit.py | 2,573 | 3.8125 | 4 | import time
# Find the nth digit of the infinite integer sequence:
# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
# Note:
# n is positive and will fit within the range of a 32-bit signed integer (n < 231).
# EXAMPLE:
# Input: 11
# Output: 0
# Explanation:
# The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, .... |
8adcacb9d5113f7f3ac7156efde3aff28ab4f606 | mcenek/corrosion | /cbcc/feature.py | 7,152 | 3.578125 | 4 | import numpy as np
import cv2
# Get patch returns a cropped portion of the image provided using the globally defined radius
# pixel is a tuple of (row, column) which is the row number and column number of the pixel in the picture
# image is a cv2 image
def get_patch(pixel, image, height, width, sd_matrix):
radius = ... |
8361ac79b4b5f7153ea82fab8ba5fe3b8c550309 | Jeffrey-A/Data_structures_and_algorithms_Programs | /HW4/Part2/Deck.py | 4,059 | 4.25 | 4 | # Deck.py
#Jeffrey Almanzar part 2
# def size() now is not needed, I am using an instance variable to get the size of the deck as suggested for exercise 1
import random
from Card import Card
class Deck(object):
#------------------------------------------------------------
def __init__(self):
"""po... |
0bd7e49b0abe70bfb1d54b30e5341729c7ac1e61 | assi23/calculadoraHavanProWay | /calculadora.py | 1,902 | 3.828125 | 4 | #Criação de variáveis, juntamento com a lista das moedas pré-cadastradas
listaMoedas = ["dólar","Dólar","euro","Euro","real","Real"]
moedaOrigem = input(" Insira a moeda de origem dentro dessas moedas pré-cadastradas:" +str(listaMoedas))
moedaDestino = input(" Insira a moeda de destino dentro dessas moedas pré-cadas... |
5f3eb49ebc39335642b8dfbcb412f39f35fae3ac | karan68/Python_mini_projects | /rock,paper,scissor.py | 1,570 | 4.1875 | 4 | from random import randint
print("welcomw to the rock,paper and scissor")
print("there will be 5 rounds hope you win!")
#create a list of play options
t = ["Rock", "Paper", "Scissors"]
#assign a random play to the computer
computer = t[randint(0,2)]
#set player to False
player = False
u=0
c=0
i=6
whil... |
c648ebb547b2e0b7e8c2b85a1d949ca39261c5d5 | ma0723/Min_Algorithm | /Algorithm_Practice/Subset.py | 569 | 3.5625 | 4 | arr = [-7,-3,-2,5,8]
n = len(arr)
# 원소의 개수
my_big_list = []
for i in range(1<<n):
# 부분집합의 개수
my_small_list = []
for j in range(n):
# 원소의 개수만큼 비트를 교환
if i&(1<<j):
# i의 j번째 비트가 1이면 j번째 원소를 출력
my_small_list.append(arr[j])
my_big_list.append(my_small_list)
print(my_big_list)
pr... |
2e6aa177eca95298c32938448034f3cb722dd741 | yknyim/dictionary-exercises-git | /letter_histogram.py | 349 | 3.890625 | 4 | # from collections import Counter
# user_input = input('Please write anything: ')
# print(Counter(user_input))
###############################
# txt = input('Please enter a word: ')
# small_text = txt.lower()
# count = dict()
# for x in small_text:
# count[x] = count.get(x, 0) + 1
# print(count)
###########... |
4620abb04fa445a60e81b147610677718c2d79db | VictorPGitHub/AsteroidsGame | /asteroids.py | 4,281 | 3.65625 | 4 | import sys
import random
import pygame
from pygame.locals import *
from game import Game
from ship import Ship
from point import Point
from rocks import Rocks
from star import Star
from bullet import Bullet
class Asteroids( Game ):
"""
Asteroids extends the base class Game to provide logic for the specific... |
9ea21d7f09e6d8b2b0fa708c90adf408debc228a | Vi-r-us/Python-Projects | /11 Binary Hexadecimal Conversion.py | 1,673 | 4.0625 | 4 | import time
print("Welcome to the Binary/Hexadecimal Converter App.")
while True:
max_value = int(input("\nCompute Binary and Hexadecimal value up to the following Decimal Number: "))
decimal = list(range(1, max_value+1))
print("Generating Lists", end='')
for i in range(3):
print(".", end='')... |
54da2d5e0043974b441f6897fe4251b0ec916bf6 | ogulcangumussoy/Python-Calismalarim | /Hatalar-ve-Istisnalar/Uygulama/hata-yakalama-try-except-finally.py | 288 | 3.6875 | 4 | try:
a = int(input("Sayi1: "))
b=int(input("Sayi2: "))
print(a / b)
except ValueError:
print("Lütfen sayıda string kullanmayınız")
except ZeroDivisionError:
print("Payda 0 olamaz.")
finally:
print("Burası çalışmak zorunda")
print("İşlemler sonlandı.")
|
bb8c697fe5e13bef7978ecfde8f6efacccc82446 | cyct123/LeetCode_Solutions | /394.decode-string.py | 2,237 | 3.671875 | 4 | #
# @lc app=leetcode id=394 lang=python3
#
# [394] Decode String
#
# https://leetcode.com/problems/decode-string/description/
#
# algorithms
# Medium (56.58%)
# Likes: 10322
# Dislikes: 459
# Total Accepted: 615.8K
# Total Submissions: 1.1M
# Testcase Example: '"3[a]2[bc]"'
#
# Given an encoded string, return it... |
67ca9852309fde372688ebb8baad930cfb0eb9ef | Frecy16/learning | /py_study/pydef/13、匿名函数.py | 977 | 3.9375 | 4 | def add(a, b):
return a + b
# x = add(4, 5) # 函数名(实参) 作用是调用函数,获取到函数的执行结果,并赋值给变量x
# print(x)
# print("0x%X" % id(add))
# fn = add # 相当于给函数add起了一个别名fn
# print("0x%X" % id(fn))
# print(fn(3, 4))
# 除了使用def 关键字定义一个函数以外,还可以使用 lambda 表达式定义一个函数
# 调用匿名函数两种方式:
# 1.给它定义一个名字(很少这样使用)
# 2.把这个函数当做参数传给另一个函数使用
# lambda a, b: ... |
cc578bbacd0c246a691a6026851cc0f07d0b0bb6 | Aasthaengg/IBMdataset | /Python_codes/p02831/s641524900.py | 148 | 3.53125 | 4 | from fractions import gcd
def lcm(a, b):
res = a*b / gcd(a, b)
return res
a, b = map(int, input().split())
ans = int(lcm(a, b))
print(ans) |
44b2ec9bac8b5f436d717106fe9614d14c119c6c | masonicGIT/two1 | /two1/lib/bitcoin/hash.py | 2,137 | 3.828125 | 4 | import hashlib
from two1.lib.bitcoin.utils import bytes_to_str
class Hash(object):
""" Wrapper around a byte string for handling SHA-256 hashes used
in bitcoin. Specifically, this class is useful for disambiguating
the required hash ordering.
This assumes that a hex string is in RPC order... |
645c1783a207e46cfbb1fbaa86e068c62361d477 | rafaelperazzo/programacao-web | /moodledata/vpl_data/445/usersdata/310/101808/submittedfiles/matriz2.py | 490 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
input('Valor de x1: ')
input('Valor de x2: ')
input('Valor de x3: ')
input('Valor de y1: ')
input('Valor de y2: ')
input('Valor de y3: ')
input('Valor de z1: ')
input('Valor de z2: ')
input('Valor de z3: ')
matriz= [
[x1,x2,x3],
[y1,y2,y3],
[z1,z2,z3]
]
i... |
6fcc88246941164249313afb2695ac56f888a666 | yuanning6/python-exercise | /005.py | 704 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 20:14:55 2020
@author: Iris
"""
username = input('请输入用户名:')
password = input('请输入口令:')
# 用户名是admin且密码是123456则身份验证成功否则身份验证失败
if username == 'admin' and password == '123456':
print('身份验证成功!')
else:
print('身份验证失败!')
x = float(input('x = '))
if x > 1:
... |
9096a3e99bc7c4fc28b7e2e9cf5c417a1d34470f | LILeilei66/tfLearn | /6_1grad_eager.py | 1,651 | 3.640625 | 4 | """
tf.GradientTape:
================
Record operations for automatic differentiation.
parameters:
persistent: bool, if True, gradient function can be called plural times.
watch_accessed_variables: bool, if False, need to trace the expected tensor by hand.
watch():
========
Ensures that `tensor` is being trace... |
ceb0c66e13b10023e08689880054d00ddfe4d1fe | gerglion/ProjectEuler | /Problem_16/problem16.py | 803 | 4.0625 | 4 | #!/usr/bin/python3.4
# Project Euler:
# Problem #16: Power Digit Sum
#
# 2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#
# What is the sum of the digits of the number 2 ^ 1000?
#
# Answer: 1366
import sys
def sum_digits(base,power):
the_number = base ** power
dig_list = []
#print("Ex... |
26448e5269fa0bb7020ee9f8c0da7794a7e27adb | nipuntalukdar/NipunTalukdarExamples | /python/misc/threadedtree.py | 3,873 | 3.5 | 4 | from random import randint
import unittest
class Node(object):
def __init__(self, val):
self.__val__ = val
self.__thread__ = None
self.__left__ = None
self.__right__ = None
@property
def val(self):
return self.__val__
@val.setter
def val(self, val):
... |
facace2361ef3f0770357ec4412c5c2d5e42b74f | heuzin/interview-codes | /checkPalindrome.py | 245 | 4 | 4 | # Given the string, check if it is a palindrome.
def checkPalindrome(inputString):
newString = []
for x in reversed(inputString):
newString.append(x)
if ''.join(newString) == inputString:
return True
return False |
96ef5e3d6015e4a48ff6b6e73d1f97c9264dea02 | bishaljung/file_writing_python | /friend_list_data_file_handling.py | 3,074 | 3.65625 | 4 | import sys
import os
def write_data(name):
friend = open(name+".txt",'w')
id_num = input('ID number: ')
phone_number = int(input('phone_number: '))
friend.write("the details of {} is:\n".format(name))
friend.write("name: %s\n" %name)
friend.write("id_num: %s\n"% id_num)
friend.w... |
732064d7c77be799ca1907b7c19d461d4303dbf1 | shinrain/leetcode-python | /code/BalancedBinaryTree.py | 472 | 3.71875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return helper(root)!=-1
def helper(root):
if root is None:
... |
a08ec5b22a3dc9bc70a465b436e322c08aca304c | ejwessel/LeetCodeProblems | /48_RotateImage/Solution.py | 2,547 | 3.84375 | 4 | def rotate_image(m):
row = 0
col = 0
layer = 0
while row < len(m) - 1 - layer:
for i in range(len(m) - 1 - (2 * layer)):
temp = m[row][col + i]
m[row][col + i] = m[len(m) - 1 - layer - i][col] # top pulling from left
m[len(m) - 1 - layer - i][col] = m[len(m) -... |
4f148667b4b39576f4f29525c9d27111cf309e00 | driellevvieira/ProgISD20202 | /Gilberto/Aula 9/Aula 09.py | 6,421 | 3.828125 | 4 | # Aula 09 - Programas da aula + slides
import numpy as np
A = np.array([[1,1],
[0,1]])
B = np.array([[2,0],
[3,4]])
print(A)
print(B)
print(A*B)
print(A-B)
print(A+B)
print(A@B)
'''
import numpy as np
vetor = np.array(((1., 0., 0.),(0.,1.,2.)))
print(vetor)
import numpy as np
print(np.... |
1cddde04dd6426c2b687fa701f358dea45c9b839 | Alvin-21/password-manager | /user_credentials.py | 2,500 | 3.765625 | 4 | from random import choice
import string
class User:
"""
Class that generates new instances of users.
"""
user_list = []
def __init__(self, fname, lname, username, password):
self.fname = fname
self.lname = lname
self.username = username
self.password = password
... |
90c132b58970262d6d9e6d19de49f6786403011e | sunnyyeti/Leetcode-solutions | /2011 Final Value o Variable After Performing Operations.py | 1,534 | 4.1875 | 4 | # There is a programming language with only four operations and one variable X:
# ++X and X++ increments the value of the variable X by 1.
# --X and X-- decrements the value of the variable X by 1.
# Initially, the value of X is 0.
# Given an array of strings operations containing a list of operations, return the fin... |
5b0f38fb1512e2c37533d3145fa067dd8df607cf | VigneshwarRavichandran/logics | /SP - Palindrome Family.py | 830 | 3.796875 | 4 | t=int(input())
while t>0:
a=input()
odd_str=""
odd_count=0
even_str=""
even_count=0
parent_count=0
for i in range(0,len(a),2):
odd_str=odd_str+a[i]
for i in range(1,len(a),2):
even_str=even_str+a[i]
odd_temp = odd_str[::-1]
if(odd_str==odd_te... |
072e09c89e4f4f0df619c7e96a1ca89752d3ce8a | DarkAlexWang/leetcode | /C3IOT/string_replace.py | 1,990 | 3.53125 | 4 | class Solution:
def string_replace(self, string, s, t):
array = list(string)
if len(s) >= len(t):
return self.replace_shorter(array, s, t)
return self.replace_longer(array, s, t)
def replace_shorter(self, array, s, t):
slow = 0
fast = 0
while fast < le... |
7ca6f7aacd5a3560efa31a6b3f57e043ee94560b | domino14/euler | /39.py | 633 | 4 | 4 | """
a^2 + b^2 = c^2
p = a + b + c
"""
def solutions(p):
"""
Find number of solutions for a right triangle with integral sides.
>>> len(solutions(120))
3
"""
sols = set()
for a in range(1, p-2):
for b in range(1, a-1):
c = p - a - b
if a**2 + b**2 == c**2:
... |
f186f783eaa01607371da45a8dc0993bb5f86492 | pneumoo/reddit-psio-tool | /pushshiftTool.py | 14,398 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 14 21:43:23 2018
@author: Brian
"""
import json
import requests
import time
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
"""
Returns a string of the URL COMMENT Search command for Pushshift.io
Ex... |
6095e1fd373902fd4d2c8ca51ea10c67724447a1 | Miracle-bo/Evernote | /19.06/demo-if语句2.py | 511 | 3.640625 | 4 | money = int(input('请输入您的存款(万):'))
if money > 500:
print('您的存款超过500万,建议您购买路虎')
elif money > 100:
print('您的存款超过100万,建议您购买宝马')
elif money > 50:
print('您的存款超过50万,建议您购买迈腾')
elif money > 10:
print('您的存款超过10万,建议您购买福特')
elif money > 5:
print('您的存款超过5万,建议您购买比亚迪')
else:
print('您的存款低于5万,不建议您购买车辆') |
e2e0d661461c111dafaf01bec387c98964a36cbb | sushantsikka/codeforces-solutions | /cheap-travel.py | 423 | 3.875 | 4 | # Cheap travel
# http://codeforces.com/problemset/problem/466/A
n = int(input("Enter number of rides planned"))
m = int(input("Enter number of rides covered by m ticket"))
a = int(input("Enter price of one ticket"))
b = int(input("Enter price of m ride ticket"))
sum1 = ((n-(m*int((n/m))))*a) + (b*int((n/m)))
... |
13c5e3c1208956225a901a156092b5216a3edba0 | Zahed75/PythonCode_Practice | /matrix.py | 311 | 4.09375 | 4 | matrix=[
[1,2,3],#1 no row/colum index 0 theke start hobe
[2,4,5], #2no Row/colum index 0 theke start hobe
]
print(matrix[1][2])
#change the matrix value change
'''matrix[1][2]=10
print(matrix[1][2])'''
#print coloum wise matrix value
for row in matrix:
for column in row:
print(column)
|
dfabcbd9f814391a5ca165ad604a1912df941e63 | AustinTSchaffer/DailyProgrammer | /GameSolvers/ColorSortPuzzle/android_game/game_objects.py | 2,337 | 3.96875 | 4 | import collections
import dataclasses
import math
from typing import Tuple, List, OrderedDict, Dict
@dataclasses.dataclass(frozen=True)
class Circle:
column: int
row: int
radius: int
color: Tuple[float]
@dataclasses.dataclass(frozen=True)
class Container:
"""
Names the properties of the rect... |
58608f77a848799337196010ba99af2cc307af19 | alirezaghey/leetcode-solutions | /python/merge-two-binary-trees.py | 1,719 | 4.125 | 4 | from typing import Optional
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# Time complexity: O(max(n, m)) where n and m are the nu... |
02e053395fa7ce8ca0b0a01aee5edb007e17062c | DustinY/EcoCar3-Freshmen-Training | /Assignment_1/Matthew/Celsius_to_Ferenheit.py | 371 | 3.875 | 4 | # Converting Celsius to Farenheit
# Formula: T(F) = T(C) * 1.8 + 32
print "Converting Celsius to Farenheit "
print " "
var_Celsius = int(raw_input("Enther the temperature in Celsius. "))
Ferenheit = var_Celsius * 1.8 + 32
#print (var_Celsius, " is ", Ferenheit, " in degrees Ferenheit. ")
print var_Celsius
print "... |
cec35f3624a1dd904cef268add642fa33906416d | NolanBabits/compsci101 | /labs/lab4/Part 1/listprint.py | 438 | 3.9375 | 4 | import filetolist
print("file to print")
file = input()
list = filetolist.filetolist("test.txt")
#print (list)
print("1 for whole list 2 for evey 3rd item")
k = int(input())
#k = 2
if k == 1:
print(list)
exit()
elif k == 2:
x = 1
for i in list:
#print (x)
#print (i)
if x % 3... |
88af4bb26412756f302e6e1ba1c4391eb7f93bc3 | KnutHurlen/vegvarsel-variousscripts | /.vscode/download/Code/Copy of loading data into Python.py | 3,019 | 3.6875 | 4 | ########################################
#Read from file
#####################################
#First open .csv files in notepad to see what's there
#Use folder icon to select path
#Load necessary libraries
import pandas as pd
import os
#Mac
os.chdir('/Users/chandler/OneDrive - BI Norwegian Business School (BIEDU)/... |
8c0b80553decc3e3ba9398c302bdd0f7e74b06a1 | dkeen10/A01185666_1510_v3 | /Lab02/lab02.py | 675 | 4.09375 | 4 | import random
def roll_die():
"""
asks user for number of rolls and number of sides of the die and returns the result
:param number_of_rolls: number of die rolls
:param number_of_sides: number of sides of the die
:return: the result of the dice roll
"""
number_of_rolls = int(input("how man... |
78566c901a08f882eb6e887267a14a42c07adc6d | andyc1997/Data-Structures-and-Algorithms | /Algorithms-on-Graphs/Week1/reachability.py | 1,438 | 4 | 4 | #Uses python3
import sys
# Task. Given an undirected graph and two distinct vertices u and v, check if there is a path between u and v.
# Input Format. An undirected graph with n vertices and m edges. The next line contains two vertices u
# and v of the graph.
# Output Format. Output 1 if there is a path between u and ... |
da47b660c6630f14cb23fd5b18c4fe12626b4eb0 | bossyjossy/IAmLearninPython | /exercises/LPTHW_Exercise8.py | 1,306 | 4.09375 | 4 | # This is my completed exercise for Learn Python The Hard Way Exercise 8
#
# This is slightly modified from the lesson so that I can test things out
# and really solidify what I learned.
#
# EXERCISE 8: Printing, Printing
# This line will set the variable 'formatter' to print a string four times
formatter = "%r %r %r ... |
d47addddab4cc76d272167b877f524aa96c02853 | Vhrizon/AnyDump | /Main.py | 249 | 3.5 | 4 | #main
#ord() = int value of chr() chr(ord('a'))
#file_contents = f.read()
import
def FileRead():
("Please give the file name")
def Encrypt():
def Decrypt():
def Menu():
print("1. Encrypt\n2. Decrypt\n3. exit")
|
d497042484f137101d3a7b13fd4303ccbd204c52 | f-e-d/2021-Algorithm-Study | /Programmers/suyeon/binary_search/징검다리.py | 701 | 3.5 | 4 | def solution(distance, rocks, n):
rocks.sort()
rocks.append(distance)
answer = 0
start, end = 1, distance # answer은 1 ~ distance 사이에 있음
while start <= end:
mid = (start + end) // 2
# 부서진 바위의 수 세기
cnt_rock, prev_rock = 0, 0
for rock in rocks:
... |
956f7e7a08b475a33f83759b8de6ed3605c07d70 | mcfitzgerald/thesis2.0 | /ipythes/ligmods.py | 809 | 3.53125 | 4 | #Useful functions for ligand binding simulation and fitting
#Load Dependencies
import numpy as np
#Simulating data
#Dilution series
def dilser(low=0.001, limit=100.0, dilfactor = 2.0):
"""Returns a numpy array containing a dilution series that ranges from
"low" to "limit" by "dilfactor".
"""
a = [l... |
923999aea0bd4dbe936612a17833958418578d4f | aguscerdo/183D-capstone | /PHANTOMbots/environment.py | 4,697 | 3.515625 | 4 | ### ENVIRONMENT CLASS
# size is [x,y], which gives the number of vertices in our grid
# vertices is the set of all vertices in our maze,
# a vertice is defined by its x and y coordinate ([x, y])
# We assume that all adjacent vertices connected if they are in the grid
# bots is a list of PhantomBots in our simulation
... |
363d1684436df120d90813d18133fed628460344 | robillersomeone/NYT_bestsellers | /ETL/combining_data.py | 979 | 3.546875 | 4 | import pandas as pd
# read in data
gr_2016_df = pd.read_csv('../data/2016_goodreads.csv')
gr_2017_df = pd.read_csv('../data/2017_goodreads.csv')
gr_2018_df = pd.read_csv('../data/2018_goodreads.csv')
gr_2019_df = pd.read_csv('../data/2019_goodreads.csv')
# need to account for list elements in 'publisher' and 'data' i... |
de8cb82568bcda295804fd14e80698fa731d8fc6 | shartrooper/My-python-scripts | /Python scripts/Rookie/If-else-fun.py | 368 | 4.0625 | 4 | name = 'Marko'
while name != "Adrian":
if name != 'Adrian':
print('name is not true, write your true name, Adrian')
name=input()
if name == 'Adrian':
print('Well done!')
elif name == 'Marko':
print('Fuck off bozzo!')
break
else:
print('You act... |
08d372dc1d03ab218fdb955ac811c3e1037fdee6 | predtech1988/Courses | /data_structures/exercise/06/merge_Sorted_Arrays.py | 1,932 | 4.40625 | 4 | #Naive version
def merge_sorted(arr1, arr2):
#check input
#create empty list
answer = []
#read array's one by one, and add items to "empty list"
for item in arr1:
answer.append(item)
for item in arr2:
answer.append(item)
#at the end use .sort() methon on "empty list"
... |
53dd3cd68d986b0411db795bada083e6655afeab | td736/Blackjack | /Table.py | 2,448 | 3.578125 | 4 | from Dealer import Dealer
from Player import Player
class Table:
def __init__(self):
self.dealer = Dealer()
self.player_list = []
def add_player(self):
name = input("Name: ")
buy_in = input("Buy-in: ")
self.player_list.append(Player(name, int(buy_in)))
def remove... |
de27f87667f031c59561bde2b95551a3628b4ec8 | asterix135/algorithm_design | /quiz_quick_sort.py | 4,184 | 3.65625 | 4 | '''implemetation of quick sort algorithm for programming questions'''
m_count = 0
def sort_array(array, sub_option=3):
"""
Main call - sub_option refers to problem number in homeowork
array is actually a list
"""
quick_sort(array, 0, len(array)-1, sub_option)
def quick_sort(array, left, right, su... |
271daf182e54da204d147997a7d27bff3e2d030d | prastabdkl/pythonAdvancedProgramming | /chap7lists/others/failchap8password_login.py | 1,309 | 4.09375 | 4 | # passwords for the campus computer system must meet the following requirements:
# • The password must be at least seven characters long.
# • It must contain at least one uppercase letter.
# • It must contain at least one lowercase letter.
# • It must contain at least one numeric digit.
password_message = """Enter a p... |
2ab270e329a5ed8f9043e147b13b4cf9afec1de7 | joestalker1/leetcode | /src/main/scala/BinaryTreeZigzagLevelOrderTraversal.py | 992 | 3.640625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import defaultdict
class Solution:
def zigzagLevelOrder(self, root: TreeNode):
if not root:
return []
def traverse(node, level, m):
if not no... |
a59502aa5b87790b190a5c6d485f3ea651f5d2e8 | esther1104/myPy | /복습/14A-calc_re.py | 695 | 3.53125 | 4 | import random
def make_question():
a=random.randint(1,50)
b=random.randint(1,30)
op=random.randint(1,3)
q=str(a)
if op==1:
q=q+"+"
if op==2:
q=q+"-"
if op==3:
q=q+"*"
q=q+str(b)
return q
right_answer=0
mistake_answer=0
for x in range(7):
q=make_qu... |
8bb8026500e0a640dd5b196ba227f4a253bd599f | davidozhang/hackerrank | /python_domain/itertools/itertools_combinations_with_replacement.py | 268 | 3.578125 | 4 | #!/usr/bin/python
from itertools import combinations_with_replacement
def main():
s, n = raw_input().split()
for i in list(combinations_with_replacement(list(sorted(s, key=str.upper)), int(n))):
print ''.join(i)
if __name__ == '__main__':
main()
|
3b7256c2b33a029779d13e1518554ae6f1a89e1d | liuskyo/Python-Practice | /py259_劉天佑.hw5.py | 950 | 3.5625 | 4 | class student:
def __init__(self,name,gender):
self.grades=[]
self.name=name
self.gender=gender
def avg(self):
sum=0
for i in self.grades:
sum=sum+i
return sum/len(self.grades)
def add(self,grade):
self.grades.append(grad... |
180cf7d6fd71a56e68f41ed38358740571e42f9b | RameswariMishra/LearningPython | /jsontest.py | 613 | 3.78125 | 4 | import json
alphabets_json = '{"a":"A","b":"B"}'
alpha_dict = json.loads(alphabets_json)
print(alpha_dict)
new_json = json.dumps(alpha_dict)
print(new_json)
# reading a json file
with open("/Users/rameswarimishra/Library/Preferences/PyCharmCE2019.3/scratches/Employee.json") as f:
dict_a = json.load(f)
print(dict... |
ef385076a27c987c86adea36fe8031707ebb6f99 | XavierCHEN34/LeetCode_py | /206.Reverse Linked List.py | 1,246 | 3.9375 | 4 |
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
def generate_LN(l):
head = ListNode(l[0])
p = head
if len(l) == 1:
return head
for i in l[1:]:
p.next = ListNode(i)
p = p.next
return head
def print_LN(head):
l = []
p ... |
3c0d3be84a80bf7ce1c35f03d8e537ed8ef0a939 | kaumnen/codewars | /[5 kyu] Valid Parentheses.py | 319 | 4 | 4 | def valid_parentheses(string):
temp = [1]
for i in string:
if i == ')':
if temp[-1] == '(':
temp.pop(-1)
else:
return False
elif i == '(':
temp.append(i)
if temp == [1]:
return True
return False
|
1fa50f14f6355b3ba10779de16950d1d0ece7458 | heronc95/Final-Project | /mongodb_setup.py | 1,233 | 3.8125 | 4 | """
Write code below to setup a MongoDB server to store usernames and passwords for HTTP Basic Authentication.
This MongoDB server should be accessed via localhost on default port with default credentials.
This script will be run before validating you system separately from your server code. It will not actually be u... |
92528a9158c84b9486f1f98619b6893a9e361f95 | koreakevin/BJ_Algorithms_Study | /bj10866.py | 2,537 | 3.6875 | 4 | from collections import deque
import sys
n = int(sys.stdin.readline())
dq = deque()
def empty():
if len(dq) == 0:
return 1
else:
return 0
def size():
return len(dq)
for i in range(n):
cmd = list(sys.stdin.readline().split())
if cmd[0] == 'push_front':
dq.appendleft(cmd[... |
fd76a1dd8e761c5c7183a2b2917153d67a407066 | lakshuguru/Geeks-for-Geeks | /List/1.multiply-nums-list.py | 406 | 3.9375 | 4 | '''The problem of finding the summation of digits of numbers is quite common. This can sometimes come in form of a list and we need to perform that. This has application in many domains such as school programming and web development.
Let’s discuss certain ways in which this problem can be solved.'''
l=[4,2,3]
k... |
675d3d6f08106d721baa4e3aa793550c56a0cd85 | Bushidokun/Python | /Learning/TCA/Review TCA 3/Nesting.py | 509 | 4.0625 | 4 | print ("Welcome to the Planet of the Apes...")
humanTotal = 0
apeTotal = 0
for loop in range(7):
print ("...be ye human or be ye ape?")
userBe = input()
if userBe == "Human":
humanTotal += 1
print ("I did not start this war. But I will finish it.")
elif userBe == "Ape":
apeTota... |
322daedcc7e797d9c1339b36b3d2d6a953b03d6a | borgebj/IN1000-Python | /innlevering2/kodeforstaaelse.py | 892 | 4.03125 | 4 | """dette programmet tar input for et heltall og sjekker om heltallet hentet fra brukeren er mindre enn 10 eller ikke"""
#1) Er dette lovlig kode?
#- Nei, det er ikke. Grunnen for at det ikke er lovlig kode er fordi + tegnet som er skrevet i print er for å sette sammen tekstself.
#Koden vil legge sammen en variabel som... |
be081d9e9cd0c32a8d939bcb9cea0916a24ba1ff | NikilReddyM/algorithms | /divisible_sumpairs.py | 265 | 3.5625 | 4 | from itertools import combinations
def divisible_sumpairs(a,s):
c=0
for a,b in list(combinations(a,2)):
if (a+b)%s == 0:
c += 1
return(c)
n,s = map(int,input().split())
a=map(int,input().split())
print(divisible_sumpairs(a,s))
|
ba7b9e939eff5958ceab0d1cb853048920484cb7 | gchotai/python-workshop | /kth_most_char.py | 896 | 3.53125 | 4 | from collections import Counter
class soluction:
# 'solution - 1'
def top_k_frequency(self, nums, k):
cnt = Counter(nums)
most_common_k = cnt.most_common(k)
res = [num[0] for num in most_common_k]
return res
# 'solution - 2'
def topKFrequent(self, nums, k):
"""
... |
e94cc4871f150b0060fae76cef18f0a17b40619e | Mschikay/leetcode | /855. Exam Room.py | 1,917 | 3.53125 | 4 | class ExamRoom(object):
def __init__(self, N):
self.N = N
self.students = []
def seat(self):
if not self.students:
student = 0
else:
dist, student = self.students[0], 0
for i, s in enumerate(self.students):
if i:
... |
4cdd64c11e2b6336e5f72a92956cbacb94a863d9 | DonaldButters/Module4 | /test_price_under_between_ten_thirty.py | 1,392 | 4.0625 | 4 | import unittest
def calculate_price(price, cash_coupon, percent_coupon):
subtotal = (price - cash_coupon)
subtotal2 = subtotal * (1-(percent_coupon/100))
tax = (.06 * subtotal2)
if subtotal2 < 10:
shipping = 5.95
elif subtotal2 >= 10 and subtotal < 30:
shipping = 7.95
elif subtotal2 >= 30 and subto... |
a3fa153d55ee0f89fd589407a47edc003f88325b | phenyque/puzzles | /mosaic/mosaic_solver.py | 2,308 | 3.625 | 4 | """
Solve a given mosaic riddle (as .csv file), by treating it as a system of equations.
"""
import csv
import matplotlib.pyplot as plt
import numpy as np
import sys
from scipy.optimize import lsq_linear
def main():
if len(sys.argv) != 2:
print('Error: No mosaic file given!')
print('Usage: {} RI... |
9a9b5d9af34ca285149d1c1a0501e70c82732dd1 | cococastano/cs231n_project | /two_layer_neural_net.py | 4,253 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import data_utils
import extract_features
from neural_net import TwoLayerNet
def rel_error(x,y):
""" returns relative error """
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
def eval_numerical_gradient(f, x, verbose=True... |
25c842c442b2e9588556188273ba75cc90de5bef | hacker-dude/codeForces | /Problemset/Stones on the Table.py | 224 | 3.609375 | 4 | n = int(input())
stones = input()
new = stones
while 'RR' in new:
new = new.replace('RR', 'R')
while 'GG' in new:
new = new.replace('GG', 'G')
while 'BB' in new:
new = new.replace('BB', 'B')
print(n - len(new))
|
e2e5b74e8f7acd02cf25a0993f94c64cf4f5da64 | Foreman1980/1.2_AlgorithmsDataStructures | /2 урок/les2_task9.py | 1,869 | 3.9375 | 4 | # Задание № 9 урока № 2:
# Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр. Вывести на экран это число и сумму
# его цифр.
#
# Примечания:
# В заданиях 2, 3, 4, 7, 8, 9 пользователь вводит только натуральные числа.
# Попытайтесь решить задания без использования массивов... |
82a81a12e1873981ccb60927cd11908d54bc8e5a | 130-Miura/everyDayWriteCode | /about_set.py | 513 | 3.546875 | 4 | # import time
# def time_check(func):
# start = time.time()
# func()
# end = time.time()
# print(end - start)
# list()にtarget以外の要素があるかどうかの確認は、set()にして減算することで確認できる
arr = ['abc', 'def', 'ghij', 'klmno']
target = ['abc', 'ghij', 'kk']
# print(set(arr) - set(['abc', 'ghij']))
# print(bool(set(ar... |
e1a71d81e8fd7786083bc99482408adfe3b3d2c9 | carlosmgc2003/guia1paradigmas5 | /ejercicio8.py | 1,199 | 3.734375 | 4 | #En Años anteriores, se necesitaba una función en python que reciba un texto conteniendo bits (simbolos
#1 y 0), y debia armar una lista conteniendo 8 bits por elementos (1 byte). Por ejemplo, si se incova la
#funcion con el siguiente texto como parámetro:
#"1001010101000101010101100101001010101010"
#la funcion devuelv... |
bb960cf058870add1ff9e03a1e01b728a10e9a21 | igormartins1/Python-Projetos | /Exercicios Python/Python-Antigos/solução de polinomial 2 grau.py | 508 | 3.765625 | 4 | from sympy import symbol,solve
def calcula_f(x):
return x**2 -4*x+3
#definir x como uma variavel
x=symbol('x')
# resolver equação calcula_f=0
resultado=solve(y)
print 'x=',resultado
########################################################
# equação do segundo grau (raizes não reais)
from symp import symbol,... |
9bbd5f308212d29dd182b7bdbb13241124d9fbbf | Zahidsqldba07/Talentio | /Day-2/climb the stairs in a unique way.py | 831 | 3.75 | 4 | Question No: 4
Coding Type Question
You live on the first floor, the way to the first floor is only through the
stairs, there are exactly N stairs. You having long legs, can either step on
the next stair, or skip it. You obviously start at the ground, below the first
stair.
One day, your friend challenges you, how m... |
71b2e58bda5c06a54f9c14900a58ef1b942e1b65 | andriiburka/Web-Development-with-Python | /course2_python_fundamentals/05-Lists-Advanced/tmp/1E_Which_are_in.py | 119 | 4.09375 | 4 |
words_list = input().split(', ')
words_string = input()
print([word for word in words_list if word in words_string])
|
53a58a003b841c4497dc06f9cd6feddd8f755c5a | maxguy2001/countdown-numbers-game | /countdown solver.py | 6,570 | 4 | 4 | import numpy as np
from itertools import product
from itertools import permutations
def choose_nums(big, small):
"""
This function takes 2 inputs (number of big number and number of small
numbers) and returns a list of appropriate randomized inetegers
"""
#test inputs
assert type(big) is int, "... |
bc273e6a1dc76b349dafeab77285cd76cf62241e | SimmonsChen/LeetCode | /牛客Top200/93.LRU.py | 1,266 | 3.59375 | 4 | # lru design
# @param operators int整型二维数组 the ops
# @param k int整型 the k
# @return int整型一维数组
#
class Solution:
def LRU(self, operators, k):
stack = []
kv = {}
res = []
for op in operators:
if op[0] == 1:
# 缓存未满
if len(stack) < k:
... |
cf72edca71b429b98af1c9f243b99b2d51016769 | lovehhf/LeetCode | /1089_复写零.py | 1,113 | 3.96875 | 4 | # -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。
注意:请不要在超过该数组长度的位置写入元素。
要求:请对输入的数组 就地 进行上述修改,不要从函数返回任何东西。
示例 1:
输入:[1,0,2,3,0,4,5,0]
输出:null
解释:调用函数后,输入的数组将被修改为:[1,0,0,2,3,0,0,4]
示例 2:
输入:[1,2,3]
输出:null
解释:调用函数后,输入的数组将被修改为:[1,2,3]
提示:
1 <= arr.length <= 10000
... |
4e0aaabcaf9fe880a0dd1fe0fdf64a2be1948f70 | dfarfel/QA_Learning_1 | /Set/Set_task_8.1.py | 318 | 3.59375 | 4 | set1=set()
set2=set()
set3=set()
set1={10,150,6,32,28}
set2={32,200,15,10,3}
set3=set1|set2
print(set3)
set3.pop()
print(set3)
print(f'Maximum- {max(set3)}\nMinimum- {min(set3)}\nLength- {len(set3)}')
set4=set3.copy()
for i in range(1000,5000,1500):
set4.add(i)
print(set4)
set1.clear()
set2.clear()
set3.clear()
|
6bdd185c7c21a89cc836fa42a3009b7d87539b0c | luigipacheco/circuitpythonexperiments | /fractalkoch.py | 1,347 | 3.5 | 4 | """
This test will initialize the display using displayio and draw a solid green
background, a smaller purple rectangle, and some yellow text.
"""
import time
import board
import displayio
import terminalio
from adafruit_display_text import label
import adafruit_imageload
from adafruit_gizmo import tft_gizmo
from adafr... |
b692ca583c3b790f2c6c63d749ee67cdc080481b | Ajithjaya/DataScienceProjects | /PythonBasics/ErrorsExecptions.py | 1,777 | 4 | 4 | # Compile time errors and run time errors
# Syntax Errors - missing a colon , : , did not declare a variable , etc..
# Errors detected during execution are called Execptions, they are not unconditionally fatal.
#print(10*(1/0))
#print(4 + spam*3)
#print('2' + 2)
# Handling Execptions
while True:
try:
x = ... |
df246551c44333f7cb38bf38cf3b89753fb594b9 | Sannidhi-17/Python-Automation-Scripts | /web-scrapper/web-scrapper.py | 3,085 | 3.859375 | 4 | # import these two modules bs4 for selecting HTML tags easily
from bs4 import BeautifulSoup
# requests module is easy to operate some people use urllib but I prefer this one because it is easy to use.
import requests
from selenium import webdriver
# I put here my own blog url ,you can change it.
url = "https://getpyth... |
8f1d21ed431ffc6b7e4afd4b24ce868b62049ecf | loot-gremlin/scrabble_hack | /word_find.py | 637 | 3.671875 | 4 | impot itertools
impor meth
possible = [
x == 0
word = inpt("6 letter string of letters to search for: ")
num = it(inut("Length of words you want to find from these letters: "))
word_url = 'http://www.greenteapress.com/thinkpython/code/words.txt'
word_file = urllib.request.urlopen(word_url)
deffindword(testword)
... |
c3a2df93f5ddfb345351f369f60472ef8ebf4bec | Aasthaengg/IBMdataset | /Python_codes/p02900/s910873147.py | 524 | 3.75 | 4 | #1は含まれない
def divisor(n):
i = 1
table = []
while i * i <= n:
if n%i == 0:
table.append(i)
table.append(n//i)
i += 1
table = set(table)
return table
def is_prime(n):
for i in range(2, n + 1):
if i * i > n:
break
if n % i == 0:
... |
d4e5103c1f55ee134071306fcb91249b99225573 | h-kanazawa/introduction-to-algorithms | /src/optimal_bst.py | 1,623 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from typing import List
def optimal_bst(p: List[float], q: List[float], n: int):
"""
15.5
Optimal Binary Search Tree
len(p) should be len(q)
sum(p) + sum(q) should be 1
returns 3 two-dimensional lists, `e`, `w`, and `root`
e[1 ... n + 1, 0 ... n]
w[1 ... n + ... |
87c124c8a78fea662761c6d9ab91c5f8a0c3f887 | rushilbh/ALL-CODE | /p100.py | 509 | 3.671875 | 4 | class ATM(object):
"""
blueprint for ATM
"""
def __init__(pin,card_no):
self.pin = pin
self.card_no=card_no
def start(self):
print("THIS IS HDFC BANK ")
input_1=input("Pls enter your card number:-")
def amount(self):
input_3=input("enter amount for transaction:-")
input_2=in... |
df22203e703bde660931bd8f4529ee304788f4f3 | woskoboy/aio | /decor/avg_class.py | 590 | 3.703125 | 4 | # class Saver:
# def __init__(self):
# self.a = 0
# self.b = 1
#
# def __call__(self, *args, **kwargs):
# self.a += 1
# self.b += 1
# print(self.__str__())
#
# def __repr__(self):
# return 'a: {} b: {}'.format(self.a, self.b)
#
# obj = Saver()
#
# obj()
# obj(... |
f7c8afbe77ff142f899aa9e05913394f5f2a17bf | payal6005/Byte_Academy_Phase_1 | /Phase - 1/Part Time/Week 3/5. MVC/MVC weather/Weather_Aditya/weather_controller.py | 1,052 | 3.609375 | 4 | import weather_view
import weather_model
def GetChoice():
'''Get choice from user:
N/n - New Search
Q/q - Quit '''
choice=input(weather_view.StartView())
# 1. weather_view.StartView()
if choice=='q' or choice== 'Q':
# 2. weather_view.EndView()
weather_view.EndView()
elif choice=='n' or choice=='N':
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.