blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fb29118b8e9297a336ec14c4af2aaea9e491cf12 | blogart/Python | /archivos externos/manejo_archivos.py | 1,745 | 3.65625 | 4 | #Primero que hay que hacer es importar el modulo io que nos permite manejar los archivos externos
from io import open #se está importando solo el método open
#argumentos(nombre del archivo, w de white para abrirlo en modo escritura )
archivo_texto=open("archivo.txt", "w") #se está creando un archivo desde aquí
frase=... |
dcbcee9ea8da62dffea2d0a316f0ed71dd91568f | PrakashPrabhu-M/pythonProgramsGuvi | /positionOfLast_1.py | 329 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 05:11:52 2019
@author: Hp
"""
'''
Print the position of first 1 from right to left, in binary representation of an Integer.
Sample Testcase :
INPUT
18
OUTPUT
2
'''
a="{:b}".format(int(input()))
print(a)
b=a[::-1]
i=b.index("1")+1
#print(len(a)-i)
... |
dbcc71d3785c5806c649906f4f2026094cae1cef | kldxz123/Leetcode | /31/nextPermutation.py | 775 | 3.5 | 4 | class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 1
while i > 0 and nums[i-1] >= nums[i]:
i -= 1
print(i)
if i == ... |
2554fbce7c3bc71399bf0e8efa7d564ab48a36dc | aceiii/advent-of-code-2016 | /day2b.py | 1,040 | 3.671875 | 4 | #!/usr/bin/env python
import sys
def add(p, m):
return (p[0] + m[0], p[1] + m[1])
def code_to_dir(code):
if code == "U":
return (0, -1)
elif code == "D":
return (0, 1)
elif code == "L":
return (-1, 0)
elif code == "R":
return (1, 0)
def solve_bathroom_code(line... |
e8b9d6c5f566b4b9f1d684e20382a1a4956a7c00 | shelcia/InterviewQuestionPython | /Patterns/rowNumberInvertedPyramid.py | 289 | 3.953125 | 4 | # Write a code to generate a half pyramid pattern using numbers.
# Sample Input :
# 5
# Sample Output :
# 5
# Sample Output :
# 55555
# 4444
# 333
# 22
# 1
N = int(input(''))
for index in range(0, N):
for secondIndex in range(0, N-index):
print(N-index, end='')
print('')
|
1e3a3062449379ff72220365c6b09ca71f63be8f | Hituls07/SampleCodes | /Stack_Queue.py | 2,429 | 4.21875 | 4 | """
Stacks, like the name suggests, follow the Last-in-First-Out (LIFO) principle.
As if stacking coins one on top of the other,
the last coin we put on the top is the one that is the first to be removed from the stack later
"""
class Stack:
def __init__(self):
self.stack = []
def push(self, element):... |
b494ea8a208f8367d03856455cabc076fd0ab8ef | Ayetony/python-parallel-training | /basic/consumer_producer.py | 1,697 | 3.703125 | 4 | import time
from threading import Thread, Condition
items = []
condition = Condition()
"""
Condition() instance
method ,condition.acquire - fetch the resource
condition.wait() jsut hold on ,wait
condition.notify() notify other threads.
condition.release() , let it go, you are finished.
"""
class Co... |
7b82ec4c8e2528bbae34ef09b02e8253958d575a | aled1027/real_gc | /main.py | 783 | 3.90625 | 4 |
from pprint import pprint
import csv
def csv_to_bits(fnin, fnout):
"""
fnin is filename of csv file to be read.
fnout is filename of txt file to be written to.
Takes data in csv file and prints bit representation to fnout
"""
def my_str(x):
# x is a binary representation
# r... |
1db19285714164a7b5a91f319ba6043e95155a85 | Jonathan-Challenger/PythonSkills | /Arrays/Validate subsequence.py | 356 | 3.53125 | 4 | array = [5, 1, 22, 25, 6, -1, 8, 10]
sequence = [1, 6, -1, 10]
def isValidSubsequence(arr1, seq):
arrInd = 0
seqInd = 0
while arrInd < len(arr1) and seqInd < len(seq):
if arr1[arrInd] == seq[seqInd]:
seqInd += 1
arrInd += 1
return seqInd == len(seq)
print(is... |
a050615f9895ab2c78e8ddb159be0ef9c828a105 | liushuai0606/Python_First | /ython-Py.py | 48 | 3.53125 | 4 | word = "Python"
print(word[1:]+'-'+word[0]+'y') |
464e811f22534fa21a739a416ff69a3ac2854c4c | JISU-JEONG/algorithm- | /20190826/coin.py | 420 | 3.71875 | 4 | coin = [1, 4, 6]
def coinChange(n, choice):
global Min
if sum(choice) > n or len(choice) >= Min:
return
if sum(choice) == n:
Min = min(Min, len(choice))
print(*choice)
return
else:
for i in range(2, -1, -1):
choice.append(coin[i])
coinCha... |
0057fcbabdb16014af391e87bb698a7c683b4c18 | Aasthaengg/IBMdataset | /Python_codes/p03068/s042941288.py | 233 | 3.734375 | 4 | # -*- coding: utf-8 -*-
#----------
N = int(input().strip())
S = input().strip()
K = int(input().strip())
#----------
new_S=""
for word in S:
if word != S[K-1]:
new_S += "*"
else:
new_S += word
print(new_S)
|
1436c86ca442afa8c42ecafcb78071d1e9ed8d79 | nguyenthetung1806/C4T_Mentor | /Exercise/Part 3.py | 1,789 | 3.96875 | 4 | import random
count_played = 0
if count_played == 0:
choice_taking = True
while choice_taking:
start_input = input('Start Game ???? (y/n)').lower()
if start_input in ['y', 'n']:
choice_taking = False
else:
print('command Invalid !!!')
if start_input == 'y':
... |
bfbe384a49e51269b3d1f07cab86f732201dd152 | pandeysaurabhofficial/Core-python | /Untitled4.py | 2,828 | 4 | 4 |
# coding: utf-8
# # Dictionaries in python
# In[1]:
#{key:value}pairs
# In[2]:
my_dict = {'Sam':25,'Bob':26,'John':29}
# In[3]:
my_dict
# In[4]:
#dict have to be enclosed in curly braces and key in '' and value after :
# In[6]:
my_dict = {'Sam':{'Age':25,'Weight':'55 kg'},
'Bob':{'Age':26... |
9712c924165bccd83592e21f82804e75e3b26bd0 | bastolatanuja/lab1 | /lab exercise/question number 8.py | 229 | 4.5 | 4 | #write a python program which accepts the radius of a circle from the user and compute the area.
# (area of circle=pi*r**2)
radius=int(input("enter the radius: "))
pi=3.14
area=pi*(radius**2)
print(f"the area of circle is{area}") |
5d509e583c2e77823549d9f03e160dcebd8de9d1 | deepdhar/Python-Programs | /Functions/reverse_num.py | 237 | 4 | 4 | #reverse of a number
import math
def reverse_num(n):
d=int(math.log10(n))
if n<10:
return n
else:
return (n%10*math.pow(10,d) + reverse_num(n//10))
num = int(input())
print("Reverse:", int(reverse_num(num))) |
ef59c442daedc9de83b4f9a4f82c519fd1e71043 | irma1991/database_homework | /database/database.py | 7,721 | 3.890625 | 4 | import sqlite3
from book import book
from book import publisher
import pprint
def create_books(book):
connection = sqlite3.connect("books.db")
cursor = connection.cursor()
sql_query_not_injectable = "INSERT into books VALUES (?, ?, ?, ?, ?)"
query_values = (book.book_title, book.author, book.publish_d... |
d88d7ba92f7394818b8c7531bc86e26adbcb5759 | fabixneytor/Utp | /ciclo 1/Ejercicios Python/captcha.py | 545 | 3.546875 | 4 | from os import system
import random
system("cls")
longitud: int = 5
abedecedario:str = '1234567890abcdefghijklmnñopqrstuvxyz'
# elije aleatoriamente 5 elementos del abecedario
desordenar: list = random.sample(abedecedario, longitud)
#join crea cadenas a partir de objetos iterables
palabra: str = ''.join(d... |
80da67271ab1001467171c3788c62502f9b51a25 | jaykhopale/cs-interview-questions | /src/main/python/projecteuler/problem052.py | 1,052 | 3.671875 | 4 | #!/usr/bin/python
"""
Permuted multiples
Problem 52
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
"""
def samedigits(n, m):
length = (len(s... |
f2af49da2e43d5bdc7915b13583411c0424fe317 | V47VANSH/Hacktober-Challenges | /Collatz/collatz.py | 240 | 4.1875 | 4 | num = int(input("Enter a number: "))
while(num != 1):
if((num % 2) == 0): # even number = divide by 2
num /= 2
else: # odd number = multiply by 3 and add 1
num = num * 3 + 1
print(int(num))
print('Done!')
|
4357057586a6c251f59740ad21919361a97ac269 | agucadiz/pro | /python/proyectos/duelo/cartas.py | 955 | 3.859375 | 4 | """
# Cartas.
- Las cartas son 4:
- 0. Gran Éxito: + 2 de vida.
- 1. Éxito: + 1 de vida.
- 2. Fracaso: - 1 de vida.
- 3. Gran Fracaso: - 2 de vida.
"""
# ¿Traerme funciones del repartidor aquí?
from random import shuffle as mezclar
GE,E, F, GF = range(4)
baraja = [GE, # = 0
E, # = 1
... |
a66ced46ec1351bdd150ece2201f46cb76f40c4d | QFD-Felix/Arduino-Route-Finder | /route finder/dummy_server/server.py | 6,581 | 3.53125 | 4 | ''' # Name: Adit Hasan Student ID: 1459800
# Name: QIUFENG DU Student ID: 1439484
With MinHeap and AdjacencyGraph in the same directory,
this script can be run from the command line with the
command: python3 server.py. The server can be interacted
with sending requests in the format
R <coordina... |
aac94f03b007d5ba2de28dfe4b2ad83423889793 | dyshko/examples | /Rent Data Model/src/utils.py | 683 | 3.578125 | 4 | import calendar
import datetime
from dateutil import relativedelta
def str_to_date(s):
if s == "":
return None
return datetime.datetime.strptime(s, "%Y-%m-%d").date()
def read_csv(filename):
with open(filename) as f:
return f.readlines()[1:] # omit header
def months_between(date1, da... |
f6a7d192285a72b214ca00a82deae8d5535b430c | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/arc070/A/3684351.py | 139 | 3.671875 | 4 | x = int(input())
import math
huga = int((-1 + math.sqrt(1+8*x))/2)
if huga*(huga+1) == 2*x:
print(huga)
else:
print(huga+1) |
53911fbd302ab182fef73aedbeb05f171b3a75de | dsqrt4/itfvalidator-python | /pyitf/check_digit.py | 523 | 4.09375 | 4 | import pyitf.internal as internal
def calculate_check_digit(code: int) -> int:
"""Calculates and returns the check digit for the given code."""
digits = internal.digits(code)
sum_digits = 0
for i, n in enumerate(digits):
sum_digits += n if (i+1) % 2 == 0 else n*3
mod10 = sum_digits % 10
... |
0c534f378b3a31e09c3095cbb3757bf458de25b8 | AayushRajput98/PythonML | /Class/June6/String.py | 277 | 4.125 | 4 | x="Welcome To Noida"
print(x[::-1])
print(x.isupper())
print(x.islower())
print(x.istitle())
print(x.capitalize())
print(x.upper())
print(x.count("o"))
print(x.index("Welcome")) #Index of a substring
print(x.replace(" ","_"))
print(x.isidentifier()) #No space should be present |
f34f42713c01d811472997a80f82d7ee02061d36 | scottpeterman/clearpass-api | /general_scripts/time_epoch.py | 1,391 | 4.03125 | 4 | #!/usr/bin/env python3
#------------------------------------------------------------------------------
#
# Script to "play" with time structures
#
#------------------------------------------------------------------------------
import time
import datetime
print("Time in seconds since the epoch: %s" %time.time())
print... |
9ab897fa6545951043f063c031ddccea89e59675 | sakurasakura1996/Leetcode | /单调栈/problem84_柱状图中最大的矩形.py | 1,357 | 3.796875 | 4 | """
84. 柱状图中最大的矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。
图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。
示例:
输入: [2,1,5,6,2,3]
输出: 10
"""
# 题解中使用的是单调栈的思想
from typing import List
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
... |
24d74e825423a489de2501cb9d0724e8c32afa75 | Albatrossiun/SVM_digital-recognition_Code_py | /my_queue.py | 914 | 4.09375 | 4 | '''
#增删查
def push(queue, num):
queue.append(num)
return queue
def pop(queue):
queue = queue[1:]
return queue
def front(queue):
return queue[0]
'''
# 类
class MyQueue:
# 构造函数
def __init__(self):
self.q = []
#print("这是构造函数")
def push(self,num):
self.q.append(num)... |
49b05e97fc3d05284b4c3cbb7bcf66c3a9ec430f | Neal0408/LeetCode | /Algorithm/String/#168.py | 499 | 3.640625 | 4 | # 168.Excel表列名称
# 给你一个整数columnNumber,返回它在 Excel 表中相对应的列名称。
# 解题思路
# 1.26为一个进制,进制转换为字母。
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
ans = list()
while columnNumber > 0:
a0 = (columnNumber - 1) % 26 + 1
ans.append(chr(a0 - 1 + ord('A')))
c... |
0dd9d42f78f0014f6a37b62b80a25181534181fb | TomsenTan/About_asyncio | /asyncio_test.py | 1,851 | 3.703125 | 4 | #Date:2018-12-10
#Author:Thomson
from threading import Thread,currentThread
import time
#阻塞检测,一个线程阻塞,另一个线程执行
def do_something(x):
time.sleep(x)
print(time.ctime())
thread1 = Thread(target=do_something,args=(1,))
thread2 = Thread(target=do_something,args=(2,))
thread3 = Thread(target=do_something,args=(3,))
t... |
33e8259bf2f94a3059dbbc5f1563bb5d063cc0ef | jversoza/p4a-spring-16-examples | /p4a-class22/scratch/abc.py | 817 | 3.828125 | 4 | class InfiniteAlphabet:
START, END = 65, 90
def __init__(self):
self.code_point = InfiniteAlphabet.START
def __iter__(self):
return self
def __next__(self):
letter = chr(self.code_point)
self.code_point += 1
if self.code_point > InfiniteAlphabet.END:
... |
65bc526da1d0bc38a775869c3b3e0811e3f81f06 | pradyumnkumarpandey/PythonAlgorithms | /LeetCode/0016_3sum_closest.py | 1,423 | 3.84375 | 4 | # Import necessary dependencies
import sys
class Solution:
def threeSumClosest(self, nums, target):
# Sort the array
nums.sort()
# Initialize closest sum
closest_sum = sys.maxsize
# Starting from the first element,fix the smallest number
# Implement the two pointers... |
96ef6364f8bc53a8389d93f60ca0361fd67c3ded | xiaoruiling/My-Memo | /Python/Hello.py | 2,793 | 3.5 | 4 |
##!/usr/bin/env python3
#
#name = input('Please enter you name ....\n')
#print('Hello', name)
#
#print('I\'m a girl')
#print(r'line1\nline2\nline3')
#
#print('''line1
#... line2
#... line3''')
#
#print(not (3 > 6 or 3 > 5))
#print(None)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#from tkinter import *
#import t... |
01c834965bf83f7c4bca7938034ff309698eaed6 | geethusk/faslulfarisa | /python_code/swap.py | 91 | 3.96875 | 4 | print("Before Swap:")
a=5
b=6
print (a,b)
print("After Swap:")
a=a+b
b=a-b
a=a-b
print(a,b) |
e4aa74b2ace15b6ed72e3e40634616f76f027c9c | jeffersonvital20/Faculdade | /InteligenciaArtificial/perceptron/perceptron.py | 2,791 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# aplicativo para verificar se o ser vivo eh quadrupede ou bipede
# quadrupede = 1, bipede = -1
# cao = [-1,-1,1,1] | resposta = 1
# gato = [1,1,1,1] | resposta = 1
# cavalo = [1,1,-1,1] | resposta = 1
# homem = [-1,-1,-1,1] | resposta = -1
# pesos (sinapses)
# w = [0,0]
... |
bb208cdd65154e0228ea9a722342e97f1002d977 | rakshithk10/protothon01 | /main.py | 747 | 3.9375 | 4 | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
def add(a,b):
return a+b
def sub(a,b):
return a-b
def multiply(a,b):
return a*b
def div(a,b):
return a/b
... |
f7321008c0478fed6fa496e73f379f8df68f1d33 | Roobanpriyanka/guvi-code-kata- | /palin.py | 223 | 4.09375 | 4 | x=int(input("enter the number:"))
temp=x
rev=0
while(x>0):
dig=x%10
rev=rev*10+dig
x=x//10
if(temp==rev):
print("the number is palindrome:")
else:
print("the number is not a palindrome:")
|
935a521afa739eef1fd7a0f41183d701be79bea8 | Cachemarra/ML_Pro | /Easy/1D_Histogram.py | 1,829 | 4.28125 | 4 | #%%
"""
A histogram represents the frequency distributionof data. The idea is to take
a list of values and make a tally of how many times each value occurs.
Given a 1D NumPy array, create a histogram of the data represented as a NumPy array
where the index represents the number and the value represents the count.
Not... |
283233c2b216cef655ef3de395cab3de6a2fd857 | anand84471/Python-for-Bioinfromatics-Oct-2021 | /day8/dictionary_functions.py | 572 | 3.921875 | 4 | seq_records={
"YC1":"ATAGATGATAAGA",
"YC2":"ATGTTATATATAT"
}
print(seq_records)
#adding new value to dict
seq_records["YC3"]="ATGATAGATAATA"
print(seq_records)
#getting all the keys
print(seq_records.keys())
#getting all the values
print(seq_records.values())
#getting length of dict
print(len(seq_record... |
ff1fdc757899946da657b84c9dd36cbcdcb69298 | GaoPeiRu/python-vs-code | /6-3.py | 143 | 3.65625 | 4 | n=int(input())
i=0
while 2**(i+1)<=n:
i+=1
print(i,2**i)
#x = int(input())
#n = 1
#while 2 ** n <= x:
#n += 1
#print(n - 1, 2 ** (n - 1)) |
8321c3b13a79bd692806e6ddd4cdd58d3df1dfd3 | LYblogs/python | /Python1808/第一阶段/day2-Python语法基础/Python/元祖语句.py | 376 | 4.34375 | 4 | # 创建一个空的元组
tuple1 = ()
print('tuple1 =',tuple1)
#创建带有元素的元组 (可以是不同类型的)
tuple2 = (1,2,3,'good',True)
print('tuple2 = ',tuple2)
#定义只有一个元素的元组
tuple3 = (1,)
print('tuple3 = ',tuple3)
#元组元素的访问
#格式: 元组名[下标]
tuple4 = (1,2,3,4,5)
print('tuple4[2] = ',tuple4[2])
#修改元组 |
aa15afa1a4e6436600a4bd7f58178053b7768bdb | gabrielleevaristo/algo-practice | /searching/jumpsearch.py | 888 | 3.96875 | 4 | # Time complexity: O(sqrt(n))
import math
def jumpSearch(arr,target):
# Get step size
step = math.sqrt(len(arr))
prev = 0
# Finds block where target is present (if present)
""" -1 is returned here when target is greater than
the last element in the array """
while arr[int(min(step,len(arr... |
0dbb2117c9998390c7058edb3d3564b5078913f5 | BasicProbability/PythonCode_Fall2015 | /src/week4_debugging_and_testing/distributions_solution.py | 4,125 | 4.15625 | 4 | '''
Created on Sep 19, 2015
@author: Philip Schulz
'''
from random import Random, shuffle
from math import factorial
class BinomialDistribution(object):
'''
This class implements the binomial distribution with parameters n and theta, where n
is the number i.i.d. random binary decisions and theta is the p... |
78a26a265a5f3283be50516249e44697453f77cc | milenaS92/HW070172 | /L05/python/chap7/excercise03.py | 386 | 4.09375 | 4 | # exercise 3 chap 7
def gradeOfQuiz(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
def main():
score = int(input("Please enter the score: "))
grade = gradeOfQ... |
7a2a8c2589b4a47dba283d4e3119d3b3b82dad09 | antoniobarbozaneto/Curso_Descubra-Python | /condicionais_start.py | 324 | 3.921875 | 4 | #
# Arquivo de exemplo das estruturas condicionais
#
def Condicionais():
x,y = 10, 100 #Declarando 2 variaveis e passando os valores diretos para ela.
if(x < y):
print("X é menor que Y")
elif( x == y): #elif é igual ao else if
print("X é igual a Y")
else:
print("X é maior que Y")
Condicionais() |
af55033e0c4c035a92bc9ea78aa54632da3de6a1 | bicknest/coding_interview_problems | /strings_and_arrays/merge_calendars/python/merge_calendars.py | 823 | 3.859375 | 4 | # Merge two calendars
# Input is a list of tuples where the first item in tuple is start time and second item is end time
def merge_calendars(calendar):
if len(calendar) < 2:
return calendar
def sort_calendar(event):
return event[0]
calendar.sort(key=sort_calendar)
update_index = 0... |
ef68695cffce198a6115b6afd14f0d7c2fe39156 | ItsSamarth/ds-python | /hrfindAngle.py | 237 | 3.9375 | 4 | import math
ab,bc = float(input()) , float(input())
#calculate hypotenus
hype = math.hypot(ab,bc)
#calculate required angle
angle = round(math.degrees(math.acos(bc/hype)))
#degree symbol
degree = chr(176)
print(angle,degree, sep='')
|
6d45203bc95d206c45489d2c8e5e49c890f2d9da | fsancho1985/Infinity_school | /Lógica de Programação/exercicio_5_aula_29-05.py | 186 | 3.953125 | 4 | def fatorial(n1):
resultado = 1
for i in range(1, n1+1):
resultado *= i
return resultado
numero = int(input("Digite um número: "))
print(fatorial(numero))
|
16f1d011b15eb6538b6efef8f0cb3949ba8b53de | Preksha1998/python | /functions/calculator.py | 815 | 3.90625 | 4 | def addition(x,y):
add = x + y
return add
def subtraction(c,d):
sub = c - d
return sub
def multiplication(e,f):
mul = e * f
return mul
def division(g,h):
div = g / h
return div
a = int(input("enter value :"))
b = int(input("enter value :"))
ch = 1
while ch != 0 :
print("\n1.Addition..")
print("... |
3936956c1b105c7fc2a081c5fedb08572862b6e2 | H1world/Pythonbasic | /isdemos.py | 4,567 | 3.921875 | 4 | # def demo(num1, num2):
# if num1 < num2:
# print('too small')
# return False
# elif num1 > num2:
# print('too big')
# return False
# else:
# print('BINGO')
# return True
# from random import randint
# num = randint(1,100)
# print ('Guess what I think?')
# bi... |
13ea27c0f0696c17d1c4ef9ff9b99dd952c96202 | daniela-mejia/Python-Net-idf19- | /PhythonAssig/5-06-19 Assigment7/coin.py | 664 | 4.0625 | 4 | #Write a program to make change for an amount of money from 0 through99 cents input by the user
#The output of the program should show the number of coins from each denomination used to make the change.
#Daniela Mejia
def main ():
coin = int(input('write the amount of money from 0 to 99 cents you n... |
1f7167a8cee49e292deb9e83d8f78def254edf98 | elijp616/CS-2340-Georgia-Tech-Objects-and-Design | /CS2340-62/app/entities.py | 11,409 | 3.5 | 4 | from enum import Enum
from app.ships import *
import random
import math
import json
class techLevel(Enum):
PREAG = 1
AGRICULTURE = 2
MEDIEVAL = 3
RENAISSANCE = 4
INDUSTRIAL = 5
MODERN = 6
FUTURISTIC = 7
def to_json(self):
data["name"] = self.name
... |
f9f71eaa0492e3e540d5a0b9e10f91e194bcffb9 | VINSHOT75/PythonPractice | /python/replace01.py | 230 | 3.71875 | 4 | a = int(input('enter a number'))
x=1
re=0
while a>0 :
x=a%10
if x==0:
x=1
elif x==1:
x=0
re = re*10 + x
a =a//10
rev = 0
while re>0 :
rev = int(re%10)
print(rev , end='')
re= re//10
|
608d8c55d009f0150a234fddf5a1d422dfe94fb4 | Queena805/100-Days-Python | /Day10/Calculator.py | 1,025 | 4.125 | 4 | #calculator
from replit import clear
from art import logo
#add
def add(n1,n2):
return n1 + n2
#subtract
def subtract(n1, n2):
return n1 - n2
#Multiply
def multiply(n1,n2):
return n1 * n2
#Divide
def devide(n1, n2):
return n1/n2
operations = {}
operations["+"] = add
operations["-"] = subtract
operations["*"... |
76804de0e98d9541ec681c140dd8512e754e71ab | taoranzhishang/Python_codes_for_learning | /study_code/class_code/26String_length_calc.py | 489 | 4.375 | 4 | def string_length_calc(str):
count = 0
for data in str:#遍历字符串,轮巡一次,计数器加1
count += 1
return count
def main():
string = input("Please enter a string:")
characters_count = string_length_calc(string)
print("The number of characters in this string are: %d" % characters_count if characters_c... |
cbe2cc69a1a32adc68300359ca5248866e449e2d | satishp962/40-example-python-scripts | /6.py | 617 | 3.90625 | 4 | num = int(input("Enter the no. of lines: "))
half = num // 2
for p in range(half):
print('*', end='')
for l in range(num):
print(' ', end='')
print('*')
for i in range(half):
for j in range(half - i):
if j==0:
print('*', end='')
else:
print(' ', end='... |
3abea0ab175f2255eeafb50c358d61826aef47f8 | tigju/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 1,629 | 4.0625 | 4 | class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:... |
1dd14904a9ac322bf76124f68c5196785e41dd2d | midasscheffers/room_game | /new/classes/player.py | 4,138 | 3.5625 | 4 | import random
class player:
def __init__(self):
self.name = ''
self.x = 1
self.y = 1
self.char = '@'
self.inventory = ["key"]
self.show_data = False
self.show_data_str = ""
self.score = 0
self.health = 100
self.use_functions = {"sword... |
94de54641eb2e9d115c0f8d481a2bfa8ba7732df | Jarvis1217/Python | /Python/24点.py | 737 | 3.53125 | 4 | import random
import itertools
# Give random number list
def Give_num():
li=[random.randint(1,9) for i in range(4)]
return li
# List to String
def st(num_list):
li=[str(i) for i in num_list]
return li
# 24 calculation
def calc_24(li):
result=[]
symbols=["+","-","*","/"]
f... |
051342987950075110463a40aaa5fa74bc90454f | donald-f-ferguson/GoTHW | /src/data_tables/BaseDataTable.py | 5,682 | 4.09375 | 4 |
# Import package to enable defining abstract classes in Python.
# Do not worry about understanding abstract base classes. This is just a class that defines
# some methods that subclasses must implement.
from abc import ABC, abstractmethod
class DataTableException(Exception):
"""
A simple class that maps unde... |
918d1aa43016f2cb3376023d39245d056b526fa6 | AmitBaanerjee/Data-Structures-Algo-Practise | /leetcode problems/868.py | 1,403 | 4 | 4 | # 868. Binary Gap
#
# Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.
#
# If there aren't two consecutive 1's, return 0.
#
# Example 1:
#
# Input: 22
# Output: 2
# Explanation:
# 22 in binary is 0b10110.
# In the binary representation of 22... |
72b377dffaecd314e6c5794d4b06701d8d8e84eb | JEONJinah/Shin | /inner.py | 1,885 | 3.5625 | 4 | # abs
print(-3, abs(-3), abs(3))
# ALL / ANY (AND / OR 유사한 동작)
list_a = [1, 2, 3, 0]
list_b = [1, 2, 3]
# False, True, ... 예상..값 작성하면 좋을 것 같습니다
print(all(list_a), all(list_b), any(list_a), any(list_b), any([0, "", []]))
# Chr 내장함수 해볼 것
# dir: 객체 또는 자료형에서 가지고 있느 내장함수의 목록을 반환
list_var = [1, 2, 3]
st... |
0eed54a44e46a5b540b6eadf882142856e641ad2 | wonjong-github/Python_algorithm | /leetcode/2.py | 1,185 | 3.8125 | 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 addTwoNumbers(self, l1: ListNode, l2: ListNode)->ListNode:
"""
:type l1: ListNode
:type l2: ListNode
:rty... |
e2a9ec536b2a85e7a6214d70eb2eed8fe3947e54 | amartyahatua/programpractice | /Ritu/IntersectionOfArray.py | 1,086 | 3.671875 | 4 | class Intersection:
def findUnion(self, array1, array2):
result = []
while(len(array1)>0 and len(array2)>0):
temp1 = array1[0]
temp2 = array2[0]
if(temp1 == temp2):
result.append(temp1)
array1.pop(0)
array2.pop(0)
... |
6aec88f8531ce166ff03af1717791aae9ac4b045 | shivapriya89/leetcode | /findComplement.py | 324 | 3.578125 | 4 | class Solution(object):
def findComplement(self, num):
num=format(num,'b')
s=''
for char in num:
if char=='1':
s+=('0')
if char=='0':
s+=('1')
return int(s,2)
if __name__=='__main__':
a=Solution()
print(a.findComplement... |
499ad7fff98a5a07b876507cbd64332d60691a64 | pasignature/holbertonschool-higher_level_programming | /0x08-python-more_classes/101-nqueens.py | 1,635 | 3.71875 | 4 | #!/usr/bin/python3
"""Module is to solve the N-Queens challenge problem"""
from sys import argv
def checkspot(board, r, c):
n = len(board) - 1
if board[r][c]:
return 0
for row in range(r):
if board[row][c]:
return 0
i = r
j = c
while i > 0 and j > 0:
i -= 1
... |
95e4c97ad349f487b243a5d497629ae983d2a226 | Reldan/python-generators-tutorial | /yieldex.py | 316 | 3.96875 | 4 | # yieldex.py example of yield, return in generator functions
def gy():
x = 2
y = 3
yield x, y, x+y
z = 12
yield z/x
print z/y
return
def main():
g = gy()
print g.next() # prints x, y, x+y
print g.next() # prints z/x
print g.next()
if __name__ == '__main__':
main()
|
ca1cff9db2d640c6c598f8cc711d478b8f6353e1 | lex-pan/Wave-1 | /compound_interest.py | 195 | 3.796875 | 4 | initialAmount = int(input())
year1 = initialAmount + initialAmount*0.04
print(round(year1, 2))
year2 = year1 + year1*0.04
print(round(year2, 2))
year3 = year2 + year2*0.04
print(round(year3, 2)) |
59031a3e9d30318fdb7899751e3c7f7ddf7caf0e | yenvth57/sector-detection | /sector-detection.py | 222 | 3.734375 | 4 | import csv
sector_name: str = input('Please input a sector name: ')
with open('input.csv', 'r') as sector:
r = csv.reader(sector)
for i in range(len(r)):
if sector_name in r[i][13]:
print(r[i])
|
2399a71da6a09a9ddf0a818a471214c49e73d0bb | avallonking/UCSD-iGEM_2014 | /Modeling/DEVICE_1.py | 1,147 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
@author: youbin
"""
def device_1(od, input, output, dt = 0.1):
''' This device is device_1''' ## Here is the discription of device
k1 = 0.3
k2 = 0.5
k3 = 0
input_1 = input - k1*od*input*dt
output_1 = output + (k2*input*od - k3*od)*dt
return (input_1, output_1)
... |
db8928f19afe6241b8c9939fa1b83c5d95a7fe44 | Afsarsoft/python | /17_01_02_class_intro.py | 934 | 3.90625 | 4 | # pyright: strict
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Why classes?
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Classes allow us to logically group our data and code (attributes and methods).
class Car:
pass # use pass for empty clas... |
8a54dbb1a1da9cf58b1b323773830e09ffdcd837 | schnneee/POOP0311 | /day3_demo7.py | 647 | 3.875 | 4 | a1 = True
a2 = False
print(a1 and a1, a1 or a2, a2 and a2, a2 or a2, not a1, not a2)
B = [True, False, None, 3.14, "Hello world", '打個中文', 500]
print("-- True and b ------------------")
# A and B 時,當A為true,B可為任何東西
for b in B:
print(a1 and b)
print("-- False and b ------------------")
# A and B 時,當A為false,B不管是啥都為f... |
679981690edc1b45cc8f256aaaf5b9b193577876 | TwoRavens/raven-metadata-service | /preprocess/raven_preprocess/msg_util.py | 541 | 3.53125 | 4 | """Convenience methods for printing to screen"""
import sys
def msg(user_msg):
"""Print"""
print(user_msg)
def dashes(char='-'):
"""Dashed line"""
msg(40*char)
def msgt(user_msg):
"""print message with dashed line before/after"""
dashes()
msg(user_msg)
dashes()
def msgn(user_msg)... |
5c071aae056f398e74224b3bb1459783827994a4 | fnqn/lphython27 | /def_enroll_001.py | 738 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
####define 一年级小学生注册####
####only name gender####
def enroll(name, gender):
print 'name:', name
print 'gender:', gender
enroll('Sarah','F')
####only name gender age city####
def enroll(name, gender, age=6, city='Beijing'):
print 'name: ', name
... |
5e68a0b14e5d9f47af2573bd90c6bea797cbb6f9 | phuwadonop/Python-Lab | /hms.py | 1,077 | 3.78125 | 4 | print("*** Converting hh.mm.ss to seconds ***")
lst_input = [int(e) for e in input("Enter hh mm ss : ").split()]
hh,mm,ss = lst_input
str_hh = str_mm = str_ss = ''
if hh < 0 or hh != int(hh) : print('hh(%d) is invalid!' %hh)
elif mm < 0 or mm > 59 or mm != int(mm) : print('mm(%d) is invalid!' %mm)
elif ss < 0 o... |
9e90d9111ca630267906aa6e7bd40bcb444363f6 | Zahirgeek/learning_python | /Functional_Programming/p1_1.py | 548 | 3.5 | 4 | # Decrator
# 任务:
# 对hello函数进行功能扩展,每次执行hello打印当前时间
import time
# 高阶函数,以函数作为参考
def printTime(f):
def wrapper(*args, **kwargs):
print("Time: ", time.ctime())
return f(*args, **kwargs)
return wrapper
@printTime
def hello():
print("Hello World")
hello()
# 上述对函数的装饰使用了系统定义的语法糖
# 下面开始手动执行下装饰器
# ... |
b9c1c5072033356297a4b92de09ffa47d9d9b7eb | Mike543/GB_python_homework_1 | /Lesson 2/homework2_5.py | 179 | 3.921875 | 4 | my_list = [7, 5, 3, 3, 2]
my_list.append(int(input('Введите натуральное целое число: ')))
new_list = sorted(my_list)
new_list.reverse()
print(new_list) |
66d17aa926e2097acc4ab854cc04c4b62fe8849b | gokou00/python_programming_challenges | /coderbyte/SymmetricMatrix.py | 298 | 3.828125 | 4 | # https://stackoverflow.com/questions/42908334/checking-if-a-matrix-is-symmetric-in-numpy
def SymmetricMatrix(strArr):
test1 = "".join(strArr)
test2 = test1.split("<>")
print(test2)
print(len(test2))
print(SymmetricMatrix(["1","0","1","<>","0","1","0","<>","1","0","1"]))
|
cdfac11934858e101e75e61738612c8bac2f5dc0 | klee2017/python-practice | /0918/lesson/try.py | 594 | 3.8125 | 4 | l = list('abcde')
d = dict(name='Lux', champion_type='Magician')
print('program start!')
try:
print('before l[5]')
d['Sona']
l[5]
print('after l[5]')
except IndexError:
print('l[5] exception!')
except KeyError:
print("d['Sona'] exception!")
print('program terminate')
while True:
try :
... |
51dad3bc056febf3e254cd6b3fb831252daa49eb | tony520/supervised-BiLSTM-CRF-ore | /new_tagging_schema/gen_new_tagging_schema.py | 3,535 | 3.578125 | 4 | """
Functions used to generate the new tagging schema sequence
"""
import pandas as pd
import numpy as np
"""
Convert a list to a string
"""
def list_to_string(in_list):
strg = ''
strg = ' '.join([str(elem) for elem in in_list])
return strg
"""
Compare whether the two sequences are same
"""
def compare_se... |
128f3d28de5374a56a714cf0e06314f27e092b09 | danny099/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 540 | 3.5 | 4 | #!/usr/bin/python3
"""cities by state"""
import MySQLdb
from sys import argv
if __name__ == "__main__":
user = argv[1]
passwd = argv[2]
db = argv[3]
conectDB = MySQLdb.connect(
host='localhost', user=user, passwd=passwd, db=db, port=3306)
cur = conectDB.cursor()
cur.execute("""SELECT ci... |
10725477597a928af475852546bcbadc81aa7dd5 | Katherinaxxx/leetcode | /134. 加油站.py | 2,129 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2020/11/18 8:25 PM
@Author : Catherinexxx
@Site : github.com/Katherinaxxx
@File : 134. 加油站.py
@Description: 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
来源... |
1678720786651826233b054af804d5b164d6edf7 | shreyasabharwal/Data-Structures-and-Algorithms | /LinkedList/160.IntersectionOfLinkedLists.py | 1,947 | 3.75 | 4 | '''160. Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no ... |
fa17e4dc73eec56c17f1247119c4e114e0fab2d3 | karthikshivaram24/Text-Summarization-of-Movie-Reviews | /code/RottenTomatoesScrapper.py | 10,446 | 3.65625 | 4 | """
This file contains the code to scrape rotten tomatoes for moview reviews as well as the corresponding links of the critic reviews.
It is the starting phase of our text summarization project.
"""
from newspaper import Article
import urllib # For url response
import bs4 # Beautiful Soup for html parsing
import... |
9dd3b56eddd4ffdbdfc90a15bc9a805a888dfa18 | ra1nfoll/summer-practice | /1День.А.9.СмвФуты.py | 405 | 3.734375 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
a = input('Введіть велbчену в сантиметрах: ')
D = float(a) * 0.39
F = D / 12
print('Дюйми: ' + str(D))
print('Фути' + str(F))
printTimeStamp('\nОсередько А... |
3735a95848e04a766ddd3c3925ed346d2052f964 | TanzinaRahman/PythonCode31 | /PythonProgram31.py | 142 | 3.96875 | 4 | # Series ; 2 + 4 + 6 +.... + n
n = int(input("Enter the last number : "))
sum = 0
for x in range(2, n+1, 2):
sum = sum + x
print(sum)
|
f62960ebf8085f1be6dc4666ff1a04bbf2fd8f51 | krolik1337/AoC2020 | /Day8/Day8.py | 1,398 | 3.515625 | 4 | #%%
#!=== PART 1 ===!#
input = open("input.txt", "r")
data = []
for line in input:
data += [line.strip().split()]
visited = [False for i in range(len(data))]
accumulator = 0
index = 0
while not visited[index]:
visited[index] = True
if data[index][0] == 'acc':
accumulator += int(data[index][1])
... |
4d59ca0a623613edb77665b6b2aa6af0354950fb | nicorendon02/primer-semestre | /Ejercicios python/ejerciciolista7.py | 269 | 3.671875 | 4 | nombres=["juan", "ana", "marcos", "carlos", "luis"]
cantidad=0
x=0
while x<len(nombres):
if len(nombres[x])>=5:
cantidad=cantidad+1
x=x+1
print("Todos los nombres son")
print(nombres)
print("Cantidad de nombres con 5 o mas caracteres")
print(cantidad)
|
02ca5e25e43b65a2bc387d9c4a44b7ff6fce3267 | RayElg/HackInstead2020 | /main.py | 9,078 | 3.640625 | 4 | #Brython things...
from browser import document
from browser.html import P, STRONG, A
import re
#The dictionaries
averages = {}
facts = {}
#METHODS USED FOR NUMERICAL FUNCTIONS
def parseAvgs(): #Populates averages dictionary from avgs.txt
with open('avgs.txt','r') as f:
for line in f:
lst = ... |
3ce4363716fd55be3a6ed216cf59dc91750723ac | KierstenPage/Intro-to-Programming-and-Problem-Solving | /Homework/hw5/kep394_hw5_q1.py | 387 | 4.1875 | 4 | inputString = input("Enter an odd length string: ")
midChrPosition = int(((len(inputString)+1)/2)-1)
if (len(inputString) % 2) != 0:
print("Middle character:", inputString[midChrPosition])
print("First half:", inputString[0:midChrPosition])
print("Second half:", inputString[midChrPosition+1:(len(inputString... |
fa3a223eb96303b80624bb6269795bbb3a232950 | lindan4/4441AssistiveDoor | /ProjectFiles/guiTester.py | 666 | 3.71875 | 4 | from Tkinter import *
def noButton():
print "you chose no"
root.destroy()
def yesButton():
print "you chose yes"
root.destroy()
root=Tk()
root.title("Are you sure?")
root.geometry("450x150+500+400")
unAuthorizedLabel= Label(root,text="This will destroy all your files and you won't be ... |
af028bb4bdbd1323364849196ab4ac072ae56aad | quarkgluant/boot-camp-python | /day02/ex00/ft_filter.py | 666 | 4 | 4 | #!/usr/bin/env python3
# -*-coding:utf-8 -*
def ft_filter(function_to_apply, list_of_inputs):
return [element for element in list_of_inputs if function_to_apply(element)]
if __name__ == '__main__':
my_numbers = [1, 2, 3, 4, 5]
results = list(filter(lambda x: x > 3, my_numbers))
ft_results = list(ft... |
3ce18b8be1db48f89f51a73de5e4b74e246f71ef | 14Praveen08/Python | /vowel_r_consonant.py | 160 | 4.09375 | 4 | character = input()
if character == 'a' or character =='e' or character =='i' or character =='o' or character =='u' :
print("Vowel")
else:
print("Consonant")
|
d1ecc7a2595d5f2270c4038edfcf1d9ee85c817a | ReneNyffenegger/about-python | /functions/return-tuple.py | 357 | 3.609375 | 4 | def F():
return 42, 99, -1
x, y, z = F()
print('x={}, y={}, z={}'.format(x, y, z))
#
# x=42, y=99, z=-1
t = F()
print('type(t) = {}'.format(type(t)))
#
# type(t) = <class 'tuple'>
print('t[0]={}, t[1]={}, t[2]={}'.format(t[0], t[1], t[2]))
#
# t[0]=42, t[1]=99, t[2]=-1
# (a, rest) = F() # --> ValueError: to... |
75f7211c3d1de994720033f6b4b54ef1f75ce782 | TomsenTan/Based-algorithm | /bubble_sort.py | 648 | 3.796875 | 4 | #-*-coding:utf8-*-
#冒泡排序
#算法要点:
#每次循环将相邻两个数进行比较,可以将最大的数冒泡到最后
#下一次循环就可以在range(len-i-1)即前一次冒泡比较次数基础上减一
#时间:o(n2) 空间:0(n)
#代码实现
import random
def bubble_sort(seq):
n = len(seq)
for i in range(n-1):
print(seq)
for j in range(n-i-1):
if seq[j]>seq[j+1]:
seq[j],seq[j+1] ... |
df249ca6f66f1647952336b627ce49838b774788 | Macielyoung/LeetCode | /168. Excel Sheet Column Title/convertTotitle.py | 396 | 3.6875 | 4 | #-*- coding: UTF-8 -*-
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
s = ''
while(n > 0):
r = (n-1) % 26
s += chr(r+65)
n = (n-1) // 26
return s[::-1]
if __name__ == '__main__':
... |
eb76b037fd837c3c3f340c6b7042d657d61e14ec | JacobHelm36/GITtesting | /Journey_Quest.py | 6,956 | 3.921875 | 4 | import random
import re
import string
class Dice:
def __init__(self, size, numb):
self.size_of_dice = size
self.number_dice = numb
def roll(self):
results = []
for i in range(self.number_dice):
results.append(random.randint(1, self.size_of_dice))
print(resul... |
a9cdc7d4e26a4041d4eddb8527c31edea9043121 | niufenjujuexianhua/Leetcode | /[752]Open the Lock.py | 3,147 | 4.0625 | 4 | # You have a lock in front of you with 4 circular wheels. Each wheel has 10 slot
# s: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freel
# y and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each
# move consists of turning one wheel one slot.
#
# The lock initially... |
eba3ec7893ff6a08835a536516e44fee662635a6 | ivan-krukov/kipple | /group_known_genes.py | 593 | 3.609375 | 4 | #!/usr/bin/env python
"""
Given a list of C elegans genes, count each group
"""
import re
import sys
from operator import itemgetter
from collections import defaultdict, OrderedDict
gene_groups = defaultdict(int)
input_file = sys.argv[1]
name_pattern = re.compile(r"^(?P<class>\w+)\-\d")
for line in open(input_file)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.