blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
649c5fd1161f462816e1292832c4382a0c8e418a | Chrisaor/StudyPython | /GeeksforGeeks/Practice/2. Basic/44.RearrangeArray.py | 426 | 3.875 | 4 | def rearrange_array(arr):
rearray = list()
for i in range(len(arr)):
if i % 2 == 0:
num = arr.pop()
rearray.append(num)
else:
num = arr[0]
del arr[0]
rearray.append(num)
return ' '.join(map(str, rearray))
t = int(input())
for i in... |
c5fb257eee3e7d2bdc141cf71fa928099ddbfbb5 | 809709370/hello-word | /game.py | 1,931 | 3.84375 | 4 |
import random
import sys
class sprite:
"""这是一个基类"""
move_len = (-3,-2,2,3)
def __init__(self,postion1 = None):
self.energy = 0
self.step = random.choice(sprite.move_len)
if postion1 is None:
self.postion = random.randint(0,20)
else:
self... |
3383e60254d290899fcbe6b77aedbb3df5668093 | lincookie/Code | /python/lab2/字串處理.py | 107 | 3.59375 | 4 | str = input()
now = input()
new = input()
print(str.upper())
print(str.lower())
print(str.replace(now,new)) |
4b916d89a07a428c5c49da488d861de7898904a8 | gbravo5/PyGame-Carrera_PyGame | /2430_Mover_Corredor_PyGame_2.py | 1,887 | 3.5 | 4 | import pygame
import actions
import random
class Game():
# assumptions:
# 1.- screen:
# size
screen_size = width, height = 640, 480
# title
game_title = 'Mover_Corredor_PyGame'
# background
coordinates_background = 0, 0
game_background = 'images/circuito.png'
... |
364b6e53db1b81b40349bc434cc3b9cebbd2b008 | miguelgallo/Python2019_1 | /Aula1/aula1_ex6.py | 204 | 3.828125 | 4 | print ('Programa usado para calcular a velocidade final de um objeto em queda livre ')
g = 9.8 #m/s^2
h = 3 #metros
v_final = (2*g*h)**(1/2)
print('A velocidade final do objeto é: ', "%.3f" % v_final)
|
bdd3e09b2dd8f5566c9fd6a1dbb116bce50d9c70 | Hacketex/PycharmProjects | /word avarage.py | 376 | 4.03125 | 4 | sum1 = 0
word = ' '
while word != '':
word = input("enter the word or press enter to exit: ")
print(len(word))
# count = len(word)
sum1 = sum1 + len(word)
print("total word is ", sum1)
# key='yes'
# while key=='yes':
# word=input("enter the word: ")
# count=len(word)
# print(count)
# if wor... |
f16e20bb6541fee0a735d3834ad33afa15704583 | havenshi/leetcode | /508. Most Frequent Subtree Sum.py | 822 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
ec8cb58a83a00b28bd7315a5246e77779c9bc02e | UmmuRasul/python-training | /Tutorials/controlStr/forLoop.py | 658 | 3.765625 | 4 | my_string = 'abcabc'
print("-"*20 +"strings for loop" + "-"*20)
# for c in my_string:
# print(c)
# print(c, end=" ")
for c in my_string:
if c =='a':
print('A', end=" ")
else:
print(c, end=" " )
print("f"*100)
print("-"*20 +"list for loop" + "-"*20)
cars = ['bmw', 'masedez', 'benz']
... |
0b3a948fe6831ac4b1e9d0d0fd722e2b9e779ea7 | privateOmega/coding101 | /hackerearth/CodeMonk/Basic Programming/Basics of Implementation/array-sum.py | 236 | 3.53125 | 4 | def main():
arrayLength = int(input())
sum = 0
array = list(map(int, input().strip().split(' ')))
for iterator in range(arrayLength):
sum += array[iterator]
print(sum)
if __name__ == '__main__':
main()
|
14f34d465b61b3beacfa3d27faec4c8231b49efd | Mihika16/Project-Euler-Solutions | /Problem10.py | 363 | 3.765625 | 4 |
def Primefunction(num):
if num<2: return "False"#From the next 3 lines, I got help from a website but I understood it fully
for i in range(2, int(num**0.5) + 1):#this
if num % i == 0:# and this
return False
return True
sum=0
for i in range(2, 2000000):
if Primefunction(i):
... |
44d08f27236771fd93a427de06ef5e508d95c42a | robbyt/query_tool-py | /query_tool/user_input.py | 4,013 | 3.90625 | 4 | import argparse
class UserInput(object):
usage = "Please read --help"
data = {}
facts = {}
debug = False
def __init__(self, args):
'''
sets up the user input system. When setting up this
class, pass sys.argv[1:] into the class, otherwise for testing
pass in a dict ... |
56e35de4078aaf3c79d5123728c3f805b4e678a3 | refiute/nlp100 | /code/chapter1/prob08.py | 261 | 3.828125 | 4 | # -*- coding: utf-8 -*-
def cipher(s):
ret = ""
for i in range(len(s)):
if s[i].islower():
ret += chr(219-ord(s[i]))
else:
ret += s[i]
return ret
if __name__ == '__main__':
print(cipher("HeLlo WoRLd"))
|
7ec0fd23dd856187253cef7097a79e87015c17e9 | prashuym/IKPrograms | /DP-0140H-WordBreakList.py | 1,722 | 3.75 | 4 | """
140. Word Break II
https://leetcode.com/problems/word-break-ii/
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary ma... |
eb87effe6727039e4192d242cb22e729be28b3c0 | VictorMinsky/Algorithmic-Tasks | /HackerRank/Python/Lists.py | 1,678 | 4.5625 | 5 | """
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse t... |
7c6f87c762ad62b2d8708d6c7e719af984ce66be | subash2617/Task-4 | /Task 4B.py | 287 | 4.5 | 4 | # Creating a tuple and printing the reverse of the created tuple #
TupleA=("26 NOVEMBER 2020")
x=reversed(TupleA)
print(tuple(x))
# Creating a tuple and converting tuple into list #
TupleB=("apple", "banana", "cherry", "orange")
ListB=list(TupleB)
print(ListB)
print(type(ListB)) |
6df9d047b82c52d6e1837d83ba5a84824c2a1578 | alisakolot/Coding-and-Testing-Practice- | /Jan/01_11/dict_review.py | 1,075 | 3.921875 | 4 | """Tests:
>>> wordcount(poem)
{'seven': 4,
'Kits: 1,
'sack': 1,
'As': 1,
'kits': 1,
'Ives?': 1,
'How': 1,
'St.': 2,
'had': 3,
'sacks':1,
'to': 2,
'going': 2,
'was': 1,
'cats': 1,
'wives': 1, ... |
0c06baec6f482537ed94f009a064e5815a549b1d | ocdarragh/Computer-Science-for-Leaving-Certificate-Solutions | /Chapter 9/Tasks/pg190_Task7.py | 1,066 | 4.1875 | 4 | # see https://realpython.com/python-square-root-function/
import math
a = int(input("enter size of stick A:"))
b = int(input("enter size of stick B:"))
c = int(input("enter size of stick C:"))
if a > b and b > c:
hypotonuse = a
opp = c
adj = b
elif b > a and b > c:
hypotonuse = b
opp = a
adj = ... |
a5c182a6ec4fdb2d302541813d7aef4a640e2ce9 | manish1822510059/Python-1000-Programs | /Pattern/43_pattern.py | 208 | 3.75 | 4 | n = 5
cen = 1 #centre
for x in range(1,n+1):
for y in range(1,n+1):
if(x==y or y==cen ):
print("* ",end="")
else:
print(" ",end="")
print() |
ccddc220111bd8f9385e5309bfa219488decc2df | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/4f0a5ffac46a4ccf8a4d53740bff9edc.py | 254 | 3.5 | 4 | def hey(what):
strippedText = what.strip()
if strippedText.isupper():
return 'Whoa, chill out!'
if not strippedText:
return 'Fine. Be that way!'
if strippedText.endswith('?'):
return 'Sure.'
return "Whatever."
|
38aff40cf28e9faa80cc48d1fd7d3f98518ac6ee | imtiaz-rahi/Py-CheckiO | /Dropbox/The Most Frequent Weekdays/mission.py | 1,140 | 4.25 | 4 | from calendar import weekday, day_name
def most_frequent_days(year):
return [day_name[day] for day in sorted({weekday(year, 1, 1), weekday(year, 12, 31)})]
if __name__ == '__main__':
print("Example:")
print(most_frequent_days(1084))
assert most_frequent_days(1084) == ['Tuesday', 'Wednesday']
ass... |
1cf18d820279706468e520e2ef8b3097e2992206 | wo-shi-lao-luo/Python-Practice | /Tutorial/class.py | 558 | 3.765625 | 4 | class Animal:
def run(self):
print("running")
class Dog(Animal):
def __init__(self, habbit):
self.habbit = habbit
def eat(self):
print("eating")
class Cat(Animal):
pass
dog1 = Dog("eat")
dog2 = Dog("run")
dog1.run()
dog2.run()
print(dog1.habbit, dog2.habbit)
#
# book
# ... |
56e00a8baf0f5432ac82d3edd199829521096ce1 | billchuan/python2 | /project1/demo08.py | 1,519 | 4.15625 | 4 | # 3月23日学习代码
# 1、创建一个函数,计算20+30的值
# def sum_2():
# n1 = 20
# n2 = 30
# sum1 = n1 + n2
# print("%d+%d=%d" % (n1, n2, sum1))
#
#
# sum_2()
# 2、修改函数,提高该函数的通用性,使其能计算任意2个数的和
# def sum_2(n1, n2):
# """计算任意两个数的和"""
# result = n1 + n2
# print("%d+%d=%d" % (n1, n2, result))
#
#
# sum_2(10, 20)
... |
bef94dbbb4dcb9df43658109f4ccb6d9d36a814e | MichaelOtt/PythonRPG | /sprites/healthsprite.py | 735 | 3.6875 | 4 | import pygame
class HealthSprite(object):
''' Simple object that moves left and right across the screen '''
def __init__(self, health):
''' Initializes the obstacle sprite '''
self.health = health
self.maxhealth = health
self.reduction = 0.0
self.dead = False
def... |
a8bada726dd3bd96d33017c063e2472d6136d17c | slavafive/GPN-Hackaton | /python_scripts/text_processing.py | 557 | 3.640625 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import pymorphy2
def normalize_word(word):
morph = pymorphy2.MorphAnalyzer(lang='ru')
return morph.parse(word)[0].normal_form
def clean_text(text, normalize=False):
tokens = word_tokenize(text.lower())
words = [word for word i... |
436536bb1b933d6a9a2dbc80e467e0743e19858f | JoanValencia/Python---Clase-4 | /PruebaTemporizador.py | 1,189 | 3.546875 | 4 |
class Hora(UnidadTiempo):
def __init__(self)
self.hora = v
self.htope = 23
class Minuto(UnidadTiempo):
def __init__(self)
self.minuto = v
self.mtope = 59
class Segundo(UnidadTiempo):
def __init__(self)
self.segundo = v
se... |
146b45cdb56c7c0cab2e228cfd3f7bda94fcd482 | IaroslavaDubitkaia/07.10.2020 | /Problema_7.py | 123 | 3.53125 | 4 | v=int(input('Introduceti varsta:'))
print("Greutatea ideala este de", 2*v+8, "kg, Inaltimea ideala este de", 5*v+80, "cm") |
7256e3fa3efe0c897f14567c55c6bc85be94ae4c | Protocol73/CIS-122 | /Hunterville-Tuition-10yr.py | 1,332 | 3.609375 | 4 | #For CIS122 p#224 Q10
#Written by Protocol73
import os
import sys
import time
import json
try: #for py v2 vs v3 input
input = raw_input
except NameError:
pass
def clear_term(): #clear the Screen
os.system('cls' if os.name=='nt' else 'clear')
#call to Clear the Terminal
def Check_Prompt():#For Asking... |
c02b96bcfe38c93fcbe412e4bf9289cc5d5d5742 | orimamo/check-bot | /exercises middel/targil-11.py | 110 | 4.03125 | 4 | a=input("insert one word :")
b=input("insert the second word :")
print("the new sentence is :" + b + " " + a ) |
efa17b970bdef0043825ca2d03032f4d59ffca08 | OakdaleRaspberryPi/RaspberryPiProjects | /Hangman.py | 4,137 | 3.765625 | 4 | #!/usr/bin/env python
2.
3.import random
4.import cPickle
5.
6.class Hangman(object):
7. '''A simple hangman game that tries to improve your vocabulary a bit '''
8. def __init__(self):
9. # the variables used, this is not necessary
10. self.dumpfile = '' #the dictionary file
11. self.... |
388ecda0263b611f91ec57237f59c33041cf7297 | fullacc/chocoremint | /week1/collections_named_tuple28.py | 256 | 3.671875 | 4 | from collections import namedtuple
import statistics
n = int(input())
columns = input().split()
Tuple = namedtuple("Tuple", columns)
res = []
for i in range(n):
s = input().split()
res.append(int(Tuple._make(s).MARKS))
print(statistics.mean(res))
|
4db50a7407ceb9f3c62ce21c36f16921a36592ba | haidragon/Python | /Python核心编程/Python-03/02-内建方法/04-内建方法-sorted.py | 359 | 4.21875 | 4 | a = [5,2,3,4,1]
a.sort()
print(a)
#[1, 2, 3, 4, 5]
b = [5,2,3,4,1]
b.sort(reverse=True)
print(b)
#[5, 4, 3, 2, 1]
print("sorted========>")
print(sorted([1,4,2,3,5]))#由小到大
print(sorted([1,4,2,3,5],reverse=0))#由小到大
print(sorted([1,4,2,3,5],reverse=2))#由大到小
print(sorted(['A','B','D','a','b'],reverse=0))#按照... |
80b30bd0a35fb8a81eedfb51aeef77951714fb13 | dhyoon1112/python_practiceproblems | /13. Fibonacci.py | 261 | 4.125 | 4 | def fibonacci(n):
a = []
for i in range(n):
if i <= 1:
a.append(1)
else:
a.append(a[i-1]+a[i-2])
return a
number = input("How many fibonacci numbers do you want? ")
print(fibonacci(int(number)))
|
778e04a2a99bef78aa119e8e45018c1ab12c0c79 | wangleiliugang/data | /aid1805/pbase/67_read_write_exercise.py | 2,279 | 3.515625 | 4 | # 1.写一个程序,从键盘输入如下信息:
# 姓名 和 电话号码
# 如: 请输入姓名:xiaozhang
# 请输入电话:13888888888
# 请输入姓名:xiaoli
# 请输入电话:13999999999
# 请输入姓名:<回车>
# 把从键盘读取的信息存入'phone_book.txt'文件中,然后用sublime text打开并查看写入的内容
# def phone_number():
# L = []
# while True:
# name = input('请输入姓名:')
# if not name:
# ... |
b22d91b2fd5493c2d4a488cfed0eced7562a7b0c | kaizencodes/algorithms | /queue.py | 2,457 | 4.0625 | 4 | class Queue:
def __init__(self):
self.first = None
self.last = None
def remove(self):
if self.first is None:
raise EmptyQueueException('Can\'t remove from empty queue')
item = self.first.data
self.first = self.first.next
if self.first is None:
... |
acf2483e15dfc783f64b1b8b476760d3d33c6eb2 | treebbb/homeschool2020 | /math/graph.py | 481 | 4.09375 | 4 | #! /usr/bin/env python
"""
Matplotlib users guide:
https://matplotlib.org/users/index.html
"""
import numpy as np
import matplotlib.pyplot as plt
RED = (1.0, 0, 0)
GREEN = (0, 1.0, 0)
BLUE = (0, 0, 1.0)
x = np.arange(0, 5, 0.1)
y = np.sin(x)
#plt.plot(x, y)
def add_shape(points, color):
polygon = plt.Polyg... |
ce3912fb7df69ec3ae8724c2894967570c7e9d39 | venkat24/advent-of-code | /2019/06/part1.py | 1,576 | 3.53125 | 4 | from copy import copy
class Node:
def __init__(self, name, depth, parent):
self.name = name
self.depth = depth
self.parent = parent
def __eq__(self, other):
return type(self) == type(other) and self.name == other.name
def __hash__(self):
return hash(self.name)
def _... |
c88f51ed4ceb059725d860dd8745edb29f5b74de | NGBashir/PDE1130 | /Week 7/wordslice.py | 152 | 4.15625 | 4 | #using slice
word="computing"
x= slice(3,6)
print ("Slicing of ", word ," is",word[x])
# change the above to let the user to specify the start and end
|
234df6eb3a95862d1efd0a8cd33f4c8b0b8f7491 | a523/leetcode | /344.py | 896 | 3.78125 | 4 | """
344. 反转字符串
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
https://leetcode-cn.com/problems/reverse-string/
"""
s = ["h", "e", "l", "l", "o"]
def reverseString(s):
"""
:type s: List[str]
:rtype: None Do not return any... |
2c97affe6ca46fbbab4bbc1fd8079e26f2f01205 | kellyseeme/pythonexample | /314/hotel.py | 502 | 3.734375 | 4 | #!/usr/bin/env python
class HotelRoomCalc(object):
"Hotel room rate calculator"
def __init__(self,rt,sales=0.0085,rm=0.1):
"""Hotel romm calc default arguments"""
self.salesTax = sales
self.roomTax = rm
self.roomRate = rt
def calcTotal(self,days=1):
"Calculate tota... |
c591cb1ad898c1a64b4df637da4301274a84bd76 | hyuk02006/Jusung | /Python 20210628/e_file_class/Ex01_readFile_exam.py | 728 | 3.71875 | 4 | """ [연습]
함수 정의 : count_words
인자 : filename
인자로 받은 파일명을 open 하여 파일을 읽어서 단어를 수를 출력한다.
존재하지 않는 파일명으로 예외가 발생해도 아무런 일을 하지 않는다
"""
def count_words(filename):
try:
with open('./data/'+filename, 'r', encoding='utf-8') as f:
line = f.read()
word = line.split()
cnt... |
81dbded45cebae8648de29b09b6250b4fa76c69d | andrewbrimusu/mis5500.sp21 | /week5_json/algo.py | 286 | 3.71875 | 4 | import numpy
lst = [3,1,4,1,5,9,3,6,5,8,9,7,9,3,2,3,8,4,6]
lst = numpy.random.randint(50, size=10000000)
for i in range(len(lst)):
for j in range(len(lst)):
if lst[i] + lst[j] == 13:
print("found the pair!, its ", lst[i], "and", lst[j])
# O(n^2)
|
719277daa8a95471032643a7e5b5774fd6503694 | mahvish23/CP | /tower of hanoi.py | 716 | 3.921875 | 4 | """ ower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on ... |
4f902d891424198ca14176f76d762d1c3ca1bc42 | luca-m/cv_homeworks | /hworks/morpho.py | 7,738 | 3.515625 | 4 | # -*- coding: utf-8 -*-
__author__ = "Luca Mella"
__version__ = "$Revision: 0.1 $"
__date__ = "$Date: 2013/05/20 $"
__copyright__ = "Copyright (c) 2012-2013 Luca Mella"
__license__ = "CC BY-NC-SA"
"""
MATHEMATICAL MORPHOLOGY
All the routines must work with logical (B/W) and greyscale images, with
automatic detec... |
e26636fe864928507364e99a108c94a6b45da93a | atronk/python | /regexp/match_search.py | 1,132 | 4.0625 | 4 | #For regular expressions мы импортируем РЕ
import re
# used in this format:
#a = re.match(pattern, string, oprtional flags)
myStr = 'You can learn any programming language, whether it is Python2, Python3, Perl, Java, JavaScript, or PHP'
a = re.match('You', myStr)
print('\'a\' is ', a)
print('Find it ignoring the ca... |
c3a9491f7a908196a10e935349575ee9ac49c43c | krishnakpatel/Summer2017 | /graphv6.py | 6,230 | 3.53125 | 4 | # add functionality: modifying values
import networkx as nx
from xml.etree.ElementTree import ElementTree, Element, SubElement
# as soon as the program loads
def initialize():
global circ
global num_node
circ = nx.MultiDiGraph()
num_node = 0
# component generation
def click(type, value):
circ.... |
5936f561d4c0cb43244cb3cbf7c3c8c8234e5a10 | hazemshokry/Algo | /HackerRank/Left Rotation.py | 530 | 4.28125 | 4 | # A left rotation operation on an array shifts each of the array's elements 1 unit to the left.
# For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
def rotLeft(a, d):
for rot in range(d):
for i in range(len(a) - 1):
a[i], a[i + 1] = a[... |
56df00c882e087901ca3582b0c5ddf21528a7326 | breezekiller789/LeetCode | /873_Length_of_Longest_Fibonacci_Subsequence.py | 1,012 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/
# Output: 5
# Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].
arr = [1, 2, 3, 4, 5, 6, 7, 8]
# Output: 3
# Explanation: The longest subsequence that is fibonacci-like:
# [... |
35fa48e4b3223a7798a4c8833a2bc11ae5a9a9d6 | mrsingh3131/Foobar | /Some other foobar gits/SadeghHayeri/questions/002 Hey, I Already Did That!/solution.py | 628 | 3.578125 | 4 | def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
def getNext(n, b, k):
x = ''.join(sorted(list(n), reverse=True))
y = ''.join(sorted(list(n)))
z = baseN(int(x, b) - int(y, b), ... |
b8984e8c25dc44179f92e32e4d41291d62525101 | Ilis/zed | /ex24.py | 770 | 4.0625 | 4 | print("Давайте попрактикуемся")
print("Экранирование\\")
print("Перенос\nстрок и\tтабуляция")
poem = """\tПоэт
Я — поэт
Зовусь я Цветик
От меня вам всем приветик
\t\tЦветик"""
print("-" * 20)
print(poem)
print("-" * 20)
five = 2**2 + 1
print(f"Five to be here: {five}")
def secret_formula(started):
jelly_beans ... |
0ddafedefbba514aa065349fcf3ba7023bfb2762 | reddyimr/Mallikarjunaa | /reverse string.py | 186 | 4.21875 | 4 | #a=input("enter the string")
#b=a[::-1]
#print (b)
#to reverse an array
n=int(input("enter the size of an array"))
a=[]
for i in range(n):
a.append(int(input()))
b=a[::-1]
print (b)
|
7450365995b6d160179a9d138e6fd927f1c8edaa | ShiJingChao/Python- | /PythonStart/Blackhorse/HM_Class/面向对象.py | 8,346 | 4.15625 | 4 | # 类:用来描述具有相同的属性和方法的对象的集合,
# 它定义了该集合中每个对象所共有的属性和方法,对象是类的实例
# class Persion(object):
# nick = 'limiao'
#
# def run(self):
# print("你会走路?")
#
# def song(self):
# print("你只会爬")
# a = Persion()
# a.run()
# a.song()
# 类 定义
# 定义类的语法规则:
# class 大驼峰法命名(父类):
# 属性 = 属性的值
# def 方法名(self):
# 方... |
188345ff8813e403de97070ee7b87ace456939fb | RichardDev01/MazeRunner | /mazerunner_sim/envs/maze_generator.py | 3,876 | 3.984375 | 4 | """Generator for a maze for the envirement."""
# Maze generation using recursive backtracker algorithm
# https://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_backtracker
from queue import LifoQueue
from random import choice
from random import randint
from typing import Tuple
from PIL import Image
impor... |
06d7a94ea199955e4662e0337c5eb37b9c48ff62 | objarni/langames | /src/table_builders.py | 2,100 | 3.84375 | 4 | class HtmlTableBuilder:
"""Produces HTML table code to be inserted into a larger HTML document"""
def __init__(self):
self.rows = []
def set_headers(self, column_headers):
self.headers = column_headers
def add_row(self, cells):
self.rows.append(cells)
def get_html(self):
... |
cb691085e825c0a5b0a1e1347666daa88ae0c509 | Ads99/python_learning | /Bitbucket Python Lessons/lesson8.py | 698 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Lesson 8
Pulling data from a Microsoft SQL database
"""
from pandas import DataFrame, date_range, concat
import pandas as pd
import sys
from sqlalchemy import create_engine, MetaData, Table, select
'''
Version 1
In this section we use the sqlalchemy library to grab data from a sql databas... |
fe8a977e976ad65f621fcd2ec6a1602d6b9f8c0a | Aasthaengg/IBMdataset | /Python_codes/p02952/s457740316.py | 245 | 3.8125 | 4 | def readinput():
n=int(input())
return n
def main(n):
count=0
for i in range(1,n+1):
if(len(str(i))%2==1):
count+=1
return count
if __name__=='__main__':
n=readinput()
ans=main(n)
print(ans)
|
4a9fef432427ba0b1b8b24e5461c422ac63316c3 | topDreamer/PyTorch-MRCToolkit | /pytorch_mrc/nn/similarity_function.py | 8,383 | 3.5 | 4 | """
This module implements the two matrices similarity calculation.
Here we assume input shape is ``(batch_size, seq_len1, dim1)` and ``(batch_size, seq_len2, dim2)`, and
we will return output whose shape is ``(batch_size, seq_len1, seq_len2)``.
"""
import torch
import torch.nn as nn
import math
class CosineSimilari... |
5b7b2bfc34316dc863ea43773c2fa0c46b8ae5b6 | thomasnield/oreilly-strata-london-2020-ml-spark-sklearn | /section_ii_preprocessing/2_3_normalization_sklearn.py | 881 | 3.9375 | 4 | import pandas as pd
from sklearn.preprocessing import Normalizer
'''
We can also use normalization which is slightly more complicated.
This rescales the input variables so the resulting vector has a length of 1.
For example, for a point (x1,x2) has a given value (2,2),
this would be transformed to (.70710678, .7071... |
9c5d15606f9bc9b4d63c839bb66fed0671d46cb1 | pythonCore24062021/pythoncore | /HW/homework06/rrasi/task6.py | 689 | 4.15625 | 4 | #У другому списку зберегти індекси парних елементів першого списку. Наприклад,
#якщо дано список зі значеннями 8, 3, 15, 6, 4, 2, то другий треба заповнити значеннями 1, 4, 5, 6
#(або 0, 3, 4, 5 - якщо індексація починається з нуля),
#оскільки саме в цих позиціях першого масиву стоять парні числа.
mylist = [8, 3, 15, 6... |
302b5f20e7fceed5dadd292678088dd727b265bb | joel35/challenges | /263/islands.py | 1,678 | 4.28125 | 4 | def count_islands(grid):
"""
Input: 2D matrix, each item is [x, y] -> row, col.
Output: number of islands, or 0 if found none.
Notes: island is denoted by 1, ocean by 0 islands is counted by continuously
connected vertically or horizontally by '1's.
It's also preferred to check/mark the vis... |
2695e2aa290da28a224eb3f987b8b4e8741a095c | bopopescu/VS2017_GIT | /test_1.1/test_1.1/file_test.py | 1,296 | 3.828125 | 4 | def file_open(filename):
try :
with open (filename,'r+')as file_object:
msg=file_object.read()
print (msg.rstrip())
return msg
except FileNotFoundError:
print ("无法找到文件"+filename)
def file_add_write(filename,add_msg):
file_msg=file_open(filename)
file_m... |
d16e128b612e871b0578bbc863626bdef64feeff | AdamZhouSE/pythonHomework | /Code/CodeRecords/2308/60870/284319.py | 1,602 | 3.578125 | 4 | class Node:
def __init__(self, item, lf=None, rg=None, nextNode=None):
self.next = nextNode
self.item = item
self.lf = lf
self.rg = rg
class Tree:
def __init__(self, root):
self.root = root
def middle_travel(self):
if self.root is None:
return [... |
48e437e41ce782afb7d0c0fda7267eea70716e77 | yonus/sparkStudyPython | /L8_2.py | 1,506 | 3.53125 | 4 | import tensorflow as tf;
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt;
import numpy as np
sess = tf.InteractiveSession()
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
a = tf.Variable(1,name="a")
b = tf.Variable(2,name="b")
f = a + b;
init = tf.global_varia... |
ba0b9e2461d1e9f337bfb20fc0879268744e5be1 | balta2ar/scratchpad | /myleetcode/020_valid_parentheses/20.valid-parentheses.py | 1,712 | 3.90625 | 4 | #
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# https://leetcode.com/problems/valid-parentheses/description/
#
# algorithms
# Easy (35.68%)
# Total Accepted: 526.8K
# Total Submissions: 1.5M
# Testcase Example: '"()"'
#
# Given a string containing just the characters '(', ')', '{', '}', '[' a... |
c845a016ed5d4a1928fba4c68ca0213e601713d5 | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Tutorial/Chapter 9. Classes/9.6. Private Variables/Mapping.py | 1,281 | 3.71875 | 4 | class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update # private copy of original update() method
class MappingSubclass(Mapping):
... |
5d94ee32d2f13dd3088229a40508eabfef487aa3 | lpham4/PythonPractice | /NextMeeting.py | 976 | 4.34375 | 4 | # Class: 1321L
# Section: 02
# Term: Fall 2018
# Instructor: Professor Malcolm
# Name: Ly Pham
# Lab: Python
day = int(input("Enter today's day: "))
days = int(input('Enter days until meeting: '))
if day == 0:
print('Today is Sunday')
elif day == 1:
print('Today is Monday')
elif day == 2:
print('Today is... |
dc980d7fd99f6daf80f33c964a88d85a5392261c | BDialloASC/AllStarCode | /Loopy.py | 117 | 3.765625 | 4 | #Some practice with loops
i=0
while i:
print(i)
j = i
while j<3:
print (j)
j+=1
i+=1 |
9357a8b9173a22715f39db4f1d53d91a9ee40126 | epuriprakash123/permutations | /num.py | 115 | 3.5625 | 4 | from itertools import permutations
n=list(input())
l = list(permutations(n,len(n)))
for i in l:
print(''.join(i))
|
77466526e3c9c86054d8414c77f2e53871859090 | ian-njuguna11/Stress-management-chat-bot | /gui.py | 494 | 3.8125 | 4 | from tkinter import *
import tkinter as tk
r = tk.Tk()
def send():
send = "You => "+ e.get()
txt.insert(END,"\n"+send)
if e.get() == "hello":
txt.insert(END, "\n" + "Counsellor => Hello")
e.delete(0,END)
txt = Text(r,bg = "green")
txt.grid(row=0,column=0,columnspan=2)
e=Entry(r,... |
bfc0708103e30801f2a49620568c57dd40e945bd | AdamZhouSE/pythonHomework | /Code/CodeRecords/2899/39200/301615.py | 158 | 3.671875 | 4 | x = int(input())
def func(x):
if x == 1:
return "true"
elif x < 1:
return "false"
else:
return func(x / 4)
print(func(x))
|
339e5674affbc0dc5a19b43fc6a5c0ce7aacc4ce | jawad1505/SoftwareEngineering | /Stacks/balance_brackets.py | 762 | 3.859375 | 4 |
from stack import Stack
def is_matched(b1, b2):
if b1 == "(" and b2 ==")":
return True
else:
return False
def brackets_balanced(my_str):
s = Stack()
is_balanced = True
index = 0
while index < len(my_str) and is_balanced:
paren = my_str[index]
if paren == "... |
7aee5e6261a69d20d7ee543ff23e0c7acc731d82 | chowdhurykaushiki/python-exercise | /PracticePython/Exercise9.py | 883 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number, then tell them whether they guessed too low,
too high, or exactly right.
Extras:
Keep the game going until the user types “exit”
Keep track of how many guesses the user has taken, and when th... |
6b098767cded28d5e1bb8dae58172ca639131834 | cdalsania/python-challenge | /PyBank/main.py | 2,801 | 3.734375 | 4 | #Importing the necessary modules/libraries
import os
import csv
#csv_file = os.path.join('folder_name', 'file.csv')
csvpath = os.path.join('Resources', 'budget_data.csv')
#define variables as integers
total_months = 0
total_profit_or_loss = 0
month_change_profit_or_loss = 0
prior_month_change_profit_or_loss = 0
first... |
226476ee605d5c0e191c6543dd39e5647fc29e98 | M0Rph3U56031769/commondtools | /commondtools/filehandling/csvreader.py | 1,126 | 3.734375 | 4 | import csv
class Reader:
file: str = None
delimiter: str = ','
def __init__(self, file: str, delimiter: str = ','):
self.file = file
self.delimiter = delimiter
def read(self):
csv_header: list = []
with open(file=self.file, mode="r") as csv_file:
csv_read... |
bc6cdd6374cd7c87bce380e22f606f88a4dab258 | eliecer11/Uip-prog3 | /Tareas/tarea4/programa4.py | 322 | 3.609375 | 4 |
chance = 0
minutos = 0
while chance < 10:
tiempo = int(input("Introduzca el tiempo en minutos: "))
chance +=1
if tiempo / 60:
dias = 24 - tiempo % 24
horas = 8 - tiempo % 8
minutos = 60 - tiempo % 60
print(dias)
print(horas)
print(minutos)
... |
ba8c55e8efeed1ece197edb8783b52963a727516 | dankodak/Programmierkurs | /Abgaben/Blatt 1/Aufgabe 3/Team 41411/Ben Romdhane_Houssem_HoussemBenRomdhane_755653/Aufgabe3_HoussemBenRomdhane.py | 487 | 3.625 | 4 | summand1 = int(input("Zahl 1: "))
summand2 = int(input("Zahl 2: "))
length_summand1 = len(str("{:b}".format(summand1)))
length_summand2 = len(str("{:b}".format(summand2)))
length_binary_sum = len(str("{:b}".format(summand1+summand2)))
print()
print(" "*(length_binary_sum-length_summand1+2)+str("{:b}".format(summand1)))... |
9119a1d9abf0063b7a3223a48b1460d8290de8f2 | herjh0405/Coding_Test | /Chapter5. DFS&BFS/5-5. 2가지 방식으로 구현한 팩토리얼 예제.py | 1,015 | 3.65625 | 4 | # 컴퓨터 내부에서 재귀 함수의 수행은 스택 자료구조를 이용한다.
# 함수를 계속 호출했을 떄 가장 마지막에 호출한 함수가 먼저 수행을 끝내야 그 앞의 함수 호출이 종료되기 때문이다.
# 재귀 함수는 내부적으로 스택 자료구조와 동일하다는 것을 기억하자.
# 반복적으로 구현한 n!
def factorial_iterative(n):
result = 1
for i in range(1, n+1):
result *= i
return result
# 재귀적으로 구현한 n!
def factorial_recursive(n... |
b02588ec05d93f4d6a6cc007662d3af161348065 | nandwanarohan/Python | /Longest Substring.py | 476 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 30 17:58:22 2018
@author: HP PC
"""
s = " dfabhdfsaebjggdfgsdghsrgsergaefr"
maxlen = 0
current = s[0]
longest = s[0]
for i in range(len(s)-1):
if s[i+1] >= s[i]:
current += s[i+1]
if len(current) > maxlen:
maxlen = len(curre... |
2169cfa4dfe95f9226a26b48fd6bda9483008642 | infomuscle/algorithms-leetcode | /leetcode-python/86. Partition List.py | 1,107 | 3.53125 | 4 | # 제출 코드 - Runtime 85.36 Memory 98.41
class Solution:
def partition(self, head, x: int):
if not head:
return head
partition1, head1 = None, None
partition2, head2 = None, None
current = head
while current:
if current.val < x:
if not hea... |
8c8c33591711fa474f9cfab92348a7e36d0f98a1 | rogcomfox/python | /python/latihan/palindrom.py | 175 | 3.75 | 4 | a = int(input())
for b in range(a):
b = input()
for i in b:
if b(chr(i)) == b(chr(-i)):
print("Palindrom")
else:
print("Bukan") |
ebe16d4f339952c6661434104ffa18b46bf9b015 | windmzx/pyleetcode | /543. Diameter of Binary Tree.py | 777 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
res = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def helper(root):
if root is None:
return ... |
06d785a3a0e0f9409b8118079aaf5c68e64c5ccf | amaljyothicollegeaes/S1-A-JILSE-JACOB-43 | /PYTHON PROGRAMING LAB/27-1-2021/3b.square of N numbers.py | 365 | 3.96875 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> list=[5,6,7,8,9,10]
>>> for x in list:
square=x*x
print(x," square is ",square)
5 square is 25
6 square is 36
7 square is 49
8 square is... |
1ebf251f35c811d579ee866a78b311a40fda63ed | mswift42/project-euler-2 | /euler56.py | 611 | 3.828125 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
"""Powerful digit sum
Problem 56
A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of ... |
0a323514f89d6f3d0566421226d6c48be96f4255 | jeffakins/numpy_pandas_visualization_exercises | /pandas_series.py | 10,148 | 4.3125 | 4 | # Pandas Exercises
import pandas as pd
fruit_series = pd.Series(["kiwi", "mango", "strawberry", "pineapple", "gala apple", "honeycrisp apple", "tomato", "watermelon", "honeydew", "kiwi", "kiwi", "kiwi", "mango", "blueberry", "blackberry", "gooseberry", "papaya"])
# Type and output of the fruit_series
type(fruit_serie... |
b7ee6c535ba1581733949b56c78ed67c013189f9 | thiagomess/pyhton | /OO2/Heranca.py | 1,442 | 3.90625 | 4 | class Funcionario:
def __init__(self, nome):
self.nome = nome
def registra_horas(self, horas):
print('Horas registradas...')
def mostrar_tarefas(self):
print('Fez muita coisa...')
class Caelum(Funcionario):
def mostrar_tarefas(self):
print('Fez muita coisa, Caelumer')... |
8e9a404e65491f0a4c5799f7be378ef0cfc55453 | EsC369/CodeSignal_Python_3_Algorithms | /Plant_Growing.py | 873 | 4.6875 | 5 | """
Each day a plant is growing by upSpeedmeters. Each night that plant's height decreases by downSpeed meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level.
Example
For upSpeed = 100, ... |
361274373e370ab7fb4212d73edb0730e6164cc2 | pcakhilnadh/Cryptography | /Ciphers/MONOALPHA.py | 246 | 3.859375 | 4 | cipAlp=list(map(str,input("Enter CipherText Alphabet").split()))
plainText=str(input("Enter Plain Text:"))
plainText=str.upper(plainText)
print("Cipher Text:",end='')
for v in plainText:
ind=ord(v)-ord('A')
print(cipAlp[ind],end='') |
bf37599490bc753845d0bafdf6a984828a9a8d1d | suzanneloures/recpoints | /model/route.py | 1,693 | 3.546875 | 4 | # coding=utf-8
class Route:
def __init__(self,googleRoute,pois):
self.google_route = googleRoute #rota inicial google
self.pois = pois #pontos de interesse
self.route_with_waypoints = False
self.scores = [] #scores das predições
self.final_score = 0.0 #score final (apos a a... |
38a8a817dd40ad8059ace90772207d89208a14f0 | GCleuziou/IntroPythonUNC | /source/exercicesDefiCode/SousChaine.py | 573 | 3.671875 | 4 | entrees_visibles = [
("program","J'aime la programmation"),
("programme","J'aime la programmation"),
("","bonjour"),
]
entrees_invisibles = [
("Jaime","la vie est belle"),
("elle","la vie est belle"),
("elle","la viell est belle"),
("la vie","la vie est belle"),
("belles","la vie est belle"),
("telle","la vie ... |
919b441584e5ef1fea53ff08b60c6859320c1c3b | gittygitgit/python-sandbox | /sandbox/practicepython/e12.py | 330 | 4.09375 | 4 | #!/usr/bin/python
'''
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
'''
l = [5,10,15,20,25]
result=[]
result.append(l[0])
result.append(l[len(l) - 1])
prin... |
cb9fd4bd99a6ba5fbf6ecaa7c0bb67ae2a0ae748 | huangqiank/Algorithm | /leetcode/other/findCelebrity.py | 1,841 | 3.640625 | 4 | # 假设你是一个专业的狗仔,参加了一个 n 人派对,其中每个人被从 0 到 n - 1 标号。
# 在这个派对人群当中可能存在一位 “名人”。所谓 “名人” 的定义是:其他所有 n - 1 个人都认识他/她,而他/她并不认识其他任何人。
# 现在你想要确认这个 “名人” 是谁,或者确定这里没有 “名人”
# 。而你唯一能做的就是问诸如 “A 你好呀,请问你认不认识 B呀?” 的问题,
# 以确定 A 是否认识 B。你需要在(渐近意义上)尽可能少的问题内来确定这位 “名人” 是谁(或者确定这里没有 “名人”)。
# 在本题中,你可以使用辅助函数 bool knows(a, b) 获取到 A 是否认识 B。请你来实现一个函数 int f... |
04a8e3d040e94f90333fea121b7c3543f7c6f1cf | jeongm-in/UVACS1110- | /Jihoon/crypto.py | 3,845 | 4.1875 | 4 | import string
def shift(text, key):
"""adds key to every letter in text, where a = 0, b = 1, etc.
Wrap around if you reach the end: z + 1 = a.
Don’t change non-letters.
Preserve case"""
answer = ''
for character in text:
if character.isupper():
index = string.ascii_uppercas... |
208845d7ffbcc38362b0b245b2d0d34b7add8ea4 | ddh/leetcode | /python/reverse_linked_list.py | 2,469 | 4.15625 | 4 | """
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
"""
# Idea:
# For iteratively, we'll load each node in the array. Then we'll iterate from both ends of the array tow... |
d287800fec7b0e959d6148d203b70031855d56a0 | Chrispresso/Artificial-Intelligence-Reinforcement-Learning-in-Python | /tic_tac_toe.py | 13,424 | 3.953125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from typing import Tuple
LENGTH = 3 # Height/Width of board
class Environment(object):
def __init__(self):
self.board = np.zeros((LENGTH, LENGTH))
self.x = -1 # Represents 'x' on the board
self.o = 1 # Represents 'o' on the board
... |
650eeb051e25ee1207d15c5f4c9513c270ae176b | yinyinyin123/algorithm | /数组/majorityElement.py | 1,220 | 3.546875 | 4 |
### one code one day
### 2020/03/13
### leetcode 169 多数元素
### 投票法
def majorityElement(self, nums: List[int]) -> int:
count = 0
majority = 0
for num in nums:
if(count == 0):
count = 1
majority = num
else:
if(num == majority):
count += 1
... |
b31d9c315f41e0e61f033aeb504b74433e28e2f8 | alexjercan/algorithms | /old/hackerrank/ai/saveprincess.py | 601 | 3.734375 | 4 | #!/usr/bin/python
def displayPathtoPrincess(n, grid):
# print all the moves here
if grid[0][0].lower() == 'p':
dir_1 = "LEFT"
dir_2 = "UP"
elif grid[-1][0].lower() == 'p':
dir_1 = "LEFT"
dir_2 = "DOWN"
elif grid[0][-1].lower() == 'p':
dir_1 = "RIGHT"
dir_... |
533e148a9dece47185c4551aa0af285cc2c7373f | mikeghen/snap-eligibility-estimate | /household_size_pdfs.py | 1,207 | 3.625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import simulator
"""
Work in progress
STEP 1: Produce the Income PDF for a county from the US Census data
"""
income_pdf, n = simulator.get_incomes_pdf(42, 101) # Philadelphia
"""
STEP 2: Produce the normally distributed PDF for a household size
... |
ffba3e8f6bb32a6db8288f2d52fecab476366741 | watsyurname529/significant-digits-soup | /prototype/extract_digits.py | 1,048 | 3.78125 | 4 | #!/usr/local/bin/python3
#Python code to do data wrangling / formatting from raw data files from the
#webscraper code.
import re
import locale
import json
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
#json_file = input('Enter a JSON database file: ')
json_file = '../digits.json'
with open(json_file, 'r') as f... |
76c36f605e559ec2f1e6477ebb6bd6725f5d4c44 | joe-arriaga/portfolio | /spark_python/22-most-popular-movie/most-popular-movie.py | 799 | 3.703125 | 4 | # most-popular-movie.py
# Auust 4, 2020
#
# Sort the MovieLens database by popularity. Which movie was watched most often?
# That is, which movie(ID) appears most often in the data set?
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster('local').setAppName('MoviePopularity')
sc = SparkContext(co... |
9afd8cfd72923db5e2864ab27935eccb6873ec6b | afusco059/what_to_eat | /food/food.py | 2,900 | 3.703125 | 4 | import random
chinese_food = ["House of China", "Imperial Garden", "Golden Hunan", "Main Moon", "Chinatown Inn",]
Buffet_food = ["Royale Grill", "Golden Corral", "Ponderosa"]
japanese_food = ["Izumi", "Mizu", "Tokyo House", "Sakura", "Asuka"]
mexican_food = ["Plaza Mexico", "Los Gallos", "Jalisco's"]
pizza_food ... |
d57f3ffa5724ff541d10ec088b3de03f197b9971 | scorum/scorum-py | /scorum/graphenebase/amount.py | 6,422 | 3.703125 | 4 | class Amount(dict):
""" This class helps deal and calculate with the different assets on the
chain.
:param str amount_string: Amount string as used by the backend
(e.g. "10 SCR")
"""
def __init__(self, amount_string="0 SCR"):
self._prec = 9
if isinstance(amou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.