blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
294a14bbae4410c0e7de6f126adcd062a4fa0b87 | Brunochavesg/Guanabara | /ex006.py | 176 | 3.953125 | 4 | n1 = int(input("Digite um numero: "))
print (f'O numero digitado foi: {n1} o dobro de {n1} é {n1*2} o triplo de {n1} é {n1*3} e a raiz quadrada de {n1} é {n1**(1/2):.2f}')
|
5b5cf85f74b45e96ddb3eb6d249525ccb3e70f96 | PratikThakkar0/MATH_2305_Final-Project | /uhd_weighted_graphs/functions/Initial_Graph.py | 1,048 | 4.03125 | 4 | import networkx as nx
print('')
print("-----------------PRIM'S ALGORITHIM----------------")
print('')
print('--------------------------------------------------')
print('')
print('The available graphs to select are G1, G2, or G3')
print('')
print("Initialize Prim's Algorithim below")
print('')
print('------------------... |
c7997340fef4396d55f430c1c55ca148f62b4f6f | yukti99/Computer-Graphics | /LAB-4/perspective.py | 4,371 | 3.984375 | 4 | # PARALLEL-ORTHOGRAPHIC PROJECTION ON AN ARBITRARY PLANE IN 3-D COORDINATE SYSTEM
from graphics import *
import numpy as np
from math import *
# draw the 3-D coordinate axis
def drawAxis(win):
xaxis=Line(Point(-500,0),Point(500,0))
yaxis=Line(Point(0,-500),Point(0,500))
zaxis=Line(Point(300,300),Point(-500,-50... |
45cca548dc60cc62036c8e69f54b785d534940fa | qwedsafgt/ex3.py | /ex00.py | 986 | 3.71875 | 4 | class CSV:
def __init__(self,filename,postfix,is_head):
self.filename=filename
self.postfix=postfix
self.is_head=is_head
def is_csv(self):
d=self.filename
b="csv"
if len(d and b )> 2:
return True
else:
return Flase
def i... |
210592aa34d35963b1c151a04f3264d1c5fc8ec3 | hadiyarajesh/LinearRegression-Samples | /SingleVariateLinearRegression.py | 2,186 | 3.765625 | 4 | import pandas as pd
import numpy as np
import seaborn as seaBorn
import matplotlib.pyplot as plot
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
# Load csv file into dataset
dataset = pd.read_csv("D://PYTHON/DATASETS/weather.c... |
b6a9b27955207810b5982b6bb0d206b7a781b25a | jyu001/New-Leetcode-Solution | /solved/347_top_k_frequent_elements.py | 867 | 3.828125 | 4 | '''
347. Top K Frequent Elements
DescriptionHintsSubmissionsDiscussSolution
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity m... |
2fb09efeb5609775cb51b801c1c222ba03d61816 | ChaoMneg/Offer-python3 | /字符串/String_Permutation.py | 1,019 | 3.734375 | 4 | # -*- coding:utf-8 -*-
"""
题目:字符串的排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
思路:
1、求第一个位置的字符
2、固定第一个字符,求后边所有字符的排列
"""
class Solution:
def Permutation(self, ss):
if len(ss) <= 1:
return ss
res = set()
# 遍历字符串,固定第一个元素,第一个元素可以取a,b,c..... |
10498ee80c11b6d8c53e0f06c3d33320ff134b82 | abhisheksingh24/random_codes_i_ever_wrote | /Base Change.py | 799 | 3.890625 | 4 | alpha = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#initializing dictionary as empty
val = {}
def repToDecimal(num, base):
#following loop fills in the value for each digit
for i in range(base):
val[alpha[i]] = i
# m here is pow(base, i)
# to avoid raising to power each time
# we m... |
b5ed2f39018616070250e9e6b5565bfcc32627d4 | thephong45/student-practices | /7_Pham_Hoang_Trung/Bai1.3.py | 149 | 4 | 4 |
Bob = input("Nhap vao ten Bob: ")
Alice = input("nhap vao ten Alice:")
if(Bob=="Bob" or Alice == "Alice"):
print("Chao Bob va Alice")
|
aaa147b552683f56ffb3cc7f8624648d005cf794 | bmihovski/soft_uni_python_adv | /polymorphism_lab/instruments_2.py | 552 | 3.71875 | 4 | class Guitar:
def play(self):
return "playing the guitar"
class Piano:
def play(self):
return "pianoto"
def play_instrument(obj: object):
return obj.play()
from unittest import TestCase
class InstrumentsTests(TestCase):
def test_guitar(self):
guitar: Guitar = Guitar()
... |
36a1b326b865a92756c44f9924228b43061d3340 | emrehaskilic/pyt4585 | /introduction/odev1.py/odev1.py | 4,698 | 3.625 | 4 | print("""
*****************
*TELEFON REHBERİ*
*****************
------------------------------
- Kayıt Eklemek İçin : 1 -
- Kayıt Güncellemek İçin: 2 -
- Kayıt Listelemek için : 3 -
- Kayıt Aramak için : 4 -
- Kayıt Silmek için : 5 -
------------------------------
Tuşlayınız...
""")
rehber = [
... |
895bc8301266de7e094ca1c1fd3b4aa8a7d32d3f | tee24/LeetcodeProblems | /Jul 2020/11.07.2020 - 78. Subsets.py | 1,133 | 3.8125 | 4 | def subsets(nums):
output = [[]]
print(output)
for i in nums:
output+=[subset+[i] for subset in output]
return output
# Space, Time: O(N*2^N)
def subsets(nums):
powerset = []
for i in range((2**len(nums))):
subset_repr = bin(i)[2:].zfill(len(nums))
subset = []
fo... |
582f773c72b4e857b96b4d416bfcf02159b88d2c | ramakrishnasonakam/Codewars-kata | /2sumII.py | 303 | 3.546875 | 4 | def twosum(arr, t):
arr = sorted(arr)
d = len(arr)
l=0
r=d-1
while l<r:
if arr[l]+arr[r]==t:
return (arr[l],arr[r])
elif arr[l]+arr[r] > t:
r-=1
else:
l+=1
arr = [1,2,3,4,5,6,7,7]
t = 8
print(twosum(arr, t))
|
1c594f1f365bd067e51bec7758b5c2452fe2b985 | t-yuhao/py | /基本语法/e1.py | 277 | 3.90625 | 4 | i = 5
print (i)
i = i + 1
print (i)
s = "This is a multi-line string.\
This is the second line."
print(s)
print('a', end=' ')
print('b')
print('{0:.3f}'.format(1.0/3))
print('{0:_^11}'.format('hello'))
print('{name} worte {book}'.format(name='TYH',book='A byte of python')) |
968fcdd45d4afa478257d0d6670f40afd8740128 | fhca/ProgramacionAvanzada_2018 | /ProgramaciónAvanzada2018/prueba_paradigmas.py | 382 | 3.65625 | 4 | __author__ = 'fhca'
# suma = 0
#
# for x in range(1, 101):
# suma = suma + x
#
# print("La suma es:", suma)
def sumatoria(a, b):
suma = 0
for x in range(a, b + 1):
suma = suma + x
print("La suma es:", suma)
# 20->30, 70->90, 110->300, 425->440, 12->900
sumatoria(20, 30)
sumatoria(70, 9... |
4e8ee0ebd00bad7e997302f565b0a1884a967258 | borisbolsh/PyFunTasks | /1.2_MostCommonCharacter.py | 494 | 3.875 | 4 | # s = input("Enter any string: ")
s = "Llorem ipsum dollor sit amet, consectetur adipiscing ellit. Nullla ut ellit iacullis, ulltricies diam sit ametll, consecteturll magnall. Integer sodallles hendreritly orcil, nec pulllvinar orci euismod well."
dect = {}
ans = ''
anscnt = 0
for now in s:
if now not in dect:
... |
a74953a77467630a1cfea273f54334c738b70550 | AlanTurist/quadratic_equation | /details_def.py | 1,404 | 3.984375 | 4 | def detail(a, b, c, D):
if b == 0 and c == 0:
print("\nFor finding the solutions of the equation we must resolve:")
print("\n\t",a,"x^2 = 0")
elif b == 0:
if (a > 0 and c > 0) or (a < 0 and c < 0):
print('\n\tThe equation has no solutions..')
else:
... |
c812a666e1f15dc6945b6a229638eb628ed5cfe7 | Rositsazz/HackBulgaria-Programming0 | /week2/Simple Algorithms/twin_prime.py | 1,146 | 4.125 | 4 | number = input("Enter number: ")
number = int(number)
def is_prime_number (n):
start = 2
is_prime = True
if n == 1:
is_prime = False
while start < n:
if n % start == 0:
is_prime = False
break
start = start + 1
return is_prime
if is_prime_number(nu... |
982c36d530f52c70d75dc5db09d47dcba57338ec | ciesielskiadam98/pp1 | /06-ClassesAndObjects/z14.py | 1,388 | 3.546875 | 4 | class TV():
def __init__(self):
self.is_on = False
self.channel_no = 1
self.channels = []
def on(self):
self.is_on = True
def off(self):
self.is_on = False
def show_status(self):
if self.is_on == True and self.channel_no <= len(self.channels... |
967c8e042a9055e9fe1973b60925d2c14b6ae66a | nvishwan/Price-Prediction-for-Used-Cars | /Price Prediction Model & Exploring Key Business Insights.py | 18,871 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Step-1 Reading and Understanding Data
# 1)Importing data using the pandas library
# 2)Understanding the structure of the data
# In[127]:
# !pip install numpy
# !pip install pandas
# !pip install matplotlib
# !pip install dataprep
# !pip install sklearn
# !pip install seabo... |
ea8ad9636da1a925264c55c553bc3070ec5b1f2a | ardaunal4/My_Python_Lessons | /classes.py | 1,401 | 4.0625 | 4 | import datetime
# class user:
# pass # passes line and that does nothing
# user1 = user() # object
# user1.first_name = "AHmet"
# user1.last_name = "Besr"
# print(user1.first_name)
# first_name = 'Arthur'
# second_name = 'Clark'
# user2 = user()
# user2.first_name, user2.second_name = first_name, second_name
# p... |
2790d78b07aed0ae98a159a11ac5ae5cbf7b76ce | vikingliu/alg | /classic/sqrt.py | 697 | 3.96875 | 4 | # coding=utf-8
e = 1e-15
def sqrt(n):
left = 0
right = n
cnt = 0
while True:
mid = (left + right) / 2.0
x = mid ** 2
delta = abs(n - x)
if delta < e:
break
if x > n:
right = mid
elif x == n:
break
else:
... |
48852a789d3ecebe67d46557f1f34df2bd29f13b | avinashn/programminginpython.com | /number_reverse.py | 341 | 4.1875 | 4 | __author__ = 'Avinash'
input_num = (input("Enter any number: "))
reverse = 0
try:
val = int(input_num)
while val > 0:
reminder = val % 10
reverse = (reverse * 10) + reminder
val //= 10
print('Reverse of given number is : ', reverse)
except ValueError:
print("That's not a valid n... |
45960acc8eff5c434b300e34996c8ea444560044 | Kepler-XX/Codeself_py | /kepler/demo/case1.py | 45,164 | 3.53125 | 4 | # 100到练习题
"""实例001:数字组合
题目 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
程序分析 遍历全部可能,把有重复的剃掉。"""
# 第一种方式
total = 0
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if ((i != j) and (j != k) and (k != i)):
print(i, j, k)
total ... |
d0a959c1b36da882c963cee35c1e591a55238c63 | QI1002/exampool | /Leetcode/271.py | 950 | 3.765625 | 4 |
#271. Encode and Decode Strings
def encode(s):
result = ""
count = 0
word = None
output = False
for c in s:
if (c == word):
count += 1
if (count < 256): continue
count,output = 255, True
else:
if (word != None): output = True
... |
d29a064a8e1ab46f25ae6acad5d0d7fd4e4e5f4f | vesteves33/cursoPython | /Exercicios/ex071.py | 634 | 3.71875 | 4 | print('='*30)
print('{:^30}'.format('BANCO VEC'))
print('='*30)
valor = int(input('Quanto quer sacar? '))
total = valor
cedula = 50
totalCedula = 0
while True:
if total >= cedula:
total -= cedula
totalCedula += 1
else:
if totalCedula > 0:
print(f'Total de {totalCedula} cedu... |
dda96b2e8de8f863bf25bea2bdfc365ab3a9f820 | clonedSemicolon/ComputerGraphics | /Drawing/Circle/Bresenham.py | 908 | 3.8125 | 4 | import PIL.ImageDraw as ID, PIL.Image as Image
def draw1(x1, y1):
draw.point((x1, y1), fill=(0, 255, 0))
def drawCircle(xc, yc, x, y):
draw1(xc + x, yc + y)
draw1(xc - x, yc + y)
draw1(xc + x, yc - y)
draw1(xc - x, yc - y)
draw1(xc + y, yc + x)
draw1(xc - y, yc + x)
draw1(xc + y, yc ... |
05d63bcd5f14d9d7702d11d357e54e2a48c64605 | nikan1996/LeetCode | /Algorithms/3. Longest Substring Without Repeating Characters.py | 2,073 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author:nikan(859905874@qq.com)
@file: 3. Longest Substring Without Repeating Characters.py
~~~~~~~~~~~
:license: MIT, see LICENSE for more details.
@time: 31/01/2018 3:35 PM
"""
"""
Given a string, find the length of the longest substring without rep... |
52497d37047f9a80da51d95c067fa951130eba6e | Miky9/Py-BasicSyntax | /NotCompleted/Grafy_1.py | 579 | 3.546875 | 4 | # Importujeme základní vykreslovací modul
import matplotlib.pyplot as plt
import matplotlib
# A samozřejmě numpy
import numpy as np
# Občas se hodí i matematika
import math
# Vytvoříme jednoduchá data
# (50 bodů rovnoměrně rozmístěných na úseku -1,5)
x = np.linspace(-1, 5, 8)
y = x ** 2
fig = plt.figure()
# U add... |
bebb24b9decb6114bed99defd8c628036535eae9 | raj13aug/Python-learning | /Course/7-classes/properties.py | 1,038 | 4.1875 | 4 | class Product:
def __init__(self, price):
self.set_price(price)
def get_price(self):
return self.__price
def set_price(self, value):
if value < 0:
raise ValueError("price cannot be negative")
self.__price = value
price = property(get_price, set_price)
# A ... |
0f34364276a0f66cb787462c912826809cb8d960 | Ali-2000-prog/Python_MySQL_Cashier_Proj | /PY-Mysql/Amysql.py | 3,855 | 3.578125 | 4 | import mysql.connector
mydb=mysql.connector.connect(
host="localhost",
user="root",
password="admin",
)
def createDatabase(db):
print(db)
mycursor=mydb.cursor()
sql="Create Database "+db
mycursor.execute(sql)
print("DataBase",db, "CREATED")
def DropDatabase(... |
37ec02bc42a4ccfb6c2700257304c79df4ba1a9f | BhagyashreeKarale/if-else | /dques1.py | 278 | 3.5625 | 4 | # Question 1
# In the further questions, you will see pre-written code.
# You have to debug the incorrect code and submit the correct code.
print ("We will learn debugging by removing all the errors from this python file.")
# Save the correct code in a new file and submit it. |
01d4464cb7c25e8e0baa8fea90a8eb11e691f852 | Kein-Cary/Tools | /normitems/nstep.py | 1,320 | 3.6875 | 4 | # this file use to calculate this type formulation: y = x!; y = x!!
import numpy as np
_all_ = ['n_step', 'n_n_step']
def n_step(x):
"""
x : the data will use to calculate x!, x can be a data, or an array
"""
x = x
try:
gama = np.zeros(len(x), dtype = np.float)
for k in range(len(... |
5c0ae4f27ab24fc9b22b2f5255d9124fe0523eb1 | ISPC2020/tscdprog2020_g2-tscdprog2020_g2 | /Banco_Jose/Clases/Cuenta.py | 1,629 | 3.90625 | 4 | class Cuenta:
@staticmethod
def menu_cuenta(cuenta):
opcion = None
while opcion != 5:
print("""
Opciones:
1. Depositar
2. Extraer
3. Consultar saldo
4. Constitucion de plazo fijo
5. Salir
... |
bb1aac41202c1ba8e4a6cc13813754477405ec41 | chenfancy/PAT_Python | /Chapter2/2-10.py | 228 | 3.78125 | 4 | lower,upper=input().split()
lower,upper=int(lower),int(upper)
if upper<lower:
print('Invalid.')
else:
print('fahr celsius')
for i in range(lower,upper+1,2):
print('{0}{1:>6.1f}'.format(i,5*(i-32)/9))
|
30827734d7cf45cc91ce5b5fdcd7da91ca1417cb | kuldeep27396/DataStructuresandAlgorithmsInPython | /com/kranthi/Algorithms/sorting/InsertionSort.py | 328 | 4.03125 | 4 |
def insertionSort(arr: list, size: int) -> list:
i, key, j = 0,0,0
for i in range(size):
key = arr[i]
j = i-1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j = j-1
arr[j+1] = key
return arr
arr = [2, 6, 3, 12, 56, 8]
print(insertionSort(arr, le... |
7b5f80ffabc8ef25b0ac34cf9110a1cd9838252c | msrocka/pslink | /pslink/backs.py | 852 | 3.5 | 4 | import csv
class ProductInfo(object):
"""Instances of this class describe a product in a background database."""
def __init__(self):
self.process_uuid = ''
self.process_name = ''
self.product_uuid = ''
self.product_name = ''
self.product_unit = ''
def read_products(f... |
a5f8f274c494de16e1e30da66bfb773b4b3e49cf | hscspring/The-DataStructure-and-Algorithms | /CodingInterview2/31_StackPushPopOrder/stack_push_pop_order.py | 1,830 | 4.125 | 4 | """
面试题 31:栈的压入、弹出序列
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是
否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列 1、2、3、4、
5 是某栈的压栈序列,序列 4、5、3、2、1 是该压栈序列对应的一个弹出序列,但
4、3、5、1、2 就不可能是该压栈序列的弹出序列。
"""
def is_pop_order(push_order: list, pop_order: list) -> bool:
"""
Whether the pop order is for the push order.
Parameters
---------... |
146ecd947f42b9276abc6291717848cb1075c8c2 | Xevion/exercism | /python/tournament/tournament.py | 1,379 | 3.625 | 4 | def tally(rows):
# Subcommand that adds teams if not yet added, and processes the result from them
def process(team, result):
if team not in teams.keys():
teams[team] = {'MP' : 0, 'W' : 0, 'D' : 0, 'L' : 0, 'P' : 0}
if result == 'win':
teams[team]['W'] += 1
te... |
47fcb516d28fc3f6740d33725d2ee7cefdc64c94 | dnvnxg/cse107-lab4 | /navigate2.py | 1,259 | 4.15625 | 4 | """
A program that takes movement commands and reflects those commands in Turtle
file: navigate2.py
author: Donovan Griego
Date: 9-15-2021
assignment: Lab 4
"""
import turtle
def main():
# grabs commands until "stop" is read
queue = ["start"]
while queue[len(queue) - 1] != "stop":
cmd = input(... |
0e5c47de1bb6fbd156d41d0b3b21b8ef6e32c51a | MuhammadAbbasi/DSA_Semester3 | /Assignments/Assignment 2/All questions/Q1.py | 319 | 4.34375 | 4 | '''Write a short Python function that takes a positive
integer n and returns the sum of the squares of
all the odd positive integers smaller than n.'''
def OddPowerSum(n):
t = 0
for a in range(n):
if a%2 != 0:
t = t + a*a
return t
print(OddPowerSum(12))
print(OddPowerSum(5))
|
9699b838abfa7e868e45cfe8eda441b89e3f90f1 | Famiha/Python-30DaysChallange- | /day2.py | 2,477 | 4.125 | 4 | # ## List #### (Ordered & Changeable )##
# name = ("Arman","John", "Kamal","John","Clair","Karen","Samantha","")
# # # print(f"Here is the list of the name and the position is given below:\n Goalkeeper is {name[0]} \n Wrestler is {name[1]} \n Cricketer is {name[2]}")
# # name.pop()
# # print(name)
# number = [ 10,... |
6bc8b334d4e1f5b30df281e8bf0e469b85f41337 | daniel-reich/turbo-robot | /tRHaoWNaHBJCYD5Nx_21.py | 721 | 3.96875 | 4 | """
Create a function that returns `True` if two strings share the same letter
pattern, and `False` otherwise.
### Examples
same_letter_pattern("ABAB", "CDCD") ➞ True
same_letter_pattern("ABCBA", "BCDCB") ➞ True
same_letter_pattern("FFGG", "CDCD") ➞ False
same_letter_pattern("FFFF", ... |
d57d910f9aab6a4df3a529764c57e1627e0f7beb | xiaoqiangcs/LeetCode | /Permutations Sequence.py | 1,303 | 3.578125 | 4 | class Solution(object):
"""
@param n: n
@param k: the k-th permutation
@return: a string, the k-th permutation
"""
def getPermutation(self, n, k):
sequence = [i for i in range(1, n + 1)]
index = 1
for _ in range(1, k):
i = 0
for i in range(n - 2, ... |
02d61d8ac5f1ee1187aafafb64d966a6462d81af | AravindVasudev/Machine-Learning-Playground | /DL/ANN/ann.py | 1,736 | 3.671875 | 4 | import numpy as np
class NeuralNetwork():
def __init__(self):
# seeding numpy
np.random.seed(42)
# Init random weights with values in the range -1 to 1 and mean 0
self.synaptic_weights = 2 * np.random.random((3, 1)) - 1
# activation function
def __sigmoid(self, X):
... |
5a03db1b796632182238a844f80a8136efe75ad9 | arunmohanan/python | /Practice/tests/TestFibanocciGenerator.py | 1,016 | 3.546875 | 4 | import unittest
from Util import Timer
from Exercise.Practice import FibanocciNumberGenerator
class FibanocciNumberGeneratorTests(unittest.TestCase):
expectedTenFibanocciNumbers = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
def testFibanocciNumberGenerator(self):
with Timer() as t:
... |
741c9c48457b97a6438579d91b5a1c92c37be489 | dticed/pythoncoursera | /week6/nim.py | 3,653 | 3.953125 | 4 | import sys
placar_computador = 0
placar_usuario = 0
def main():
partida()
def computador_escolhe_jogada(n,m):
global placar_computador
for i in range(1, m+1):
if ((n - (i + 1)) % (m + 1) == 0):
n = n - 1
if i > 1:
print("O computador tirou "... |
a211e39468487370a4af797818d362268726b207 | dorisserruto/pythonbasic | /leap_acumulator.py | 392 | 3.59375 | 4 | #!/usr/bin/python
import datetime
def getSumLeap():
sumLeaps = 0
today = datetime.date.today()
proposed_leaps = range(0,today.year,4)
for prop_leap in proposed_leaps:
if isLeap(prop_leap):
sumLeaps+= prop_leap
def isLeap(year):
if (year % 100 > 0): #no divisible
return True
elif (year % 400 > 0):
retu... |
2ffe7136e4bf83b6c62f53614f0967759cb996d9 | josdeivi90/Python_exercise | /fibonacci.py | 459 | 3.640625 | 4 | f_0 = 0
f_1 = 1
f_n = 0
print (f_0)
print (f_1)
while(f_n<50):
f_n = f_0 + f_1
if(f_n >=50):
break
print(f_n)
f_0,f_1 = f_1,f_n
'''def fib(n):
if n < 1:
return None
if n < 3:
return 1
elem1 = elem2 = 1
sum = 0
for i in range(3, n + 1):... |
857a3949347d405df8897c12a90542aeaae4c0b6 | yzl232/code_training | /mianJing111111/Google/Three coke machines. Each one has two values min & max, which means if you get coke from this machine it will load you a random volume in the range.py | 2,693 | 3.53125 | 4 | # encoding=utf-8
'''
Three coke machines. Each one has two values min & max, which means if you get coke from this machine it will load you a random volume in the range [min, max]. Given a cup size n and minimum soda volume m, show if it's possible to make it from these machines.
'''
# 和另一道coke的题目似乎不大一样。
#应当是用DFS
'''
A... |
75d82d4b9e1f126685e0a62b9e22d4d154d33c89 | adgarciaar/HackerRankInterviewPreparationExercises | /Warm-up Challenges/RepeatedString.py | 965 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 01:00:41 2020
@author: adgar
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the repeatedString function below.
def repeatedString(s, n):
ocurrences_first = 0
for i in range(0, len(s)):
if(s[i] == "a"):
... |
e4d61d9987b7381cca5709af3c86ae0cd3cb1f85 | EinarK2/einark2.github.io | /Forritun/Forritun 1/Verkefni 1/Skilaverkefni 1.py | 1,791 | 3.625 | 4 | #Höfundur Einar Karl Pétursson 27/08/2018
#Liður 1
print("#Liður 1")
nafn=input("Hvað heitir notandinn? ") #Forritið spyr notandann um nafn
#Útskrift
print("Velkominn í áfangann FOR1TÖ3AU",nafn+".","Þetta verður skemmtileg önn, ég hlakka til að læra forritun.")
#Liður 2
print("#Liður 2")
tala=float(input("Sláðu inn kom... |
ebf5601f9a3f56a47412797a3608648fdd0f6b18 | gabriellaec/desoft-analise-exercicios | /backup/user_286/ch158_2020_06_09_20_00_21_827161.py | 181 | 3.5 | 4 | contador = 0
with open('texto.txt', 'r') as arquivo:
conteudo = arquivo.read()
lista = conteudo.split()
for a in lista:
if a != ' ':
contador += 1
print(contador) |
d4e9dbba741fa0328b743d3ab15f4b540ca96b1f | yunchan312/assignment_2 | /calculator2.py | 912 | 3.5 | 4 | # -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
class Calculator:
def __init__(self):
self.Value = 0
self.memory = 0
def setValue(self, x):
self.Value = x
def getValue(self):
return self.Value
def add(self, x):
self.Value += x
def sub(self, x):... |
b6355c85911eec5e21920d6e9daa8346ab29ef03 | nirajkvinit/python-programming-exercises-1 | /Exercises/Exercise24.py | 353 | 3.78125 | 4 | # Making a game board
not_ok = 1
while not_ok:
try:
x = int(input("What size game board you want to draw: "))
not_ok = 0
except ValueError:
continue
v_cell = " --- "
h_cell = "| |"
b_width = v_cell * x
c_edge = h_cell * x
for i in range(x):
print(b_width)
... |
dd12fe3362ebf3ac40f24fa6f7cf36c04982750d | aeciovc/sda_python_ee4 | /SDAPythonBasics/strings.py | 893 | 4.15625 | 4 | # Prints the number of characters in the sequence
sentence = "Lorem ipsum dolor sit amet..."
amount = len(sentence)
print(amount) # Prints 29
hello = "Hello, World!"
amount_app = hello.count('o', 0, 8)
print(amount_app) # Prints 4
# List and strings
list_of_letters = ['A', 'E', 'C', 'I', 'O']
string_of_letters =... |
a8fe8424c4fbdc3c051d9e022daedf318f38cd0b | bgoonz/UsefulResourceRepo2.0 | /_OVERFLOW/Resource-Store/01_Questions/_Python/squarecube.py | 1,285 | 4 | 4 | # pre code
def square():
print(" ")
makeUse = raw_input("Square or Cube : ")
if makeUse.strip() == "Square":
print(" ")
user = int(raw_input("Enter number to get square : "))
square = user ** 2
print(" ")
print("Square of the number " + str(user) + " is " + str(squa... |
44fbad1122120bba3783a59e92d01a8329e35fd2 | sharmaatul9654/python-program | /greatest.py | 178 | 4.09375 | 4 | a=int(input('enter the number'))
b=int(input('enter b'))
c=int(input('enter c'))
d= 'a is greater' if a>b and a>c else 'b is greater' if b>a and b>c else 'c is greater'
print(d)
|
179784558ec7b24988745758080d993cedfbbe77 | sgmpy/TIL | /startcamp/day02/for_variable.py | 61 | 3.59375 | 4 | items = ['1','2','3']
for i in items:
print(i)
print(i) |
1fa120effad783358b862faa920ca9a8115a6665 | samzhengkangliu/flask-REST-api | /python-refresher/functions/lamda_functions.py | 433 | 4.03125 | 4 | def add(x, y):
return x + y
# Lambda version: Normally we don't give it a name
# if need a name just name it like: add = lambda
lambda x, y: x + y
def double(x):
return x*2
sequence = [1, 3, 5, 7]
# lambda version
doubled = [(lambda x: x * 2)(x) for x in sequence]
doubled = list(map(lambda x: x * 2, sequen... |
2b4d8810a897945cfdd89b30c2e9ce13cb2862be | ANh0r/LeetCode-Daily | /9.8 combine.py | 759 | 3.5625 | 4 | """
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
return list(itertools.combinations(range(1,n+1),k))
"""
from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if n < k or n < 1:
... |
3055413e03d6106999afdd6ceb6044a4c6ec52a0 | averycordle/csce204 | /exercises/mar16/smile_click.py | 1,048 | 3.90625 | 4 | #Author: Avery Cordle
import turtle
turtle.bgcolor("skyblue")
turtle.setup(575,575)
pen = turtle.Turtle()
pen.pensize(3)
pen.speed(.5)
pen.color("black")
pen.hideturtle()
smileRadius = 50
def draw_smiley(x,y):
draw_head(x,y)
draw_eye(x-smileRadius/3,y+smileRadius)
draw_eye(x+smileRadius... |
be036ffa504d69d0f54f25d31f50cc1bdc56414c | takumiw/AtCoder | /ABC058/B.py | 183 | 3.703125 | 4 | O = input()
E = input()
if len(O) > len(E):
for o, e in zip(O[:-1], E):
print(o + e, end='')
print(O[-1])
else:
for o, e in zip(O, E):
print(o + e, end='') |
c9b51fc98a07f3dac6ef52246f30f1a3b19ceeae | assassint2017/leetcode-algorithm | /Odd Even Linked List/Odd_Even_Linked_List.py | 921 | 4 | 4 | # Runtime: 48 ms, faster than 89.44% of Python3 online submissions for Odd Even Linked List.
# Memory Usage: 15.1 MB, less than 6.02% of Python3 online submissions for Odd Even Linked List.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.... |
b3f373d175a12838a8877b8e1943d09f585f4f27 | minhvip2001/pythonproject | /Week1_PyThonBasic/Beginner/Exercise10.py | 349 | 3.796875 | 4 | def mergeList(lis1, list2):
print("list1 =", list1)
print("list2 =", list2)
list3 = []
for i in list1:
if(i % 2 == 1):
list3.append(i)
for i in list2:
if(i % 2 == 0):
list3.append(i)
return list3
list1 = [10, 20, 23, 11, 17]
list2 = [13, 43, 24, 36, 12]
print("Result List ... |
15a35248faa38de93290f409d188b45e244c6a74 | shiki7/Atcoder | /ABC216/A.py | 133 | 3.671875 | 4 | S = input()
x, y = S.split('.')
if 0 <= int(y) <= 2:
print(x + '-')
elif 3 <= int(y) <= 6:
print(x)
else:
print(x + '+')
|
af7ced082e9912430bdeb0107fba281f0216f52e | dynotw/Leetcode-Lintcode | /LeetCode/28. Implement strStr().py | 942 | 3.96875 | 4 | # Question:
# Implement strStr().
# Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack, or return 0 when needle is empty.
"""The first of occurrence means the first index when needle occurs in haystack """
# Answer:
class Solution:
def strStr(self, haystack: ... |
d8d477bd49716f31d30aab52fadbee26578d7bf2 | kapitalistka/GBpythonLessons | /lesson4/ex2.py | 3,488 | 3.703125 | 4 | # Эти задачи необходимо решить используя регулярные выражения!
# Задача - 1
# Запросите у пользователя имя, фамилию, email. Теперь необходимо совершить проверки, имя и фамилия должны иметь заглавные первые буквы.
# email - не должен иметь заглавных букв и должен быть в формате: текст в нижнем регистре, допускается ниж... |
d27df5e4bb337705ebadf2b7623776030ebdeedc | joel-lim/Advent-Of-Code-2020 | /day12/main.py | 615 | 4.03125 | 4 | """
https://adventofcode.com/2020/day/12
"""
from ship import Ship, ShipWithWaypoint
FILE = 'input.txt'
def main():
ship1 = Ship()
ship2 = ShipWithWaypoint()
instructions = parse_input(FILE)
for instruction in instructions:
ship1.read(instruction)
ship2.read(instruction)
print(f'P... |
2aeb6382452f9d617d04330ede244bbd2c50c1cd | Cyber-code/Projet_python | /class/Transaction.py | 4,819 | 3.84375 | 4 | from Interaction import Interaction
from Merchant import Merchant
from Player import Player
class Transaction(Interaction):
""" Transaction class instantiate a transaction object where the player buy or objects with a merchant. """
def __init__(self, player, merchant):
Interaction.__init__(self,... |
47501fbfc8ced59d4360f2f8fbf8ae3b536ef1b6 | VamsikrishnaNallabothu/MITx-My-Python-Work | /ps4/ps4-3.py | 467 | 4 | 4 | def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
le... |
920e699260f6e2c1b6dd65a0684c25122bd1fd90 | Aasthaengg/IBMdataset | /Python_codes/p02627/s733988493.py | 75 | 3.796875 | 4 | x = input()
if x.islower():
print('a')
elif x.isupper():
print('A') |
b20c123c501c5dd466b69abddeb0329fde7fbc8c | Lightman-EL/Python-by-Example---Nikola-Lacey | /N1_The_Basics/006.py | 194 | 4.09375 | 4 | slides = int(input("With how many slides of pizza you started with? "))
eaten = int(input("\nHow many slides of pizza you have eaten? "))
print("\n", slides - eaten, " slides of pizza remain") |
b5b1eb7994cdbf8e6f4459a18e69e963aed37d09 | Anastasia-Cloud/LearnPython | /task16.py | 632 | 3.71875 | 4 | '''
Даны две строки S1 и S2 . Длины строк не превосходят 1000000. Найдите их наибольшую по длине общую подстроку.
'''
def fixSubstr(l,s1,s2):
m=set()
for i in range(len(s1)-l+1):
m.add(s1[i:i+l])
for i in range(len(s2)-l+1):
if s2[i:i+l] in m:
return s2[i:i+l]
def maxSubstr(s1,s2):
l=min(len(s... |
d9583966b08b2d65aee5069de21545afc534a3ac | seboldt/ListaDeExercicios | /EstruturaSequencial/03-Soma.py | 155 | 3.890625 | 4 | a = float(input('Informe o primeiro numero da soma \n'))
b = float(input('Informe o segundo nuemro da soma \n'))
soma = a + b
print(f'A soma é {soma}')
|
5a63859a428f009b3c1cd1b3d8676b3b93f7fbfc | sbeleidy/406-AlgoBOWL | /solver.py | 8,487 | 4.125 | 4 | import random, itertools, time
def getManhattan(pOne, pTwo):
"""
Returns the Manhattan Distance between two points
"""
return abs(pOne[0] - pTwo[0]) + abs(pOne[1] - pTwo[1]) + abs(pOne[2] - pTwo[2])
def getMaxManhattan(allPoints, indexes):
"""
Returns the maximum Manhattan Distance between ea... |
7fc07679580cdd91326abf25cde9078b0b1f0b91 | kakakeven/kaka-python-practice | /Day04/while_loop_guess.py | 453 | 3.625 | 4 | '''
猜数字游戏
@author: kakakeven
'''
import random
answer = random.randint(1, 100)
counter = 0
while True:
counter += 1
guess = int(input("请输入: "))
if guess > answer:
print("小一点!")
elif guess < answer:
print("大一点!")
else:
print("恭喜你,猜对了!")
break
print('你一共猜了 %d 次' % co... |
1429b157c040800f2045afe903cbe4e7b99c768d | acdlee/Interview-Prep | /ctci/chapters/chpt4/4_2.py | 1,134 | 3.890625 | 4 | #O(nlgn) to create a BST time
#O(n) storage since we're making n nodes
class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insertBST(node, val):
if not node:
return Node(val)
if val < node.val:
node.left = insertBST(node.left, val)
elif nod... |
48254bff1432603541f3c397d4861f5833a2e3ad | aojugg/leetcode | /21_MERGE_two_sorted_lists.py | 744 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p1=l1... |
3bfbd87a83570a274a2facb4a6741514f4e56385 | danielsan98/Curso-de-Python | /Clase python/Caracteres.py | 598 | 3.921875 | 4 | miCadena = input("Dame un a palabra:")
primeraL = miCadena[0]
ultimaL = miCadena[len(miCadena)-1]
print("\n")
print("La primera letra de tu cadena es:", primeraL)
print("\n")
print("La ultima letra de tu cadena es:", ultimaL)
print("\n")
print("La longitud de la cadena es:", len(miCadena))
print("\n")
... |
69e9899f189caf9f919fa24bf2ad03c6cdf144c7 | cauegonzalez/exerciciosCursoPythonUsp | /ordemInversa.py | 240 | 3.890625 | 4 |
lista = []
n = int(input('Digite um número (zero para parar): '))
while n != 0:
lista.append(n)
n = int(input('Digite um número (zero para parar): '))
i = len(lista)
while i > 0:
print(lista[i-1], end = ', ')
i = i - 1 |
08e4a844963910ad7f62052c1faf79beffe1d383 | Fjmr18/IPS | /CPeD/Labs/Lab2/fiboSeq.py | 586 | 3.859375 | 4 | # Computação Paralela e Distribuída 2020/2021
# Aluno: Fernando Ramalho 200290040 BS (BrightStart 2ª Edição)
# Aluno: Antonio Costa 200221097 (BrightStart 2ª Edição)
#############################################
import checkSys as check
print(check.get_processsor_info())
import random
def fibonacci(input):
a, b =... |
eca86d913763c8acba2df72ce6d6037b10f75fe7 | perjlieb/Freyja | /freyja/fastwalshtransform.py | 968 | 3.78125 | 4 | import numpy as np
def ispoweroftwo(num):
"""
Check if num is power of 2
"""
return num > 0 and ((num & (num - 1)) == 0)
def ceilpoweroftwo(num):
"""
Rounds num up to the next power of 2
"""
x = 1
while(x < num):
x *= 2
return x
def fastwalshtransform(x):
"""
... |
826cd2b8df8bcff04ec971f83320805a8bf0b12b | Nora-Wang/Leetcode_python3 | /Hash and Heap/lintcode_0526. Load Balancer.py | 2,922 | 3.5 | 4 | Implement a load balancer for web servers. It provide the following functionality:
Add a new server to the cluster => add(server_id).
Remove a bad server from the cluster => remove(server_id).
Pick a server in the cluster randomly with equal probability => pick().
At beginning, the cluster is empty. When pick() is cal... |
57a95e90a119bd0c7b17e3a4518140e16f28db6c | anubhav-shukla/Learnpyhton | /for_loop_string.py | 385 | 3.75 | 4 | # name="Anubhav"
# for i in range (len(name)):
# print(name[i])
# it is an old way you can use in javascript and other
# but in python is special
name='Anubhav'
for i in name:
print(i)
# easy way same output
# 1234 .....>1+2+3+4
num=input("enter any number: ")
total=0
for i in num:
total... |
0ce485f995805891079a654b8e1f8ada29470b5e | procendp/Code_Study | /Programmers/Python/LV1/짝수와 홀수.py | 147 | 3.8125 | 4 | def solution(num):
if num % 2 == 1:
return "Odd"
elif num % 2 == 0:
return "Even"
print(solution(3))
print(solution(4)) |
80c77efa08418414a6cf736146a1ef7c944b01fb | engrjepmanzanillo/hacker_rank_practice | /text_wrap.py | 237 | 3.5 | 4 | import textwrap
def wrap(string, max_width):
return textwrap.fill(string, width=max_width)
if __name__ == '__main__':
string, max_width = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ', int(4)
result = wrap(string, max_width)
print(result) |
5bc17fa9a3faaebfd8a0469d759e7f283ef9db1b | DamianNery/Tecnicas-De-Programacion | /5Mayo/23/err_01.py | 263 | 3.96875 | 4 | #!/usr/bin/env python3
# calcula el cuadrado
# de un nro.
try:
a = float(input("ingrese número: "))
except:
print("ingresá un número")
else:
print("El cuadrado de ",a," es ", a*a)
finally:
print("siempre pase lo que pase")
|
5a99466c375abf84746d37bc7b31094311827095 | ramyasutraye/python_programming-1 | /codekata/natural.py | 126 | 4.09375 | 4 | print("enter the value")
a=int(input())
sum=0
for b in range(a+1):
sum=sum+b
print("the output sum of natural no is",sum)
|
0da6748b43d74d94562e0aba546edc497632cdd1 | Immaannn2222/holbertonschool-higher_level_programming | /0x03-python-data_structures/7-add_tuple.py | 162 | 3.578125 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
tmp = tuple_a + (0, 0)
trd = tuple_b + (0, 0)
return ((tmp[0] + trd[0]), (tmp[1] + trd[1]))
|
fac967877520280a219047ad0d978eff9621619a | kileyneushul/python_stack | /_python/python_fundamentals/Week 1/functions_basic_I.py | 1,698 | 4.0625 | 4 | #1
def a():
return 5
print(a())
#Predictions: 5
#2
def a():
return 5
print(a() + a())
#Predictions: 10
#3
def a():
return 5
return 10
print(a())
#Predictions: 5
#4
def a():
return 5
print(10)
print(a())
#Predictions: 5
#5
def a():
print(5)
x=a()
print(x)
#Predictions: 5, undefined
... |
3cea76bf17a623c82d4a299902d7b6a47de4ed61 | saotuzi/tensorflow_study | /kerasJianDanXianXing.py | 1,939 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 15:43:11 2019
@author: 64054
"""
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
print('Data -----------')
#构建训练数据和测试数据 (100个点)
number=100
list_x = []
list_y = []
for i in range(number):
#返回... |
4d2aab22c792495e23e914524efb5b37b871be69 | brandonmburroughs/data_structures_and_algorithms | /1_algorithmic_toolbox/week6_dynamic_programming2/1_maximum_amount_of_gold/knapsack.py | 1,144 | 3.71875 | 4 | # Uses python3
import sys
def optimal_weight(W, w):
n_items = len(w)
optimal_weights = [[0 for _ in range(W + 1)] for _ in range(n_items + 1)]
for item_number in range(1, n_items + 1): # Loop through number of items
for current_weight in range(1, W + 1): # Loop through weights
# Get... |
58b3bea4c52180db9a45a9053cce1a56918857f0 | Nimger/LeetCode | /344.py | 287 | 3.78125 | 4 | # -*- coding:utf-8 -*-
# https://leetcode.com/problems/reverse-string/description/
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
if __name__ == '__main__':
solution = Solution()
print(solution.reverseString('hello')) |
15bdc1260b02f6947bd0290ebe0e9cf67073166e | toanrock/pythonpractice | /Automate The Boring Stuffs with Python/Chapter8/MadLibs.py | 455 | 3.890625 | 4 |
print('enter the adjective:')
adj1 = input()
print('enter the noun:')
noun1= input()
print('enter the verb:')
verb=input()
print('enter the noun:')
noun2 =input()
textfile = open('text.txt')
textcontent = textfile.read()
finalstring=textcontent.replace("ADJECTIVE",adj1).replace("NOUN",noun1,1).replace("VERB",verb).re... |
15cbbd83293fe583cfa30d0643060469bc07709d | forxhunter/ComputingIntro | /solutions/cs101_openjudge/12065_newton.py | 394 | 3.765625 | 4 | # Newton's method
def solve(function = "x**3-5*x**2+10*x-80", a=4.0):
# a = float(input())
def f(x):
return eval(function)
def df(x, dx):
return (f(x + dx) - f(x)) / dx
while abs(f(a)) > 1e-10:
if df(a, 1e-10) == 0:
a -= 1e-10
else:
a = a - f(... |
aa22935540055b6db41e64a2b5856355ad0716ab | namratapadmanabhan/15112termproject | /playerRulesCheck.py | 10,097 | 4.15625 | 4 | #The main purpose of this file and the classes within it is to check each move
#made by the person player with the Scrabble rules. For example, we make sure
#after each move, that the letters are in either the same row or column, that
#they are attached to each other, and that the letters
# actually make a word wh... |
3d44262bd522debe84d707e139443c893684bfa7 | techlib/kerator | /modules/keywords.py | 5,326 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from modules import utility
import os
def get_keywords(toc_xml_location):
"""
Gets keywords from XML TOC files by calling utility function send_ker_request and returning the responses.
:param toc_xml_location: path to the XML TOC file or ZIP file containing mu... |
5f93f5b23b3cdc4329d028a307d4b8f1463c3069 | poojaKarande13/ProgramingPractice | /python/LinkedList/reverseLL.py | 467 | 4.21875 | 4 | # Reverse Linked List
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse(head):
prv = None
curr = head
nxt = None
while curr:
nxt = curr.next
curr.next = prv
prv = curr
curr = nxt
return prv
head = Node(1)
head... |
a6581823a4ba01ea1816994d598c6d47f36b00a1 | kvsaijayanthkrishna/Python_Programming | /15_string_title.py | 435 | 4.1875 | 4 | #15. Write a Python program to capitalize
#first and last letters of each word of a given string.
string=input("enter a string\t:")
string_list=string.split()
length=0
new_string=""
for string in string_list:
length=len(string)
if(length==1):
new_string+=((string[0]).upper()+" ")
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.