blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e592dd3761457d02d7b4d83ce2adfa76ac52a6fc | linuxergr/Advanced-Python-Mathesis | /code/Week 4/stringvar.py | 824 | 3.75 | 4 |
# StringVar
import tkinter as tk
class MyApp():
def __init__(self, root):
self.r = root
self.myText = tk.StringVar()
self.myText.set(30*' ')
self.mylabel = tk.Label(self.r, textvariable = self.myText, width=30,
font="Arial 20")
self.mylabel.p... |
7e17f2fbaa313dd2e7329527e95b42809b29ecfc | 00agata/PythonLearning | /Lesson2/KnightMoves.py | 713 | 3.671875 | 4 | def firstCond(first_vertical, first_horizontal, second_vertical, second_horizontal):
return abs(second_vertical - first_vertical) == 2
def secondCond(first_vertical, first_horizontal, second_vertical, second_horizontal):
return abs(second_horizontal - first_horizontal) == 1
first_vertical = int(input('Pleas... |
7d4c846e221113f3d0a77c88f1753f54de0e6d72 | G00398275/PandS | /Week 08/Lab-8.7_scatter.py | 539 | 3.71875 | 4 | # Lab 8.7; scatter.py
# This program plots a scatter plot of the salaries in salaries.py
# Author: Ross Downey
import numpy as np
import matplotlib.pyplot as plt
minSalary = 20000
maxSalary = 80000
numberOfEntries = 10 # specifying min, max and how many numbers needed
np.random.seed(1) # ensures "random" array calle... |
08b56e2880a2b08205f21977d52061bb92026ccc | shreeyamaharjan/Assignment | /Functions/QN10.py | 309 | 4.03125 | 4 | def even_numbers(num):
x=[]
for i in num:
if i%2 ==0:
x.append(i)
return x
n=int(input("Enter size of list : "))
lst=[]
print("Enter the list of items:")
for i in range(n):
a=int(input())
lst.append((a))
print(lst)
print ("The even numbers are :",even_numbers(lst))
|
70b15a9e14b7af3db57a05cd4aaa139bcc35e5af | unfoldingWord-dev/d43-catalog | /libraries/tools/date_utils.py | 1,111 | 3.671875 | 4 | import arrow
import time
def unix_to_timestamp(timeint):
"""
Converts a unix time value to a standardized UTC based timestamp
:param datestring:
:return:
"""
if timeint == None:
return ''
d = arrow.get(timeint).to('local').datetime
return d.isoformat()
# datetime.datetime.fr... |
a9147cc5926f65a17973dd10291d565921622151 | neighbor983/tic_tac_toe | /human_player.py | 1,342 | 3.546875 | 4 | from player import Player
from board import Board
from typing import List
class HumanPlayer(Player):
def __init__(self, symbol):
super().__init__(symbol=symbol)
def make_move(self, board: Board) -> int:
available_squares = board.openSquares()
print(board)
while True:
... |
16815725c7b23a6c72e22643655e5a230d2ef6da | davll/practical-algorithms | /HackerRank/list/cycle_detection.py | 477 | 3.828125 | 4 | # https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle/problem
# Hint: Floyd's Tortoise and Hare
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def has_cycle(head):
if not head:
return False
slow, fast = head, head
... |
4eae039073403284e9391a7e9232743d2b9fa0ab | mmore21/ds_algo | /python/tests/test_insertion_sort.py | 593 | 3.890625 | 4 | import unittest
from lib.insertion_sort import insertion_sort
class InsertionSortTest(unittest.TestCase):
def setUp(self):
self.arr = []
def test_insertion_sort(self):
# Already sorted
self.arr = [1, 2, 3, 4, 5]
self.assertEqual(insertion_sort(self.arr), [1, 2, 3,... |
556d69cf1bf78e1f5015af83ab415ecb978c8deb | vicwuht/pl-hd | /learning/compare.py | 549 | 3.953125 | 4 | """函数conpare用来比较xy的大小"""
def compare(x, y):
"""
compare函数比较xy大小
:param x:
:param y:
:return: 1,0,-1
"""
if x > y:
return 1
elif x == y:
return 0
else:
return -1
# x = input('请输入X值:\n')
# y = input('请输入Y值:\n')
# print(compare(x, y))
def is_between(x, y, z):... |
c38846ae21cee40374c962a75500cca7b3df74e7 | LFBianchi/pythonWs | /mandosBot/dbHandler.py | 1,334 | 3.734375 | 4 | import sqlite3
def dbConnection():
conn = None
try:
conn = sqlite3.connect('mandosBot.sqlite')
except:
print('Failed to connect to database.')
return conn
conn = db_connection()
def createQuery(author, para, de, dmy1, dmy2 = None, price = 0):
cursor = conn.cursor()
sql = """IN... |
ff723c48cd6e84d4a995f27651832604f0cb4654 | Svens1234/operator_while | /main.py | 676 | 4.03125 | 4 | #x = 5
#while x >= 1:
#print(x)
#x = x-1
#x=5
#while x < 10:
#print(x)
#x = x+1 # x+=1
#x = 5
#while x <10:
#print(x)
#x+=2
#print('Next code')
#x=0
#while x<10:
#print('x is less than 10')
#x+=1
#else:
#print('x now is not less than 10')
#for x in range(10):
#print(str(x) ... |
5c47c7eb8adb7be931f2fb6eb12b04eb9b8205d4 | Alex-Khouri/Movie-Archive-with-Database-Repository | /getflix/domainmodel/watchlist.py | 2,506 | 3.53125 | 4 | class Watchlist:
def __init__(self, arg_user_code, arg_movies=None, arg_movie_codes="", arg_code=None):
self.watchlist_user_code = arg_user_code
self.watchlist_code = str(hash(self.watchlist_user_code)) if arg_code is None else arg_code
self.watchlist_movies = list() if arg_movies is None else arg_movies
... |
d80f214173d2e9544a21da401b0cad021656236d | schoef/fun | /python/IPD/arena/Torus.py | 1,499 | 3.578125 | 4 | ''' Implements toric arena, i.e. rectangle with periodic boundary conditions
'''
import abc
from ArenaBase import ArenaBase
from helpers.memoize import memoize
class Torus( ArenaBase ):
def __init__( self, nx = 10, ny = 10):
''' Initialize toric arena
'''
self.nx = nx
self.ny = ... |
8705e1877cd0e6585788f9a078cbd448661c8de0 | Rezervex/2019 | /You turn 100 on.py | 251 | 3.96875 | 4 | Name = str(input("What is your name: "))
Age = int(input("How old are you: "))
cYear = int(input("What year is it: "))
fYear = cYear + (100 - Age)
SfYear = str(fYear)
print("Hi " + Name + "." + "You will be turning 100 in the year " + SfYear + ".")
|
d47c8ee14a325a180d07bf9022751ad43e45e2aa | CodeForContribute/Algos-DataStructures | /GraphCodes/cloningUndirectedGraph.py | 1,612 | 3.578125 | 4 | from collections import defaultdict
class GraphNode:
def __init__(self, data):
self.data = data
self.neighbors = []
def CloneGraph(src):
hash_map = dict()
q = list()
q.append(src)
node = GraphNode(src.data)
hash_map[src] = node
while len(q):
p = q.pop(0)
n... |
ea2c9670bf41e6f77a705bfba92878a860fcbf2e | anupm12/data-structures | /queue/priorityQueue.py | 1,439 | 3.75 | 4 | class queue:
def __init__(self, size):
self.size = size
self.queue = [None] * self.size
self.count = 0
self.front = 0
self.rear = 0
def print(self):
temp = self.front
for i in range(self.count):
print(self.queue[temp])
temp+=1
... |
2e76b640f03f32476270f4ef5dc00284c5c87ac2 | omitiev/python_lessons | /python_tasks_basics/general_tasks/task_7-8.py | 1,602 | 4.09375 | 4 | # Преобразовать строку с американским форматом даты в европейский. Например, "05.17.2016" преобразуется в "17.05.2016"
print ("==========================================================")
print ("task 7")
print ("==========================================================")
us_date = str(input("Please, enter a date in... |
375f53b6487cc18805c027a6cc151f5a812fed9f | rupaku/codebase | /python basics/higherOrderFunc.py | 710 | 4.25 | 4 | '''
A function is called Higher Order Function if it contains other functions
as a parameter or returns a function as an output i.e, the functions that
operate with another function are known as Higher order Functions.
'''
#Function as object
def shout(text):
return text.upper()
print(shout('hello'))
x=shout
prin... |
73c62e7265c481a53db61e86ebf57ad22736d63a | chadm9/python-basics | /work_or_sleep_in.py | 248 | 3.859375 | 4 | day = int(input('Day (0-6)? '))
dayKey = {0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday'}
if dayKey[day] == 'Saturday' or dayKey[day] == 'Sunday':
print 'Sleep in'
else:
print 'Go to work'
|
d329646b9c37d2d03bf4a1decccf6876e698030f | may2991/HW_python1 | /lesson4_2.py | 886 | 4.125 | 4 | # Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
# Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор.
# Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
... |
22f2527d427d57304009ec6e42d0e056a29b4a33 | songdanlee/python_code_basic | /day01/practice_1/my_code_number.py | 644 | 3.796875 | 4 | # int 类型
print(type(10), 10)
#float 类型
print(type(10.0), 10.0)
#bool
print(type(True), True)
print(type(False), False)
# int + True ,自动转型,级别低的向级别高的的类型转换
print(10 + True)
print(10 + False)
print(10.0 + False)
#数值强制转换为bool
print(bool(0))
print(bool(1))
print(bool(0.0))
print(bool(1.1))
# bool转为浮点类型
print(float(True)... |
049eadfb622c7404198373cdfa9073da24582413 | Del-virta/goit-python | /lesson3/fibonacci.py | 380 | 3.953125 | 4 | def main():
n = int(input("Введите положительное целое число: "))
return n
def fibonacci(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n-2)+fibonacci(n-1)
if __name__ == '__main__':
n = main()
print(f"{n}-й член ряда фибоначчи равен: {fibonacc... |
b813bbdf9924e86f0dc7f94cb29b76d5942f2cef | liyuhuan123/Learnselenium | /pythonStudy/面向对象.py | 3,549 | 4.09375 | 4 | class MyClass:
i = 132
def fun(self):
return 'hello world!'
def __init__(self):
self.data = []
# 实例化类
x = MyClass()
print(x.i) # 132
print(x.fun()) # hello world!
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.... |
f921f2fe5a5b9814e8c7c03a982f0b099f98038c | jjlumagbas/cmsc124 | /12-expressions.py | 66 | 3.640625 | 4 |
x = 5
if (x = 5):
print("True")
else:
print("False :(")
|
ea733356803e1ea9cdeccc7a9a9da68601df3b70 | marcinpgit/Python_exercises | /Exercises_1/krotka elementy wyposazenia.py | 492 | 3.828125 | 4 | inventory = ()
if not inventory:
print ("Masz puste ręce.")
input ("\nAby kontynuować naciśnij klawisz Enter.")
inventory = ("miecz",
"zbroja",
"tarcza",
"napój uzdrawiający")
print ("\nWykaz zawartości krotki: ")
... |
3872a8cb98760e976a42f42993eb2011126c4516 | katewen/Python_Study | /study_1.py | 425 | 3.515625 | 4 | import re
from urllib.request import urlopen
from urllib.parse import urlencode
def getWithUrl(url):
res = urlopen(url)
def postWithUrl(url):
data = {'name': 'erik', "age": '25'}
s = urlencode(data)
res = urlopen(url, s.encode())
print(res.read().decode())
def getHTMLContent(url):
res = urlop... |
5e86411725dec00e620638a988fc608430a2d86c | 20130353/Leetcode | /target_offer/二分+双指针+滑动窗口/连续子序列的最大值的最小值.py | 634 | 3.71875 | 4 | # 输入一个序列判断所有长度为k的连续子序列中的最大值中的最小值。
# 每个连续子序列中都有一个最大值,所有最大值的最小值。
# 解题思路:滑动窗口找到长度为k的子序列(同时移动左右边界就可以模拟窗口了),保存最大值就找到最小值了。
def solution(arr, k):
i, j = 0, k
min_value = float('inf')
while j <= len(arr):
min_value = min(min_value, max(arr[i:j]))
i += 1
j += 1
return min_value
if __n... |
7f6235f1d8b178d532c8dbe3c04210b8bdacba46 | geo-gkez/basic-exercises-python | /for_loop_continueVsPass.py | 209 | 3.5625 | 4 | for i in 'hello':
if(i == 'e'):
print('pass executed')
pass
print(i)
print('----')
for i in 'hello':
if(i == 'e'):
print('continue executed')
continue
print(i) |
480c8dca4971558b9bc057f3a3afb2ca052a3c32 | Sheersha-jain/Tree | /leaf-node.py | 857 | 4.15625 | 4 | # find total number of leaf node in binary tree.
class Root:
def __init__(self, value):
self.left = None
self.right = None
self.key = value
def leafnode(parent_node):
if parent_node is None:
return
leaf_node = 0
q = []
q.append(parent_node)
while(len(q)):
... |
785763cf423784695854b2cb3e8798eaa764c7ca | tegetege/tegetege_AtCoder | /Practice/ABC/Bcontest009_a.py | 109 | 3.53125 | 4 | import sys
N = int(input())
if N % 2 == 0:
print(int(N/2))
sys.exit()
else:
print(int(N/2)+1)
sys.exit() |
eaedda306343f4ae9258c995a9dc32a852069f80 | felix-schneider/tensorflow-transformers | /merge_vocabulary.py | 526 | 3.796875 | 4 | # coding=utf-8
# Merge two vocabulary files into one, without duplicating words that are present in both
#
# Usage: python merge_vocabulary.py {vocab1} {vocab2} > {out_file}
import sys
vocabulary = dict()
for line in sys.stdin:
word, count = line.split(" ")
count = int(count)
if word in vocabulary:
... |
edc3dd637ad1ea782284ef7e5c73564fc4feff85 | sejin423/Library | /함수/변환, 연산.py | 884 | 3.546875 | 4 | # 변환
a = int(input())
print('%x' %a) # 10진수 -> 16진수_소문자
print('%X' %a) # 10진수 -> 16진수_대문자
b = input()
n = int(b,16) # 입력된 b를 16진수로 변환
print('%o' %n) # 16진수 -> 8진수
# ord()는 문자를 유니코드 값으로 변환
c = ord(input()) # 문자 -> 10진수 변환
print(c)
#chr()는 정수를 유니코드 문자로 변환
d = int(input())
print(chr(c)) # 정수 -> 유니코드... |
8c71b2ea3cc1f3df7a9e22ac005d4b6a1c6408ec | ankitsoni5/python | /course_python/Python/search_student.py | 1,073 | 3.859375 | 4 | from com.ankit.collage.student import Student
'''
# It is using list.
slist = [
Student(name='Ankit', gender='M', roll=1, marks=90),
Student(name='Soni', gender='M', roll=2, marks=80),
Student(name='Anjani', gender='F', roll=3, marks=70)
]
roll_no = int(input('Enter the roll number: '))
#studen... |
b6d8f2df4289fd03436658a908fd0969c8bdfbcd | eet172291/assignment-8 | /ps2.py | 1,768 | 3.78125 | 4 | ###### this is the second .py file ###########
####### write your code here ##########
######Code for problem 2######
import numpy as np
#Getting input from user
k= (input().split(" "))
#checking for boundry conditions
if len(k)!=3:
print("Wrong number of arguments")
exit()
for i in range(3):
k[i]= int(k[i])
i... |
e7fe790268c6971c4b3dfa3f5c677ecf28db94f1 | Cheater115/acmp | /Python/1006.py | 809 | 3.875 | 4 | section1 = input()
section2 = input()
section3 = input()
if section1 == 'black' and section2 == 'YELLOW' and section3 == 'black':
print('black', 'YELLOW', 'black', sep='\n')
elif section1 == 'black' and section2 == 'black' and section3 == 'green':
print('black', 'black', 'GREEN', sep='\n')
elif section1 == 'bl... |
32da2d6ba2960b31718b6f3386a7a9841600bcda | brunstart/coding_test | /BFS(Breadth first search).py | 594 | 3.578125 | 4 | graph_list = {1: set([2,3,4]),
2: set([1,5]),
3: set([1,6,7]),
4: set([1,8]),
5: set([2, 9]),
6: set([3, 10]),
7: set([3]),
8: set([4]),
9: set([5]),
10: set([6])}
root_node = 1
from collection... |
f50dc12a66138079fd980283a6d1f90ad325456e | nickayresdemasi/adventofcode | /code/2020/day_3_2020.py | 1,557 | 3.625 | 4 | from utils import parse_fname, read_input
def parse_input(input_str):
return [row for row in input_str.split('\n') if row != '']
class TobogganRun(object):
def __init__(self, grid):
"""Initializes TobogganRun object with a grid
Args:
- grid (list(str)): grid of trees (#) and ope... |
43eb04f5fd45488d8b4712ac0b73b773ac967fc4 | mrditter/Long-Project-3 | /unzip.py | 891 | 3.859375 | 4 | def unzip(compressed):
"'Unzips' the compressed stream"
final_string = ""
current_index = 0
string_index = 0
for i in compressed :
assert (type(i) == str) or (type(i) == tuple)
if type(i) == str :
assert len(i) == 1
if type(i) == tuple:
assert type(i[0... |
cd9a49c14ff422f6630e1b77a2f593744943b0fa | Ru8icks/old-ai | /A3/AstarX.py | 6,283 | 3.65625 | 4 | import assig3, pprint
offsets = (1, 0),(0, 1),(-1, 0),(0,-1)
COSTTABLE = [100, 50, 10, 5, 1, 0, 1]
solution_loc = None
class SearchNode():
g = 0 #cost to node
f = 0 #estimated total cost of a solution path going through this node; f = g + h
parent = "ROOT"
kids = []
status = "OPEN"
def __in... |
5a34f49e7976df91b41c8a9d072dd1e0e4ebcaf9 | xiaoxiaolulu/arithmetic | /Objects.py | 131 | 3.84375 | 4 |
num = 88
super_num = num
list_ = [1, 2, 3, 4, 5, 6, 7, 8]
print(list_.count(1)) # 访问器
list_.append(2) # 变形器
|
c15edff0f86a854a25bb65093807e5cd1237a241 | bihailantian/PythonPractice | /practice1/practice6.py | 550 | 4.21875 | 4 | #!/use/bin/env/python3
# -*- encoding: utf-8 -*-
"""
题目:斐波那契数列
程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。
"""
def fib(n):
'''
n是大于0的整数
'''
if n < 1:
print("n是大于0的整数")
return []
if n == 1:
return [1]
if n == 2:
return [1, 1]
fibs = [1, 1]
for i in range(2, n):
fibs... |
a1af89a93e4d33fc29070b7b9c6ae19d3e9af465 | rhondene/Analyzing-Sequencing-DNA-Reads | /Overlap between reads.py | 898 | 3.875 | 4 | #finds the minimum overlap between prefix of b in a, returns lenght of longest suffix
def overlap(a,b, min_length=3):
start = 0
while True:
start = a.find(b[:min_length], start ) #look in a for min prefix in b
if start == -1: #no occurence of b in a, reach last part of a -1
re... |
3328ef8a1764073dcc0a58d833bc5aca3951643e | kamal1491644/Codeforces-problems-solutions | /Python/Inverted Luck.py | 198 | 3.640625 | 4 | t=int(input())
for i in range(t):
new=''
string=input()
for i in string:
if i=='4':
new+='7'
elif i=='7':
new+='4'
print(new)
|
69d5c6339c7607a14193a437a0f0e6fa68daee33 | psycho-pomp/DSA-Workshop | /Week2/Mathematics/Learn/Trail.py | 125 | 3.796875 | 4 | # Abhishek Anand
# trailing zero's in factorial
n=int(input())
count=0
p=5
while p<=n:
count+=(n//p)
p*=5
print(count)
|
214c993613f116730f17f8409b6e2ade4384b62d | judeh20-meet/meetyl1201819 | /lab6.py | 816 | 3.84375 | 4 | from turtle import Turtle
import random
from turtle import *
import turtle
colormode(255)
class Square(Turtle):
def __init__(self, size):
Turtle.__init__(self)
self.shape("square")
self.shapesize(size)
def random_color(self):
rgb = (random.randint(0,256), random.randint(0,256), random.randint(0,256))
... |
46431e82174a7a27fab3f45b53aab2e803ec2d0b | OlegZhdanoff/python_basic_07_04_20 | /lesson_1_6.py | 739 | 3.734375 | 4 | def input_int(msg):
str = input(f'{msg}\n')
while True:
if not str.isdigit():
str = input('Ошибка! Введите целое положительное число\n')
continue
else:
return int(str)
a = input_int('Сколько километров пробежал спортсмен в первый день?')
b = input_int('Сколь... |
7dca791bdcbb0aad74cbfd00e194feb3601e7bba | xmy7080/leetcode | /canPlaceFlowers.py | 902 | 3.703125 | 4 | class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
if not n: return True
for i, x in enumerate(flowerbed):
if not x and (i == 0 or flowerbed[i-1] == 0) and (i == len(flowerb... |
5326b337bc0b56d4eb0a3e575b66b7214182e72f | mdegree-nedas/WA-slides | /others/knapsack/instance.py | 325 | 3.5625 | 4 | ##### knapsack instance: put here the instance data
# Items
# item i -> {p: profit, w: weight}
# IMPORTANT: the i of the items starts from 1
O = {
1: {"p": 1, "w":2},
2: {"p": 2, "w":4},
3: {"p": 2, "w":3},
4: {"p": 3, "w":5}
}
# total number of items
n = len(O)
# max capacity of knapsack
b = 5
... |
4acde286cc53c754c9dd54e20b7fcc0c52deb27a | ike97/usefulPythonScripts | /Mirror_A_Tree.py | 2,437 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 30 10:02:22 2019
Mirroring a Binary tree
@author: Ike Osafo
"""
#Mirror a tree
#This algorithm simply uses a post traversal to duplicate the tree
class Node(object):
def __init__(self, left=None, right=None, data=None):
self.left = left
self.right = ... |
cfd6be31631d3a9e42ca54d6d62c50007e4d8858 | Andrewmazyar/python-course-alphabet | /serialization/homework.py | 4,907 | 3.75 | 4 | """
Для попереднього домашнього завдання.
Для класу Колекціонер Машина і Гараж написати методи, які створюють інстанс обєкту
з (yaml, json, pickle) файлу відповідно
Для класів Колекціонер Машина і Гараж написати методи, які зберігають стан обєкту в файли формату
yaml, json, pickle відповідно.
Для класів Колекціонер М... |
2a159bba70e5a6eff76138b951d3ab6f8ed2a26b | samirad123/lab_lec5 | /task 3 h.py | 112 | 3.609375 | 4 | x = 5
y = 0
print("A")
try:
print("B")
a = x/y
print("C")
except:
print("D")
print("E")
print(a) |
a13582a4505d7068c31cfa6cf3ecbaca8dc64f1d | MrRuiChen/CHEN-RUI | /11 判断奇偶数.py | 177 | 3.890625 | 4 | # -*- coding: UTF-8 -*-
a=int(input('请输入一个数:'))
if (a%2)==0:
print('输入的数为偶数{0}'.format(a))
else:
print('输入的数为奇数{0}'.format(a))
|
dbcc74fc249960b96003e90fd914b5566bcd360f | sethips/python3tutorials | /ClassesObjects.py | 765 | 4.375 | 4 |
class Fish:
size = "large"
color = "white"
def swim(self):
print("the", self.size, self.color, "fish is swimming")
goldfish = Fish()
goldfish.swim()
goldfish.size = "small"
goldfish.color = "gold"
goldfish.swim()
class MarineCreatures:
""" class variables and instance variables differentia... |
4c13d69d006116b760c715b20d7a5a48bfeb2b0f | neeltron/Random-Number-Generator | /main.py | 795 | 4.21875 | 4 | # This is a random number generator that works on the basis of users' time in seconds and the time taken by the user to input the range in which they want the random number.
import time
from datetime import datetime
def random_func(num1, num2):
now = datetime.now()
cur = now.strftime("%S")
print(cur)
start ... |
c78da8bed0912d61fea1635868911eda8bb6b082 | gnidan/cs650 | /assn2/src/icode.py | 2,185 | 3.84375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
CS650
Kevin Lynch
Nick D'Andrea
Keith Dailey
icode.py represents the icode
"""
class ICode(object):
def __repr__(self):
return str(self)
class OpICode(ICode):
"""This is used to better categorize all of the Arithmetic Operation
instructions"""
pass
class Add(... |
089b42eebe81a535895f39155ae47de1196a6b6b | Ph0enix171/Command_Line_Preprocessor | /save_dataset.py | 1,079 | 3.8125 | 4 | import pandas as pd
def saveHere(dataSet):
name=input("\nEnter name of dataset\n:")
try:
dataSet.to_csv(name+'.csv')
print("\nDataset saved successfully in the same directory")
except:
print("\nError: Could not save dataset\n")
def saveToFilePath(dataSet):
filepath=input("\nEnt... |
c72f020aa072c5a53b2841cfb6950a9bacfa7d02 | oplt/Codecademy-Projects | /Data-Science-Path/Machine Learning_Supervised Learning/Predict Titanic Survival.py | 2,558 | 4.21875 | 4 | # The RMS Titanic set sail on its maiden voyage in 1912, crossing the Atlantic from Southampton, England to New York City.
# The ship never completed the voyage, sinking to the bottom of the Atlantic Ocean after hitting an iceberg, bringing down 1,502 of 2,224 passengers onboard.
# In this project you will create a ... |
32682c0b63efeb105d4f87fa3f5300e6ec7b5983 | BrandonDotson65/LeetCode | /search_insert.py | 275 | 3.921875 | 4 | def searchInsert(nums, target):
beg, end = 0, len(nums)
while beg < end:
mid = (beg + end)//2
if nums[mid] >= target:
end = mid
else:
beg = mid + 1
return beg
numList = [1, 3, 5, 6]
print(searchInsert(numList, 1)) |
36daf6ec8ecc4f8c4ec25155ecb62888ecffef88 | tracysallaway/inf1340_2014_asst1 | /exercise2.py | 1,983 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Perform a checksum on a UPC
Assignment 1, Exercise 2, INF1340 Fall 2014
"""
__author__ = 'Tracy Sallaway, Sarah-Anne Schultheis'
__email__ = "tracy.armstrong@mail.utoronto.ca, sarah.schultheis@mail.utoronto.ca"
__copyright__ = "2014 Tracy Sallaway and Sarah-Anne Schultheis"
# imp... |
ab9857648b6aba268d132d63cdf99e87ae7034ec | ChristianEsperanza/COMP3981_Project | /GUI/tile.py | 2,286 | 4.1875 | 4 | class Tile:
"""
Class to represent a tile to be displayed on the board.
"""
def __init__(self, row, column, board_coordinate, piece):
"""
Constructor for the tile. Holds a row and column (Ex. 8, 4),
board coordinate for representation (Ex. "I5"), and a piece. A piece
is ... |
27194c74bfe8a460bf2036e681c365c9c3f6341d | mleue/project_euler | /problem_0065/python/e0065.py | 724 | 4.09375 | 4 | def generate_e_fraction_terms(n):
"""Return n fraction terms for sqrt(e)."""
yield 2
count = 1
for i in range(2, n + 1):
if i % 3 == 0:
yield i - count
count += 1
else:
yield 1
def roll_up_fractions(fraction_list):
"""Return global numerator and denumenator."""
num, den = 1, 0
... |
51c4f1fa88f7f9f1ae4de104a42c7a860c3db452 | Taxel/PlexTraktSync | /plextraktsync/mixin/ChangeNotifier.py | 552 | 3.5625 | 4 | class ChangeNotifier(dict):
"""
MixIn that would make dict object notify listeners when a value is set to dict
"""
listeners = []
def add_listener(self, listener, keys=None):
self.listeners.append((listener, keys))
def notify(self, key, value):
for listener, keys in self.liste... |
380c08fa6106f11aae6d3a76f2387411d96b2499 | RinatStar420/programming_training | /lesson/conert_binary.py | 272 | 3.828125 | 4 | def binary_array_to_number(arr):
return sum(val*(2**idx) for idx, val in enumerate(reversed(arr)))
print(binary_array_to_number([0,0,0,1]))
print(binary_array_to_number([0,0,1,0]))
print(binary_array_to_number([1,1,1,1]))
print(binary_array_to_number([0,1,1,0])) |
ce75feecdb6c142ec02ce35fe2e791e625b812d3 | yinyinyin123/algorithm | /双指针/double_pointer.py | 1,418 | 3.5 | 4 |
### one code ond day
### 2020/02/28
### leetcode 209 长度最小的子数组
### 双指针法
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
Left = 0
Sum = 0
Answer = float('inf')
for i in range(len(nums)):
Sum += nums[i]
### 当总和大于s时,滑动窗口
while(Sum >= s):
Answer = min(answer,i... |
dd9a61cfffb33f14e3cd73694c39c767ca2078bd | adriana-nm/P4e | /Chapter_8/Ex6.py | 401 | 4.09375 | 4 | # Prompts the user to enter a list of integer numbers until the user write 'done'
# Store the numbers in a list, and use the max/min functions and print it.
nlist = []
while True:
snumb = input('Type a number:')
if snumb == 'done':
break
try:
inumb = int(snumb)
except:
continue
... |
fc1b68455731c236975ccd1f3a4ec7b031742550 | Aasthaengg/IBMdataset | /Python_codes/p02880/s366150024.py | 120 | 3.5 | 4 | N = int(input())
multiple_list = {i*j for i in range(1,10) for j in range(1,10)}
print(['No','Yes'][N in multiple_list]) |
e4bb0b419bac34ac530512eccaf5050f87b790e3 | janosgyerik/advent-of-code | /2019/day18/part1.py | 2,543 | 3.703125 | 4 | #!/usr/bin/env python3
import sys
from collections import defaultdict
class Maze:
def __init__(self):
self.grid = {}
self.name_to_pos = {}
self.neighbors = defaultdict(set)
self.keys_count = 0
def add(self, x, y, name):
pos = (x, y)
self.grid[pos] = name
... |
5ac6bb85df26912fe0149e5095f2645030e3bea8 | Lyzzp/practice | /practice8.py | 1,001 | 3.65625 | 4 | # coding=UTF-8
"""
@Time:2021/3/25 14:27
@Author:Administrator
@Project:pythonProject1
@Name:practice8+
"""
# 有一个已经排好序的数组,现在输出一个数,要求按原来的规律将它插入数组中。
# a = [1, 4, 6, 9, 13, 16, 19, 28, 40, 100, 0]
# print 'original list is:'
# for i in range(len(a)):
# print a[i]
# number = int(raw_input('insert a new number:\n'))
# ... |
47952f86f685828c0c617c3447a0fb83cba7100c | Xenovoyance/adventofcode2015 | /day2/day2.py | 1,919 | 3.65625 | 4 | #!/usr/local/bin/python3
run_env = "prod" # test or prod
if run_env == "test":
input = "day2-inputtest.txt"
else:
input = "day2-input.txt"
totalBoxArea = 0
totalribbon = 0
currentExtra = 0
def breakApartString(box):
return box.rstrip("\n\r").split('x')
def smallestinlist(smallist):
smallist.sort... |
7d8193d44ba02b8be814033e483836a47239923d | nguyenngochuy91/programming | /interview/ARRAYS/pyramidTransition.py | 2,029 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 14:04:32 2019
@author: huyn
"""
#756. Pyramid Transition Matrix
#We are stacking blocks to form a pyramid. Each block has a color which is a one letter string.
#
#We are allowed to place any color block C on top of two adjacent blocks of colors A and B, if and only if... |
6db586344ac2e51cea059125fe99f398de436d7f | charwell-glitch/programming-challenges-v.14 | /amigoinvisible.py | 939 | 3.5625 | 4 | # coding=utf-8
import random
print "\nAMIGO INVISIBLE\n"
print "Inserta jugadores";
lista = [];
elegidos = [];
eleccion = True;
while eleccion:
aux = raw_input("> ");
if aux == "done":
break;
else:
lista.append(aux);
elegidos.extend(lista);
for i in range(len(list... |
160061522e91f4b6f6e97b7d34c5e64ac7685a40 | tjlqq/pythoncookbook | /zifuchuanhewenben/re/pythonre.py | 150 | 3.8125 | 4 | #!/usr/bin/env python
#coding:UTF-8
import re
pattern = re.compile(r'hello')
match = pattern.match('hello world!')
if match:
print match.group()
|
e73cfe1b7189b4c131a1efc15b07076479d55e94 | MartinPetkov/AdventOfCode | /2021/day14-extended-polymerization/part1.py | 871 | 3.5625 | 4 | # Run as:
# python3 part1.py [input|sample]
import sys
STEPS = 10
def solve(data):
lines = [line.strip() for line in data.splitlines()]
polymer = lines[0]
rules = dict([tuple(r.strip() for r in rule.split(' -> ')) for rule in lines[2:]])
for step in range(STEPS):
print(polymer)
next_polymer = ''
... |
0035816284bacec4e6b578def5ef411088aa2e4d | saloni027/hackerrank-solutions | /hackerrank_python/Basic-Data-Types/runner_up_score.py | 529 | 4.1875 | 4 | # Find the Runner-Up Score!
#
# Task
# Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given n scores. Store them in a list and find the score of the runner-up.
#
# Input Format
#
# The first line contains n. The second line contains an array A[]... |
cffea2d1880f93a25f65019e334b0e65d4096be1 | kpjani/HackerRank-master | /Findingthepercentage/Solution.py | 221 | 3.734375 | 4 | N= int(raw_input())
d={}
for i in range(N):
str = raw_input()
x= str.split(" ")
total = float(x[1]) + float(x[2]) + float(x[3])
avg = float(total/3)
d[x[0]] = avg
s = raw_input()
print ('%.2f' % d[s]) |
7c99b27cedac86ad153112712451c823230e5f4b | mattnmorgan/ECU-3010 | /Assn 01/server-morganmat16.py | 3,532 | 3.5 | 4 | # Assignment 01
# File: server-morganmat16.py
# Author: Matthew Morgan
# Date: 21 January 2018
# Special notes:
# This server is programmed to work in cooperation with its client,
# but also works as a standalone. It will shut down when either
# a number of predefined clients connects and disconnects, or the... |
5262c294926eaffcee94e61ef2ff9c6442b10be8 | ernie0423/1234 | /variables 2/ejercicio4.py | 454 | 4.03125 | 4 | numero1 = int(input("ingrese el primer numero: "))
numero2 = int(input("ingrese el segunto numero: "))
iguales = (numero1 == numero2)
print(f"los numeros son iguales?" ,iguales)
diferentes = (numero1 != numero2)
print(f"los numeros son diferentes? " ,diferentes)
primer_mayor = (numero1 > numero2)
print(f"el primer nu... |
520fec8f0bf84e1899a10e5d64754dabdd1eb5a4 | XeroHero/Coderdojo-UCD | /Python/inputConditional.py | 239 | 4.25 | 4 | name = input("What is your name? ")
if (name == "Lorenzo" or name == "lorenzo"):
print("Hi Lorenzo!")
elif (name == "Skye" or name == "skye"):
print("Hi Skye!")
else:
print("Hi " + str(name) + ". Sorry, but I don't recognize you.")
|
c692422ec2f6b212cbcba1eca47bb8c617cee1b5 | johnjagan13/guvi | /div_2_arr_with_equal_avg(pro21).py | 465 | 3.640625 | 4 | from itertools import permutations,combinations
def find_avg(arr,size):
sum=0
for i in range(size):
sum+=arr[i]
return(sum//size)
n=int(input())
l=[int(i) for i in input().split()]
avg=[]
f=0
for i in range(1,len(l)):
li=list(combinations(l,i))
for j in li:
lis=list(j)
sum=find_avg(lis,len(lis))
if sum not... |
683928585a5b63221b6c01e01a564b047cff3d59 | MikelShifrin/Python1 | /Students/Daniel/assignment 9.py | 365 | 4.4375 | 4 | #Assignment 9
#write a km to miles converter
#Miles = KM x 0.6214
#write it using void functions
#HINT:
#you will have 2 functions:
#main():
#km_to_miles(km):
def main():
km = float(input("Please enter a number of kilometres:\n"))
km_to_miles(km)
def km_to_miles(km):
miles = km * 0.6214
print("The ki... |
f26adea9f8742410be8d8e8f580dc02966a728f9 | jerels/app-academy-work | /projects/py-num-guess/guess-a-num.py | 726 | 4.125 | 4 | import random
guessCount = 7
name = input("what's your name, stranger? ")
secretNum = random.randint(1, 20)
print(f'hi, {name}!! can you guess my secret number?')
while guessCount:
if guessCount == 1:
print(
f'sorry, {name}!! you couldn\'t guess the secret number {secretNum}')
break
... |
3c0511eddd462e7f5bde9a9869f5f2f7b0878325 | starrye/LeetCode | /DFS_BFS/98. 验证二叉搜索树.py | 1,622 | 3.703125 | 4 | #!/usr/local/bin/python3
# -*- coding:utf-8 -*-
"""
@author:
@file: 98. 验证二叉搜索树.py
@time: 2020/8/20 16:59
@desc:
"""
from typing import List
"""
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 ... |
683308f2130ead441878e8909a4de94d89c3055e | snProject1/sn | /com.test/押题.py | 2,203 | 3.59375 | 4 | # 1反转三位数
num1=str(235)
# print(num1[::-1])
# 2合并排序数组
a=[2,3,5,7,8]
b=[3,4,5,6,7]
c=[]
i,j=0,0
while i<len(a)-1 and j<len(b)-1:
if a[i]>b[j]:
c.append(b[j])
j+=1
elif a[i]<b[j]:
c.append(a[i])
i+=1
elif a[i]==b[j]:
c.append(a[i])
c.append(b[j])
j+=1
... |
f3024bfdf661984772a6d043c040dcad709c3c59 | mehzabeen000/Function_python | /length_print.py | 405 | 4.09375 | 4 | #function to print the greatest length string and if it is equal then print both.
def length_print(str1,str2):
count_str1=0
count_str2=0
for i in str1:
count_str1+=1
for i in str2:
count_str2+=1
if count_str1==count_str2:
print(str1,str2)
elif count_str1>count_str2:
... |
425a81906b22bf179ee61d5287635a6c6bbce171 | hexinyu1900/LearnPython | /day10/07 多态.py | 670 | 3.78125 | 4 | # 目标:实现多态
class Dog:
def __init__(self, name):
self.name = name
def game(self):
print("%s 简单玩" % self.name)
class Skydog(Dog):
def __init__(self, name):
self.name = name
def game(self):
print("%s 天上玩" % self.name)
class Person:
def __init__(self, name):
sel... |
ef7aee694727b0dd9edd35972e6ee379065b1f64 | MJtsholo/OOP-MSDie | /MSdie.py | 742 | 3.640625 | 4 | import random
class MSDie(object):
#construct here
#define classmethod 'roll' to roll the MSdie
#I used 'dieroll' to roll the die
def __init__(self):
self.dieside = 6
self.dieroll()
def dieroll(self):
self.value= 1 + random.randrange(self.dieside)
... |
2ccfe1f641ad7319bd8195b28790910e1f97e512 | Shawn070/python_intr | /sim_bmi.py | 1,044 | 3.9375 | 4 | _DEBUG = True
def debug_bmi(height, weight, gender):
if _DEBUG == True:
import pdb
pdb.set_trace()
if gender != 'male' and gender != 'female':
print("input error!")
elif gender == 'male':
standard_weight = (height - 100)*0.9
else:
standard_weight = (height - 100)*... |
94c39b383e16c01eeb4681168fc1a8c9846bc25a | DenisStolyarov/Python.Study.Lite | /Game/Game 1 Guess the number.py | 699 | 3.984375 | 4 | #Guess the number.
import random
guessTaken = 0
print('What is your name?')
name = input()
number = random.randint(1,20)
print('OK,'+ name + '. I made a number from 1 to 20')
for guessTaken in range(6):
print('Try to guess.')
guess = input()
guess = int(guess)
if guess < number:
print('You... |
d8b7d5bfa4d0bae686a1df9a8e31d95cbf2c6437 | courses-learning/katas | /write_numbers_in_expanded_form.py | 554 | 4.375 | 4 | """You will be given a number and you will need to return it as a string in
Expanded Form. For example:
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0."""
def expanded... |
39ee5bd45aa99ef81e2124eefefadf88aec1b771 | maomao905/algo | /single-number.py | 331 | 3.59375 | 4 | """
A XOR A = 0 -> duplicates will zero out
A XOR 0 = A -> single number will be left
"""
class Solution:
def singleNumber(self, nums: List[int]) -> int:
r = 0
for el in nums:
# XOR
r ^= el
return r
s = Solution()
arr = [1, 4, 2, 1, 3, 2, 3]
print(s.singleNu... |
80dd73e6eab6995336825221615a2631de9b3ff5 | qinyaoting/python3-study | /tutorial.py | 459 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
斐波那契数列
这个数列从第3项开始,每一项都等于前两项之和
'''
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(1000)
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
'''
'''
fruits = ['Banana', 'Apple', 'Lime']
loud_fruits = [... |
9216fb0775998ac7e14c46d3fb2a91de4ce93020 | akantuni/Kattis | /judgingmoose.py | 234 | 3.828125 | 4 | line = input()
x = int(line.split()[0])
y = int(line.split()[1])
if x == 0 and y == 0:
print("Not a moose")
elif x != y:
ans = int(max(x, y)) + int(max(x, y))
print("Odd", int(ans))
elif x == y:
print("Even", x + y)
|
f392d3ca98e9cbe4743a27efbac354f3fe6b556f | Akavov/PythonDss | /SimpleCritter/critter.py | 556 | 3.9375 | 4 | #demonstrate classes
class Critter(object):
"""Virtual critter"""
def __init__(self,name):
print("New creature has shown!")
self.name=name
def __str__(self):
rep="Object of Critter class\n"
rep+="name: "+self.name+"\n"
return rep
def talk(self):
print("Hi,... |
80c2e22f620d1b73e5fe1112e4f08727a98e5399 | rduvalwa5/OReillyPy | /PythonHomeWork/Py4/Py4_Homework09/src/question1b.py | 1,017 | 3.640625 | 4 | '''
Created on Mar 31, 2014
A Method is only associated with a CLASS
@author: red
'''
import inspect
class o():
zz = []
yy = "12334"
vv = 123
def __init__(self):
pass
def __call__(self):
pass
def a(self):
print("A")
def b(self):
print("A")
def c(self):
... |
2ccea6fca922560aefd032c7c7011327b4a4e3f1 | grados73/pythone_learning | /projekt2.py | 187 | 3.78125 | 4 | kwiat = input("Podaj nazwę kwiata: ")
if(kwiat == "Skrzydłokwiat"):
print("Skrzydłokwiat jest najlepszą rośliną w historii!")
else:
print("Nie, ja chce Skrzydłokwiat...!")
|
0fec1bbec0ca44c886dbace5af75ab0ed392c92c | OrangeB0lt/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/101-remove_char_at.py | 194 | 3.859375 | 4 | #!/usr/bin/python3
def remove_char_at(str, n):
index = 0
nexxt = ""
for character in str:
if index != n:
nexxt += character
index += 1
return (nexxt)
|
c09b7d515d911ef38d22255f0f9155c7a2a998af | SujithAVJ794/Trialrepo | /py/listusage.py | 577 | 4.03125 | 4 | #Lists and tuples
#list in python is ahybrid data type, similar to array in c, but different data types
#usage of lists uses square brackets
mylist=['one','two',3,4.5,3+2j]
print(mylist)
print(mylist[0]) #gives the first value
print(mylist *3 )
newlist=[3,'sujith',4.0]
add=mylist+newlist
print(add)
newlist[0]=... |
a5d3b33ffce3ae48fb4831c9165462012bc008b9 | iSouma/Curso-python | /CursoemVideo/Desafio105.py | 1,351 | 3.71875 | 4 | def notas(*n, situação=False):
"""
--> Função para analisar notas e a situação de vários alunos de uma turma.
:param n: notas dos alunos (aceita várias)
:param situação: situação da média da turma (opcional)
:return: um dicionário com a várias informações da turma.
"""
dados = {'total': 0, '... |
5dd95fa9ce8a58f56a52d96d5abd2a1f83422927 | 3desinc/YantraBot | /linefollower_rrb3.py | 1,273 | 3.53125 | 4 | #!/usr/bin/env python3
import RPi.GPIO as GPIO
from rrb3 import *
from time import sleep
#initialize variables
voltB = 6 ## number of batteries * 1.5
voltM = 6 ## voltage of motors, standard is 6 volts.
GPIO.setmode(GPIO.BCM)
rr = RRB3(voltB,voltM)
#Use pin 7 for the line follower sensor on RRB3
#The other 2 pins a... |
57edc7ee902ececf40063c644985ae2004891514 | setyo-dwi-pratama/python-basics | /19.perulangan_for.py | 3,444 | 4.40625 | 4 | # PERULANGAN FOR
print("===============PERULANGAN FOR===============")
# Perulangan for di python untuk memproses sebuah array/himpunan. dengan format:
# variabel = [tipe data : string, list, tuple, set, dict]
# for i in variabel:
# statement
# statement
# dan seterusnya
# dari format diatas, te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.