blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
facda8d7d37112ff37dd7835e3469100156e166b | magicfoo/atonce | /atmake/tools/token.py | 880 | 3.59375 | 4 |
import shlex, io
def tokenize( line ) :
""" Returns a list of token from a string line
"""
parser = shlex.shlex( io.StringIO(line) )
tokens = []
while True :
tok = parser.get_token()
if not tok: break
tokens += [str(tok)]
return tokens
def mepize( line, tokens ) :
""" Returns "mise en page" informati... |
c2f312bc26c0b163170187f25c229c2920758c5e | bbnsdevelop/python_3_estudos | /python3/execptions/write_file.py | 323 | 3.53125 | 4 | #!/usr/bin/python
# coding: utf-8
def escreva():
try:
file = open('testeFile.txt', 'r')
file.write('Testandooo')
print('Gravou com sucesso')
except IOError as e:
print('Erro ao escrever no arquivo', e)
finally:
print('Fechando arquivo')
file.close()
escreva... |
12a55928554ed86317c36bd001666b0eae75b19b | lionelherrerobattista/practica_python | /01-python_crash_course/01-ejercicios_teoria/chapter_04_lists/4.11-my_pizzas_your_pizzas.py | 321 | 4.125 | 4 | pizzas = ["muzzarella", "napolitana", "calabresa"]
friends_pizzas = pizzas[:] #creo una copia
pizzas.append('marinara')
friends_pizzas.append('margherita')
print("Mis pizzas favoritas son:")
for pizza in pizzas:
print(pizza)
print("\nLas pizzas favoritas de mi amigo son:")
for pizza in friends_pizzas:
print(pizza)... |
e0e84b9379bcbd5aecd1e633f2efa75eccbdc7ae | khangnngo12/astr-119-section-2 | /check_in_solution.py | 415 | 4.21875 | 4 | def main():
i=0 #declare an integer 1
x=119.0 #declare a float x
for i in range(120): #make a loop that loop 0 through 119
if i%2 ==0: #if i is even
x+=3 #add three to x
else: #if i is odd
x-=5 #subtract five from x
s = "%3.2e" % x #make a string containing x
#with scientific notation and two deci... |
8b166d01078ee0826ab8c4895e755e7ad75b9e73 | FrancoVol/python-lab2 | /lab2ex1.py | 660 | 4.0625 | 4 | flag=True
tasks=[]
while flag==True:
print('''Choose one task:
[1. insert a new task
2. remove a task
3. show all existing tasks
4. close the program]''')
a=int(input())
if a==1:
print("Insert the task you want to add:")
tasks.append(input())
elif a==2:
print ("Insert the task... |
682a282499fb77ea36782595a778c1f34a810168 | songtaegeun/pytest | /test4.py | 102 | 3.75 | 4 | a = "x"
for k in range(5, 0, -1):
for i in range(0, k):
print(a, end="")
print("")
|
294cd99a6d96dc84b3225bcfc64be4a0afb981b8 | Septink/PythonDecimalToBinary | /Number Base Conversion.py | 272 | 3.625 | 4 | import os
def main():
os.system ("title Decimal To Binary")
os.system ("cls")
os.system ("color b")
fromNum = int(input("Number: "))
fromBase = int(input("From Base: "))
toBase = int(input("To Base: "))
print (str(convert(fromNum,)))
input ("Press Enter")
main() |
b64f87bd4414453858356bc65fea6e5c97807429 | macroscopicentric/practice | /6.00X/pay_debt.py | 472 | 3.734375 | 4 | balance = 3329
annualInterestRate = .2
def pay_min(a, b):
test_balance = balance
month = 0
total_paid = 0
payment = 0
while test_balance > 0:
payment += 10
month = 0
test_balance = balance
while month < 12:
month += 1
test_balance = (test_bala... |
5fb7a087933cb85bac90bbb762c6fc1a22b8a837 | MathPlayer/advent-of-code-solved | /2020/10.py | 1,041 | 3.6875 | 4 | #!/usr/bin/env python
import sys
def read(in_file):
''' Reads data for day 10. '''
with open(in_file) as f:
data = tuple(map(lambda x: int(x.strip()), f.readlines()))
return data
def solve(in_file):
''' Solves day 10. '''
print(in_file)
data = read(in_file)
elements = sorted(data... |
6d0303b6a5f1d6b317a1837a3a3ea8424c12dc34 | sky-dream/LeetCodeProblemsStudy | /[0136][Easy][Single_Number][Bit_HashTable]/Single_Number.py | 378 | 3.5625 | 4 | # solution 1, bit manipulation, xor
# leetcode time cost : 32 ms
# leetcode memory cost : 15.3 MB
# Time Complexity: O(N)
# Space Complexity: O(1)
# a^0 = a, a^a = 0, a ^ b ^ c = a ^ c ^ b,
class Solution:
def singleNumber(self, nums: List[int]) -> int:
single_number = 0
for num in nums:
... |
c511d0437c2af15c929038d3a93dfe9191887741 | girishbarca/revup_legacy | /core/revup/core/Utils/sim_measures.py | 2,666 | 3.65625 | 4 | """
Collection of
"""
import re
import math
from collections import Counter
import numpy as np
WORD = re.compile(r'\w+')
def sentences_intersection(sent1, sent2):
"""
Calculate the intersection between 2 sentences
"""
# split the sentence into words/tokens
set1 = set(sent1.split(" "))
set2 =... |
660e7d186b986e67d8957f32bb0f17b2655d82bd | z1223343/Leetcode-Exercise | /105_445_AddTwoNumbersII.py | 795 | 3.75 | 4 | """
1 level solution:
1. convert to number and then create new listnode
"""
# solution 1: # 没有按照Leetcode solution,但我感觉这个解法更棒
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self,... |
f0caa1d85548db5bb16278f7763cd8ed2fbd9523 | Angayarkkanni9/infytqprob | /practice_27.py | 190 | 3.921875 | 4 | def check_for_ten(num1,num2):
if(num1 ==10 or num2 ==10):
return True
elif num1+num2==10:
return True
else:
return False
print(check_for_ten(10,9))
|
b886e49db469b49c9713d6bcdbbd689e1a8124fe | Tomant1/Boozebot | /DrinkClass.py | 2,355 | 3.703125 | 4 | #This program defines the Drink class for the booze bot
#Programmers: TRG
#Iteration: 0.4
#Last edited: 10/04/2019
#Created: 10/04/2019
#imports the relevant libraries
import Data #imports the data file
#the drink class
class Drink:
#class variables
CupSize = 475 #the size of the cup(ml). Default ... |
9770ba63a1393541502f506084df9582f5b36404 | hdgmemory/Data-structures-and-algorithms | /二叉树/判断完全二叉树.py | 983 | 3.640625 | 4 | ###https://www.cnblogs.com/jiaxin359/p/9257960.html#_label7 二叉树
def is_complete_tree(head):
"""判断一个树是不是一个完全二叉树
主要考虑这么两种情况:
情况1:当前节点,有右节点,但是没有左节点,那么直接返回False
情况2:当前节点,有左节点没有右节点,或者没有双节点,那么后面的节点都应该没有双节点
"""
if head is None:
return True
is_last = False
queue = [head]
while(... |
446d17a56ba10df6dc5b6c8ebad871c943522775 | arnabs542/python_leetcode | /bitwise/is_power_of_3.py | 2,007 | 3.640625 | 4 | """
1 0b1
3 0b11
9 0b1001
27 0b11011
81 0b1010001
243 0b11110011
729 0b1011011001
3的幂的规律(自己瞎猜的)
1. 个位是1,3,9,7: n%3=0 or 1
2. 二进制最后一位是1: (n & -n) == 1
3. 二进制最高位是1: ?
获取从右边往左第一位非0 bit的索引位置的方法: math.log2(n&-n)+1
# 官方解答:
1. 转换为3进制后做正则
// Integer.toString(n, 3)表示将n转为3进制的字符串
// 字符串是否以1 ^1 开头,后跟 0 或 多... |
48facce027cc761f0835d3c808b9bdbdee43ca67 | fredtavares2018/estudando_python | /estudoVariaveis.py | 845 | 4.15625 | 4 | # tipos de variáveis
a = 2
b = 3.4
c = True
d = 8 + 7j
e = 'Teste'
# Para saber os tipos usamos type
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
# resposta do terminal
# <class 'int'> inteiro
# <class 'float'> decimal
# <class 'bool'> boleano
# <class 'complex'> complexo
# <class 's... |
d1f5997ec578ef6c4a2b5e574106c87df250769d | jovi-yang/workplace | /zuoye1.11.py | 316 | 3.734375 | 4 | # coding=utf-8
a = (1, 2, 3)
b = list(a)
b[0] = 5
c = tuple(b)
print("第一种输出:{0}\n".format(c))
b = list(a)
b.insert(1, 5)
del b[0]
c = tuple(b)
print("第二种输出:{0}\n".format(c))
bool1 = 2 in a
print(bool1)
a = set(['a', 'b', 'c'])
a.add('jay')
b = set(['b', 'e', 'f', 'g'])
c = a | b
print(c)
|
9621406487e89ebc1845929ecca4ee604ffdc28c | dzivaljic/alg_bio_inf | /1G.py | 309 | 3.71875 | 4 |
def hamming_distance(text1,text2):
br=0
for i in range(0,len(text1)):
if(text1[i]!=text2[i]):
br=br+1
return br
if __name__ == "__main__":
text1 = "GGGCCGTTGGT"
text2="GGACCGTTGAC"
res = hamming_distance(text1,text2)
print(res)
|
5e332b8cbbdb486281eac98fb91fda9cd5e0345e | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc034/B/4788617.py | 65 | 3.734375 | 4 | x = int(input())
if x%2 == 0:
print(x-1)
else:
print(x+1) |
57f97cc3a09a6693e9d3173f03d17325cfe38d5e | HalfMoonFatty/Interview-Questions | /506. Relative Ranks.py | 1,095 | 3.90625 | 4 | '''
Problem:
Given scores of N athletes, find their relative ranks and the men with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first thre... |
3507f4b3d0f33f1c66c675356dde5c90750d74a9 | yakun344/LeetCode_record | /Breadth First Search/210. Course Schedule II.py | 4,459 | 4.15625 | 4 | 题目:
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you shou... |
ee247b71130125baa5f05f0fafa6ddf3753e5211 | eban12/compettitive_programing-cs478- | /Competitive/Day14/constructBSTfromPreoreder.py | 596 | 3.828125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def bstFromPreorder(preorder: List[int]) -> TreeNode:
if len(preorder) == 0:
return None
left = []
right = []
r = preorder[0]
for i in preo... |
8deba2d88d764cd8583bddf4a6cab3ec9754ba83 | SayanDutta001/Competitive-Programming-Codes | /Codechef May CookOff 2020/CHEFSHIP.py | 273 | 3.609375 | 4 | def chefship(s):
count = 0
for i in range(1, len(s)-2, 2):
if(s[:(i+1)//2] == s[(i+1)//2:i+1]):
if(s[i+1: (len(s)+i+1)//2] == s[(len(s)+i+1)//2:]):
count+=1
return count
test = int(input())
for i in range(test):
s = input()
print(chefship(s))
|
88b504da1e4cdb8ad41e0222e5cfe7794c90a9c7 | helaisha/TOW-Sprocket-Central-Data | /spc_datapreproc.py | 2,930 | 3.5625 | 4 | # create age variable from DOB
def create_age(data=None):
""" To create age variable from DOB. """
data['age'] = data['DOB'].map(lambda x: x.year)
data['age'] = 2015 - data['age']
return data
# correct misspelled gender
def correct_misspelled_gender(data=None):
""" To correct misspelled gender v... |
c60bd76e1ea77bd9fbc8d4a082504324b11076cc | yashar-sb-sb/my-codeforces-submissions | /800-899/877/(31635855)[OK]A[ b'Alex and broken contest' ].py | 126 | 3.578125 | 4 | inp = input()
num = sum(inp.count(i) for i in {"Danil", "Olya", "Slava", "Ann", "Nikita"})
print("Yes" if num == 1 else "No")
|
fa078bf0fa491a51cae6b6836b12dff2ad64c4e6 | daniel-reich/ubiquitous-fiesta | /Z6kRGLpYgSuFQJ7Rx_22.py | 405 | 3.96875 | 4 |
def find_longest(sentence):
longest_word = ''
biggest_size = 0
words = sentence.split()
print(words)
for word in words:
if '\'' in word:
word = ''.join([i for i in list(word[:word.index('\'')])])
if '.' in word:
word = word.replace('.', '')
if len(word) > biggest_size:
... |
f3f507688fbfba079e98dbebfc0bd8668640a64b | JuliaYu2002/HunterDE | /Comp Sci 127 hw/timeConverter_jy.py | 402 | 4.34375 | 4 | #Name: Julia Yu
#Email: julia.yu83@myhunter.cuny.edu
#Date: September 6, 2019
#This program takes in a number of seconds and outputs it converted into a number of seconds, minutes and hours
time = int(input("Enter a number of seconds: "))
hours = time // 3600
print("Hours:", hours)
remain = time % 3600
... |
a3dfc1fe768df28a6da4054ce0479626ee66d98e | Thatsgaurav/niet-Python-Lab | /Problem Solving using Python Lab. Index/53.compute_the_factorial_function.py | 312 | 4.375 | 4 | # WAP to compute the factorial of the given number using user defined function
def factorial(num):
fact=1
for i in range(1, num+1):
fact=fact*i
return fact
num=int(input("Please enter any number to find factorial: "))
result=factorial(num)
print("The factorial of %d = %d"%(num,result)) |
9ebed73b4bfe38e2362fa10ce4af7b2e98bf4225 | damiansp/completePython | /pytut/open_closed.py | 710 | 3.96875 | 4 | from abc import ABC, abstractmethod
def main():
person = Person('Johnny D')
PersonDB().save(person)
PersonJSON().save(person)
class Person:
def __init__(self, name):
self.name = name
def __repr__(self):
return f'Person(name="{self.name}")'
# Goal: design such that when add... |
24aa978658a440c967c06c61b5159a41ec6ca673 | hi-andy/python-study | /fileRename.py | 539 | 3.6875 | 4 | #!/bin/python env
# 文件重命名程序
import os
import re
# 存放文件目录
file_dir = './mp3/'
# path = input('请输入文件路径:')
files = os.listdir(file_dir)
add_string = ''
for file in files:
if not os.path.isdir(file):
m = re.match(r'(.{2})(\d{3,}).*(\.mp3)$', file)
if str(m) != 'None':
newName = m.group(2... |
a5fe48972aea61c09710e898e0279ccea2847644 | martin-varbanov96/summer-2016 | /Pitonia/softuni/01/04.example.py | 151 | 4.125 | 4 | angle = int(input("Enter angle: "));
length = int(input("Enter length: "));
import turtle as t
while True:
t.left(angle)
t.forward(length)
angle+=1 |
cc80374cb826fd83d4b7ce9264c1a644c9f580e7 | Lopsy/smile.py | /examples.py | 1,548 | 3.546875 | 4 | from smile import emoticon, _
def testSmile():
import itertools
@emoticon("^_^") # This creates the operator ^_^ globally!
def smile(a, b):
return itertools.chain(a,b)
# Now ^_^ is an infix iterator chainer!!! ^_^
funIterator = [1,2,3] ^_^ xrange(10,20,5) ^_^ {"apple":1, "banana":4... |
5f8139dc53bd6e4bafa05ce8c9468f761da5af49 | sharmaachintya/Python | /DataTypes.py | 742 | 4.3125 | 4 | # data types help us store different type of data
# we will go over each of these
# ofcourse you can print them now we don't need to see them
# some basic data types include
# string
nick_name = "raufie"
city = 'lahore'
# numbers
age = 55
weight = 91.2
productivity_ratio = 0.97211
# group of similar data: arrays
weight... |
1bed94b91ac4f4d0e9b110aa854e02bd1dd59f3f | saruns/updates | /oct13-14/chapter11/exrsce.11.3.py | 255 | 3.75 | 4 | import sys
def sortdict(x):
d = dict()
for f in x:
if f not in d:
d[f] = 1
else:
d[f] = d[f] + 1
b = sorted(d.keys())
for w in b:
print w, d[w]
a = raw_input("Enter your string: ")
sortdict(a)
if __name__ == "__sortdict__":
sortdict(a)
|
e8e8129028b07ff37e45ef79343e1c3b66aa77ee | prathamtandon/g4gproblems | /Arrays/find_celebrity.py | 901 | 3.921875 | 4 | import unittest
"""
You are given a party of N people. There may be one person in the party who does not know anyone but is
known by everyone. Such a person is called celebrity. Your task is to find this person.
You will be given a square matrix M, where M[i][j] is 1 means ith person knows jth person. You need to write... |
c07dbd21bf052f414a385cee49fd766af4ffcd89 | Bbowen100/array-list-leveler | /code.py | 3,691 | 4.28125 | 4 | '''leveling arrays Algorithm
excess = len(big_array) - mean
floaters = number of elements % number of arrays
1. take the sum of the number of elements in each array
2. integer-divide the sum by the number of arrasy to find the mean
3. Loop (while the excess is greter than the floaters on the top)
{ go through each ar... |
d8e4cd4d27e10abb7379a062a0169b507e52ac2e | marcson909/sum-pairs | /python/sum_pairs.py | 498 | 3.75 | 4 | def sum_pairs(int_list, target):
output_list = []
#iterate with 2 range loops and append matches to output list
for i in range(len(int_list)-1):
first = int_list[i]
for j in range(i + 1,len(int_list)):
second = int_list[j]
if target == int_list[i] + int_list[j]:
... |
8848fb16f49ec560ac3665f11a6294a0acae81c9 | tomhuhges/everything-burrito | /python/min.py | 255 | 3.71875 | 4 | import random
random_list = [random.choice(list(range(1, 100))) for _ in range(10)]
print(random_list)
def get_min(random_list):
print("min value is:", min(random_list))
print("min index is:", random_list.index(min(random_list)))
get_min(random_list) |
cb0d73b9fc1519ee834dce3936fb4c67ae43bf56 | jaredchin/Core-Python-Programming | /第十一章/练习/11-17.py | 4,058 | 3.96875 | 4 | # (a)
# 【名词解释】Currying:因为是美国数理逻辑学家哈斯凯尔·加里(Haskell Curry)发明了这种函数使用技巧,所以这样用法就以他的名字命名为Currying,中文翻译为“加里化”。
#
# 我感觉很多人都对函数加里化(Currying)和偏函数应用(Partial Application)之间的区别搞不清楚,尤其是在相似的上下文环境中它们同时出现的时候。
#
# 偏函数解决这样的问题:如果我们有函数是多个参数的,我们希望能固定其中某几个参数的值。
#
# 几乎所有编程语言中都有非常明显的偏函数应用。在C语言中:
#
# int foo(int a, int b, int c) {
#
# return ... |
2fed6de79c654388b3a7d1cd57b684b90417f168 | AmeySingh/PythonDjangoInternship | /pythonProjectInterns/concepts/TestDictionary.py | 377 | 4.25 | 4 | #key value pair in curly bracket
# dictionary are indexed by key
#dictionary are mutable
student = {101:"rajesh",102:"suraj",103:"tom"}
print(student[102])
for i,j in student.items():
print(i," and value is ",j)
for i in student.keys():
print(i)
for i in student.values():
print(i)
student[105] = "Ram... |
cccbbfa13b37b6ba722cf23de5f4d9abbc3ab4cf | vidyullathaks/Chat-app-sockets-in-Python | /client.py | 2,745 | 3.828125 | 4 | # Socket Chatroom client - Creating chat application with sockets in Python
import socket
import select
import errno
HEADER_LENGTH = 10
IP = "127.0.0.1"
PORT = 3000
my_username = input("Username: ")
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((IP, PORT))
client_socket.setblo... |
0cc49a9771230b2ba8ecff74e083fc21bcc45f2a | haebuki/python_prac | /basic/comp_dict_list.py | 241 | 3.953125 | 4 | list = [1,2,3,4,5]
list1= [1,2,3]
dict = {'a':1,'b':2}
dict1 = {'a':5, 'c': 3, 'b': 2}
list2 = list + list1
print(list2)
dict1.update(dict)
print(dict1)
print(dict1.keys())
print(2 in dict.values())
dict.clear()
print(dict)
#수정 |
7e0614a2cd961f4e454e6452ceeb7854bf57e656 | MartinGebske/KBA | /ProgBackend.py | 2,967 | 3.515625 | 4 | import csv
import os.path
import tkinter as tk
from tkinter import filedialog, messagebox
import Utils as ut
## Hier werden datenrelevante Operationen ausgeführt.
# Listen für jeden Eintrag
bevList = []
h2List = []
phevList = []
ottoHybList = []
dieselHybList = []
lpgList = []
class myBackend():
def __init__(se... |
5484c370ec8e04687c4f0be843561ccfda0d41ba | margunwa123/Simple-Sundanese-Translator | /src/TehManager.py | 1,703 | 3.671875 | 4 | class TehManager:
"""
Teh Adder digunakan untuk menambahkan teh setelah kata ganti orang
dalam bahasa sunda
"""
kataGantiOrang = ["pribados", "urang", "aing", "abdi", "dewek",\
"kaula", "kuring", "anjeun", "hidep", "maneh", "sia", "anjeunna",\
"manehna"]
uselessWord = ["a... |
6a9dbc71914ff347a0c61e89afccf39eac333c76 | luizgustavodarossi/Pyhton | /ex051.py | 232 | 3.734375 | 4 | t = int(input('Informe o termo da progressão aritmétrica: '))
r = int(input('Informe a razão da progressão aritmétrica: '))
d = t + (10 - 1) * r
for c in range(t, d, r):
print('{}'.format(c), end=' - ')
print('FIM!')
|
4a537ddd9cb8fee8d53c2f74ad79cacc6dfbfbd7 | gabby/the_hard_way | /ex14.py | 981 | 4.125 | 4 | from sys import argv
script, user_name, saying = argv
prompt = '> '
print "Hi %s, i'm the %s script. %s!" % (user_name, script, saying)
print "I'd like to ask you a few questions."
print "Do you like me %s? %s!" % (user_name, saying)
likes = raw_input(prompt)
print "Where do you live %s? %s!" % (user_name, saying)
... |
eb893d53d5445dccecbcff2536fa9152d543c4fa | DominikBuj/mouse-game | /behaviour.py | 953 | 3.5625 | 4 |
"""
File with classes meant for the simple Behaviour Tree decision making of the player.
"""
class Atomic():
"""Atomic action"""
def __init__(self, func):
self.func = func
def run(self):
return self.func()
class Task(object):
"""Task class"""
def __init__(self, *children):
... |
ede13a0cac492154d064f0c790e182bc59cca527 | jiajiabin/python_study | /day11-20/day15/12_读操作.py | 988 | 3.796875 | 4 | # 打开一个文件读取文件中的内容
path = r'C:\Users\Ace\Desktop\武汉1902\day15\dir\1.txt'
file = open(path, 'r', encoding="GBK")
# 读取文件内容,生成字符串
# 全部读入
s = file.read()
print(s)
# 在文件操作中有一个虚拟的读写指针,记录着读写的进度,下次读写只能接着读写
# 重定向读写指针
file.seek(0) # 参数是字节数
s = file.read()
print(s)
file.seek(0)
# 读取指定字节数
s = file.read(3)
print(s)
s = file... |
379a323462293763a086b706184fead5b2b35d8c | vj-reddy/PythonBatch1 | /Aug20/projectEuler/problems2/euler3.py | 484 | 3.984375 | 4 | is_factor = lambda x, y: x % y == 0
def prime_factors(value=13195):
"""
In this method will try to find prime factors
"""
prime_factors_found = [index for index in range(2, value//2) if is_factor(value, index) and is_prime(index)]
return prime_factors_found
def is_prime(value):
is_prime_numb... |
e040564ad9913d1b048f0617c403129763a13079 | oscarhscc/algorithm-with-python | /程序员面试经典/面试题 02.08. 环路检测.py | 1,398 | 3.890625 | 4 | '''
面试题 02.08. 环路检测
给定一个有环链表,实现一个算法返回环路的开头节点。
有环链表的定义:在链表中某个节点的next元素指向在它前面出现过的节点,则表明该链表存在环路。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:no cy... |
a17fe3f1583dbf7757a03f23fe45b5015455db7d | Manraj15/KnightFall | /src/Play.py | 4,113 | 3.90625 | 4 | '''
The following class is responsible for the visual representation of the
board on the screen that the user will interact with the game from
Last updated in March 17 2019
'''
import pygame
import os
from PauseMenu import *
from Button import *
from BoardModel import *
from ViewController import *
class Play(ViewCon... |
c676b4de4c4f5193897269d7b338a29c003c58fa | JulianDavidG07/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 125 | 3.8125 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
return [replace if o == search else o for o in my_list]
|
290ab5f626ac39084a6afd473b9657215936314e | mkorell75/mkdev_python | /clip2.py | 2,102 | 3.84375 | 4 | #!c:\tools\Python\Python35\python.exe -u
''' My Clipboard Dictionary
' Usage: clip add <key> : Copies text currently in the clipboard to our dictionary
' clip del <key>
' clip list : Lists all keywords from the dictionalry
' clip <key> : Copies the text contained with the key to the clipboard for fu... |
ce1890a69e98d413346a00ca5c4c5a4aa341645f | Hubwithgit89/ajiranet | /dl_insert.py | 1,631 | 4.28125 | 4 | #!/usr/bin/env python3
"""
dl_insert.py file contains the functions to insert the elements to
doubly linked list.
This file supports two funtions to insert a node in the doubly
linked list. (dl_insert_before, dl_insert_after)
Authour: ?
"""
from dlist_node import DListNode
def dl_insert_before(head, ins_node, new_... |
dad99c479928868922385a733e04b8736b4ad345 | rafaelpalmerio/WebServices | /password_breaking/bruteforce.py | 891 | 3.796875 | 4 | from string import printable
from itertools import product
user_password = 'senha' # just a test password
found = False
caracteres = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
tries = 0
for length in range(1, 10): # it isn't reasonable to try a password more than this length
#password_to_att... |
ef0cdecaa0f2eb8b9a0a95903ea7cc67cd91464c | mscbalakrishnan/bigP | /IntellPython/src/DemoArray/ArrayCreate.py | 880 | 4.1875 | 4 | arr = [10, 20, 30, 40, 50]
print(arr[0])
print(arr[1])
print(arr[2])
#negative indexing
arr = [10, 20, 30, 40, 50]
print(arr[-1])
print(arr[-2])
#Adding an element in an array using append()
add = ['a', 'b', 'c']
add.append('d')
print(add)
#Removing elements of an array using del, remove() and pop()
colors = ["viole... |
33770b881a1bced81cf3f408ab60a0edd74d7fb6 | greenDNA/Python-Crash-Course | /Exercises/Chapter 3/7.py | 740 | 4.09375 | 4 | names = ['nicki minaj', 'sabrina claudio', '6lack']
print('{} you are invited.\n{} you are invited.\n{} you are invited.'.format(names[0], names[1], names[2]))
print("{} can't make it".format(names[0]))
names[0] = 'akon'
print('{} you are invited.\n{} you are invited.\n{} you are invited.'.format(names[0], names[1], n... |
430e80452c181676247034be369e61e7d9d358b0 | jtveals1/my-python-software | /recursion.py | 171 | 3.875 | 4 | def main():
num = multiply(8,4)
print(num)
def multiply(x,y):
if x == 1:
return y
else:
return multiply(x-1,y + 4)
main()
|
cdee78eda02dbb11d8a6d44e7421587fed4141ad | Huzet/Leet_Code | /sortMatrixDiagonally.py | 3,231 | 4.0625 | 4 | #! Python3
# https://leetcode.com/problems/sort-the-matrix-diagonally/
# Input:
mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
def diagonalSort(mat):
# 1. make diagonal lists
diagonalList = []
counter = 0
blankline = []
for y in range(len(mat)):
for x in range(len(mat[y])):
... |
ba13ec07c2c25a88bedbf8e8806ec462df39486d | Ihyatt/algo_patterns | /tree_dfs/warm_up/path_sum.py | 609 | 4.09375 | 4 | """
Path Sum
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
"""
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
... |
baf41a19ec598d2f9bac22b5bc7b56ceabce9410 | Danlei27/PycharmProjects | /exercicio 51.py | 683 | 4.0625 | 4 | # Desenvolva um programa que leia o
#primeiro termo e a razão de uma PA.
# no final, mostre os 10 primeiros
# termos dessa progressão.
a1 = int(input('Digite o primeiro termo da PA:'))
r = int(input('Digite a razão da PA:'))
print('Os dez primeiros termos dessa PA são:\n',a1,end=' → ')
for n in range(1,10):
a1 += r... |
1f1014b8a5e1e5d2c4fd0c892966483f40d8bce5 | efrigo88/Python-Course-Udemy | /01. HelloWorld/interpolation.py | 328 | 4 | 4 | age = 32
print('My age is %d years' % age)
print()
major = 'years'
minor = 'months'
print('My age is %d %s, %d %s' % (age, major, 6, minor)) # I can use the %s to use strings
print('PI is approximately %f' % (22 / 7)) # %f for float data type
print('PI is approximately %60.50f' % (22 / 7)) # using prec... |
22940fa2ddfb8e5a791c57c4b3e6ca9465e18c85 | iFengZhao/Algorithms-1 | /剑指Offer/48-最长不含重复字符的子字符串.py | 1,114 | 3.78125 | 4 | '''
题目:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含‘a’~‘z’的字符。例如,在字符串”arabcacfr“中,
最长的不含重复字符的子字符串是“acfr”,长度为4。
'''
class Solution:
def longest_substring_without_duplication(self, str):
if not str:
return
string = list(str)
current_length = 0
max_length = 0
p... |
762f8df720a58192b50be8faa7382e90c76e05f4 | Fynardo/AoC2k20 | /day10/adapter.py | 884 | 3.53125 | 4 | # -*- coding:utf-8 -*-
import os
def read_input():
with open(os.path.join('day10','input'), 'r') as f:
return [int(line) for line in f.read().splitlines()]
adapters = read_input()
# Part 1
wall_plug = 0
my_device = max(adapters) + 3
adapters_end_to_end = [wall_plug] + adapters + [my_device]
print('Pa... |
465c5fde0538c41504995bfc5813d86e54d25c52 | JoyLeeA/CodeUp | /74.py | 82 | 3.65625 | 4 | N = input()
for i in range(ord('a'), ord(N)+1):
print(chr(i), end=' ')
print() |
a498c9ea0e4ff99f247e874b23ffe6c1b966ba41 | RookieDay/py_basic | /basic/IMPORTANT.py | 14,252 | 3.609375 | 4 | # 如果字符串里面有很多字符都需要转义,就需要加很多\,为了简化,Python还允许用r''表示''内部的字符串默认不转义,可以自己试试:
# >>> print('\\\t\\')
# \ \
# >>> print(r'\\\t\\')
# \\\t\\
# 如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''...'''的格式表示多行内容,可以自己试试:
# >>> print('''line1
# ... line2
# ... line3''')
# line1
# line2
# line3
# /除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数:
# >>... |
ecdb3042102ff2777fade4db562725e5929cfed0 | SnorlaxLarid/lessonProjects | /mlp_numpy.py | 4,413 | 3.5625 | 4 | import os
import numpy as np
import datasets
import time
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_deriv(x):
return sigmoid(x) * (1 - sigmoid(x))
def relu(x):
c = np.zeros_like(x)
slope = 0.01
c[x > 0] = x[x > 0]
c[x <= 0] = slope * x[x <= 0]
return c
def relu_deriv(x):... |
8e4a81433733b78f7d2bb4ee1ed76ce96da98392 | bakunobu/exercise | /python_programming /Chapter_1.3/thousand_nums.py | 603 | 4.125 | 4 | """ Составьте программу fiveperline.ру,
использующую один цикл for и один оператор if для вывода, по пять в строку,
целые числа от 1 ООО (включительно) до 2 ООО (исключительно).
Подсказка: используйте оператор %. """
def print_thouthand() -> None:
"""
prints all the numbers in [1000:2000) (five per line)
... |
30d926091d8936bf425b77aeba4e09662c41838f | keerthz/luminardjango | /Luminarpython/languagefundamentals/positiveornegative.py | 145 | 4.15625 | 4 | num=int(input("enter the num"))
if(num>0):
print("num is positive")
elif(num<0):
print("num is negative")
elif(num==0):
print("zero") |
b1606564717b5da488246dea8a723a95c5e4efe9 | unorthodox-character/Desktop_repo | /everything_python/python_practice/dictionary.py | 146 | 3.75 | 4 | # A simple example of dictionary
myCat = {'color':'orange', 'size':'huge', 'disposition':'loud'}
print(f"The color of my cat is {myCat['color']}") |
ada137753ffc450c591e6a9a4f2d521f71b5b9a5 | rockingrohit9639/pythonBasics | /forLoops.py | 144 | 3.96875 | 4 | list1 = [int, float,"Rohit", 1, 67, "Ninja", 22, 0,1,4,"etc"]
for item in list1:
if str(item).isnumeric() and item > 6:
print(item) |
63d897eedb34bea7b6f5d8d06153f82ee529f9a0 | olee2/Phrase-Hunters | /game.py | 3,193 | 3.703125 | 4 | import random
import string
from phrase import Phrase
class Game:
def __init__(self, phrases):
self.play = True
self.phrases = phrases
if self.verification():
print("\n Phrase Hunters\n \nOnly letters (A-Z)"
"\n \n Good Luck!")
self.phrases =... |
018ec1e50451925036bbae63e9849ffb3002e3b1 | luisescobar09/poo_1719110043 | /semana_2/objeto_calculadora.py | 1,113 | 3.703125 | 4 | class Calculadora:
#Atributos:
funciones = True
memoria = True
digitos_max = "12"
sonido = False
exponente = True
marca = "Casio"
tipo_calculadora = "Cientifica"
costo = "165 pesos"
tamano = "Mediana"
peso = "512 gramos"
#Métodos:
def sumar (self):
print("Sumar")
def restar (self):
... |
d6803ee8c03df0713fb2bb7091ddf581a5a553d3 | pablomacp/tfm_stochastic_dividends | /python_lib/code/graphics.py | 1,284 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 15 14:17:16 2021
@author: pablo
"""
from random import randint
from math import sqrt
import matplotlib.pyplot as plt
# plt.plot([0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 1, 2, 1, 0, -1], 'b')
# plt.plot([0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 1, 2, 1, 0, -1], 'bo')
# plt.ylabel('... |
399bdc283f34b9a385c334978b95b1ec9072b089 | Baistan/FirstProject | /str_method_tasks/Задача4.py | 359 | 4.1875 | 4 | string = input()
if string[0].islower() and len(string) < 10:
print(string[0].islower())
string = string.upper()
print(string)
elif string[0].isupper() and len(string) < 10:
print(string[0].isupper())
string = string.lower()
print(string)
elif len(string) > 10:
print(len(string))
string ... |
c48a6f32237c7c8fd034c13825db137a271d7302 | Reza-Salim/Training | /18.py | 266 | 3.96875 | 4 | a = int (input("Enter 1st:"))
b = int(input("Enter 2sd:"))
c = int(input("Enter 3rd:"))
if a>b :
temp= a
a = b
b= temp
if a>c:
temp = a
a = c
c = temp
if b>c :
temp = b
b = c
c = temp
print ("Sorted is ", a, b, c)
|
202c78f60844185a3771c71b2870bb0a3dfd0c28 | yamendrasinganjude/aws_cloud | /CheckPrime.py | 322 | 4.1875 | 4 | num = int(input("Enter a Number:"))
if num>1:
#iterate from 2 to n/2
for i in range (2, num//2):
#if num is divide by 2 or n/2 then return false
if (num % i==0):
print(num,"is not prime.")
break
else:
print(num,"is a prime")
else:
print(num,"is not prime"... |
69f62f67f9b0b953d10544380bff4213a1322d0d | souradeepta/PythonPractice | /code/pgms/string-comp.py | 409 | 3.734375 | 4 | from typing import List
def compress(chars: List[str]) -> int:
count = {}
result = []
for char in chars:
if char not in count:
count[char] = 1
else:
count[char] += 1
for key, value in count.items():
result.append(key)
result.append(value)
r... |
8b88b854b3c99accb75a7f40ac5977c6b27a9ece | qwerty1092/Coursera | /week4/synth/magic_class.py | 1,055 | 3.5625 | 4 | import os
import tempfile
class File:
def __init__(self, path):
self.path=path
def __str__(self):
return self.path
def write(self, string):
try:
with open(self.path, 'a') as f:
f.write(string)
except:
pass
... |
9f6fc0032d8741182fafde10b085675541d689e6 | luolan-677/louPlus | /FindDigits.py | 150 | 3.796875 | 4 | #! /usr/bin/env python3
fobj = open('/tmp/String.txt')
s = fobj.read()
res = ''
for char in s:
if char.isdigit():
res += char
print(res)
|
2c22c81ff365a9bf16cb3fe03c34d0dd9694c3bf | jorgeromeromg2/Python | /mundo2/ex007__D44.py | 1,568 | 4.0625 | 4 | #-------SISTEMA DE COMPRA COM DESCONTO------
print(10 * '--=--')
print('CONDIÇÃO ESPECIAL PARA PAGAMENTOS')
print(10 * '--=--')
nome = str(input('Digite seu nome: ')).capitalize()
valor = float(input('Digite o valor do produto: R$ '))
condicao = int(input(' 1 - dinheiro ou cheque\n 2 - cartão à vista\n '
... |
88c712c19c7b96c5012b2c3e1dad178a31ba2a2b | DatPhan-code/datphan | /baitap10.py | 639 | 3.640625 | 4 | #Viết chương trình sử dụng generator
# để in số chia hết cho 5 và 7 giữa 0 và n,
#cách nhau bằng dấu phẩy, n được người dùng nhập vào.
n = int(input("Please Enter number : "))
def printchiahet(n):
for i in range(n+1):
if (i%5==0) and (i % 7 ==0):
yield i
values = []
for i in printc... |
3d54b8fb67d520f9dc77bc9f35e6f6b95c6a39e8 | 316112840/Programacion | /ActividadesEnClase/Class/MatrizNN.py | 1,431 | 3.796875 | 4 | class MatrizNN:
def __init__(self, N, matriz):
self.n = N
self.matriz = matriz
def mostrarMatriz(self):
for i in self.matriz:
print(i)
def MatrizLista(N, lista):
l = []
indice = 0
for i in range(N):
m = []
... |
7f332fe63938bce53a51b6ee74fa5570b49d83c5 | Rose22/rsbm | /rsbm_calculator.py | 585 | 3.5 | 4 | def total_price(items, only_paid=False):
total_price = 0.00
for item in items:
if only_paid and not item['paid']:
continue
total_price += float(item['price'])
return total_price
def total_price_bills(monthly_bills, only_paid=False):
total_price_bills = 0.00
for bill in... |
323e53631c192068595dc0af64d24b070a263c67 | RileyAbr/Frequent-of-Legends | /mining-algorithms/bayes_classifier.py | 2,793 | 3.5625 | 4 |
#A skeleton for implementing Naive Bayes Classifier in Python.
## Author: Salem
import numpy
import pandas
import random
import time
import operator
import math
import random
trainingFile = "classifier_train.txt"
testingFile = "classifier_test.txt"
Xtrain = numpy.loadtxt(trainingFile)
n = Xtrain.shape[0]
d = Xtrain... |
bc351d68ee107d4214017ceb4fa6eedd7f3fca48 | seoyeonhwng/algorithm | /BJ/1080.py | 765 | 3.546875 | 4 | def convert(n, m):
# (i, j)부터 시작해서 3*3크기의 A의 부분행렬값을 뒤집음
for i in range(n, n+3):
for j in range(m, m+3):
matA[i][j] = 1 if matA[i][j] == 0 else 0
def check():
for i in range(N):
for j in range(M):
if matA[i][j] != matB[i][j]:
return False
return T... |
c6602cd568e92b1bacdd1df22a6c5b8b515c2808 | emiliano-f/ia-uncuyo-2021 | /tp5-busquedas-locales/code/genetic.py | 6,319 | 3.546875 | 4 | # This algorithm uses:
#
#
#
#
#
from random import random, randint
class Board:
def __init__(self,
_size: int,
_board: list = None):
if _board == None:
self.board = [randint(0, _size-1) for _ in range(_size)]
else:
self.board = _board
... |
46038c41149958998a8140506730140bc4e948b7 | iomusashi/python-playground | /100daysofpython/004/d4-coin-flip.py | 122 | 3.71875 | 4 | # 0 tails, 1 heads
import random
flip = random.randint(0, 1)
if flip == 0:
print('Tails')
else:
print('Heads')
|
8629fb4e3a99b8ee4990c32de6f8b1e4304dc357 | kcbhamu/MLclass | /codes/10_Advanced/GAN/GAN_MNIST.py | 8,551 | 3.5 | 4 | '''
This code shows how to apply GAN to MNIST dataset.
It is to train the generator to forge human handwriting numbers.
'''
import numpy as np
import matplotlib.pyplot as plt
import sys
import time
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
np.random.seed(1) # make result reproducible
from keras.layers im... |
3429d6926a3da2df8c426ee45a45f27b044a62c5 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4127/codes/1800_2565.py | 431 | 3.671875 | 4 | from numpy import*
nota= array(eval(input("quais as notas do aluno?")))
freq= array(eval(input("quais as frequencias dos alunos?")))
ch=int(input("qual a carga horaria da materia?"))
vet= zeros(3, dtype=int)
for i in range(size(nota)):
if (nota[i]>=5 and freq[i]>=(ch*75)/100):
vet[0]=vet[0]+1
elif (nota[i]<5 and ... |
360a3400b65a527a54aab378a27ebd8195ff5943 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4162/codes/1836_2604.py | 121 | 3.5625 | 4 | from numpy import*
mt=array(eval(input("insira a relacao: ")))
print(mt)
for i in range(shape(mt)[0]):
print(max(mt[i])) |
25faa84e2bbdcde2a08d51083e2b9960fbdc5dc9 | zerghua/leetcode-python | /N2057_SmallestIndexWithEqualValue.py | 1,323 | 3.703125 | 4 | #
# Create by Hua on 1/31/22.
#
"""
Given a 0-indexed integer array nums, return the smallest index i of nums such
that i mod 10 == nums[i], or -1 if such index does not exist.
x mod y denotes the remainder when x is divided by y.
Example 1:
Input: nums = [0,1,2]
Output: 0
Explanation:
i=0: 0 mod 10 = 0 == nums[0]... |
3ca54614ac4fb4a2307a8d22c3ab9c7deb2d2071 | pulinghao/LeetCode_Python | /回溯/22. 括号生成.py | 1,082 | 3.8125 | 4 | #!/usr/bin/env python
# _*_coding:utf-8 _*_
"""
@Time :2020/6/6 1:38 下午
@Author :pulinghao@baidu.com
@File :22. 括号生成.py
@Description :
"""
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
track =... |
19184776d8264f7628f658e5baac95b99034ace9 | arnabid/QA | /sortsearch/binarysearch.py | 3,350 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 15 09:20:57 2017
@author: arnab
"""
# recursive binary search
def binarysearch(arr, low, high, key):
# returns the index of key or -1 if key not found
if low > high:
return -1
mid = low + (high-low)/2
if arr[mid] == key:
return m... |
01199dbd9a8d5c27a267056ba0991847129a38b1 | HLW168/LintCode | /98 · Sort List.py | 2,100 | 3.9375 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The head of linked list.
@return: You should return the head of the sorted linked list, using constant space complexity.
"""
... |
ec94aa6a84098ba41b9d718abf2fafa6da715c4d | mchez808/OOPython | /ch1-oop-basics/class_level_book.py | 1,860 | 4.15625 | 4 | # class methods and attributes
class Book:
# TODO: properties defined at the class level are shared by all instances
BOOK_TYPES = ("HARDCOVER", "PAPERBACK", "EBOOK")
# TODO: dunder properties are hidden from other classes
__booklist = None # essentially a private variable
# instance methods rece... |
10275c2efad943939564ae90fe8142c26791d3b1 | shiwuhao/python | /module/re_demo2.py | 149 | 3.53125 | 4 | #!/usr/bin/env python3
import re
emphasis_pattern = r'\*\*(.+?)\*\*'
res = re.sub(emphasis_pattern, r'<em>\1</em>', '**This** is **it**')
print(res) |
38651a48d6316dbf0862ca2122b8bd40696040ff | Harry-Rogers/PythonNotesForProfessionals | /Chapter 8 Sets/8.2 Get unique elemtns of a list.py | 261 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 27 16:00:07 2020
@author: Harry
"""
restaurants = ["Mcdonalds","Chicken", "Burger King", "KFC"]
unique_res = set(restaurants)
print(unique_res)
print(list(unique_res))
print(list(set(restaurants))) |
f3fdb597305eeeede5585799aa03439c2cd3d87b | CaoZewei/learnPython | /hitAlien/setting.py | 1,010 | 3.765625 | 4 | class Setting():
"""储存外星人入侵的所有设置的类"""
def __init__(self) -> None:
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230,230,230)
self.bullet_width =3
self.bullet_height =15
self.bullet_color = (60,60,60)
self.bullet_allowed = 10
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.