blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
378c8d17049b895f1ca536f244fa2ffb48b82d21 | csreyno/Digital-Crafts-Classes | /programming101/medium.py | 2,288 | 4.03125 | 4 | #Exercise 1
# bill = float(input("What is the bill amount?\n"))
# split = input("Split how many ways?\n")
# good = .20 * bill
# fair = .15 * bill
# bad = .10 * bill
# if service == "good":
# print(f"Tip Amount: ${good}\nTotal Amount: ${bill + good}")
# elif service == "fair":
# print(f"Tip Amount: ${fair}\nTo... |
a54fe967fca959cf86c605cb5736d2db377cabc0 | ShantanuBal/Code | /cracking/ll_mergeSort.py | 1,097 | 4.0625 | 4 |
class LL():
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def print_list(head):
while head != None:
print head.data," ",
head = head.next
print
def mergeList(head1, head2):
if head1 == None:
return head2
if head2 == None:
return head1
if head1.data < head2.data:
hea... |
793eeae3988b0399da1846bfa5f02aa4346a2584 | jibinsaji/coders-house-python- | /triangle_check.py | 220 | 4.15625 | 4 | a=int(input("enter the 1st side"))
b=int(input("enter the 2nd side"))
c=int(input("enter the 3rd side"))
if ((a+b)>c) or ((b+c)>a) or ((c+a)>b) :
print("is a Valid Triangle")
else:
print("is not valid Triangle")
|
0891e3015572db6a2f6e07cc642e01d472f7dbf0 | kebingyu/python-shop | /the-art-of-programming-by-july/chapter1/exercise/exer21.py | 990 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
21、最长连续字符
用递归算法写一个函数,求字符串最长连续字符的长度,比如aaaabbcc的长度为4,aabb的长度为2,ab的长度为1。
"""
def func1(word):#{{{
length = len(word)
if length:
curr_char = None
max_length = 1
curr_length = 1
for _ in word:
if curr_char == None:
curr_char = _... |
b3261b642a6b23ef0a21a8e498041d63e729eba2 | DamianHuerta/Gatech-CS-CourseWork | /CS-1301-Python/HW05.py | 2,488 | 3.515625 | 4 | #!/usr/bin/env python3
import calendar
import statistics
"""
Georgia Institute of Technology - CS1301
HW05 - Tuples and Modules
"""
__author__ = """Damian Huerta-Ortega"""
__collab__ = """I worked on this alone"""
"""
Function name: favorite day
Parameters: dates (list of tups), weekday (int), day (int)
Returns: red... |
ca00674f9c1f0a05951a869433961e5cf00c2b8b | AhmetOsmn/Programlamaya-Giris | /057.kalan_borc_hesapla.py | 207 | 3.6875 | 4 | kredi = float(input("Çekilen kredi: "))
ay = int(input("Kaç ay: "))
odenecek = kredi + (kredi*9)/100
aylık = odenecek/ay
for i in range(3):
odenecek -= aylık
print("Kalan Borcunuz: ",odenecek)
|
3969ff7aa2052a76cc92ee3226ac591bafa7bf28 | Aasthaengg/IBMdataset | /Python_codes/p02265/s217222157.py | 419 | 3.6875 | 4 | from collections import deque
x = deque()
for i in range(int(input())):
com = input()
if com == "deleteFirst":
x.popleft()
elif com == "deleteLast":
x.pop()
else:
com,n = com.split()
if com == "insert":
x.appendleft(n)
elif com == "delete":
... |
e8d25cdf9216dc0bc50bacaea83b22353ed3f96b | Vovchik22/Python_test | /ex20.py | 1,122 | 3.953125 | 4 | from sys import argv
script, input_file = argv # pre-start recognise script and file
def print_all(f): # read recognised file
print( f.read())
def rewind (f): # define position in file in BYTES
f.seek(0)
def print_a_line(line_count, f): # define variable number of a line and a second argument d... |
4ce1b49e0413dfbd53aa1bb8bb5a709a333a01ca | DeshanHarshana/Python-Files | /pythonfile/findDuplicate.py | 1,145 | 3.703125 | 4 | def checkDuplicateAvailable(lst):
isDuplicate=False;
for i in lst:
if(lst.count(i)>1):
isDuplicate=True
break;
return isDuplicate
lst=[2,3,3,3,4,1,4,6,6]
print(checkDuplicateAvailable(lst))
def Repeat(x):
_size = len(x)
repeated = []
for i in range(_size): ... |
0c387f937fbf7c1c9da8fd381e6ab586259894da | tsevans/AdventOfCode2020 | /day_3/puzzle_1.py | 1,714 | 4.28125 | 4 | # Count the number of '#' characters seen traversing a (3,1) slope on the given input.
# Implementation is O(n) time complexity and O(n) space complexity.
HORIZONTAL_INC = 3
def load_input():
"""
Load the contents of input.txt into a list.
Returns:
([str]): Lines of input.txt as a list of strings.
"""
... |
7ee8ec23a5f780e767fe12cdf323eb158b3c5b86 | ulgoon/dss-python-basic | /resources/ask_age.py | 172 | 4.125 | 4 | age = int(input("How old are you?"))
if age <= 19:
print("Kid!!!")
elif age <= 29:
print("20th!!")
elif age <= 39:
print("30th!!")
else:
print("Elder!!!")
|
4597d63c3b0d9d9473325da87a1b37efcb8cb95e | jmstudyacc/python_practice | /POP1-Exam_Revision/repl_problems/session_9/bank_account_inheritance.py | 2,377 | 3.796875 | 4 | class Person:
def __init__(self, fn, ln):
self.first_name = fn
self.last_name = ln
self.address = None
def set_address(self, addr):
self.address = addr
# BankAccount class has been created to eliminate redundancy in later account types
class BankAccount:
def __init__(self,... |
871b714dd09397b92298f6fa67d0d102d391ed50 | BoLindJensen/Reminder | /Python_Code/Snippets/Iterations/Generator_Function/generator_function_using_yield.py | 716 | 3.953125 | 4 | '''
Generator functions have at lease one yeild in then, they are used when Lazy evaluation is needed.
Eg sensors, very large data sets, etc
'''
names = []
def read_file(): # Normal function using custom generator function.
try:
f = open("names.txt" , "r")
# instead of using the build in generator .... |
0017141022b8503a5ea7ec2f77a3e4b53e7a4742 | MysteriousSonOfGod/GUIEx | /JumpToPython/test021(class).py | 1,238 | 3.796875 | 4 | # 계산기
class Calculator:
def __init__(self):
self.result = 0
def add(self, num):
self.result += num
return self.result
def sub(self, num):
self.result -= num
return self.result
cal1 = Calculator()
cal2 = Calculator()
class FourCal:
def __init__(self, first, se... |
20d9c0a49119668d83912a5461e520aeae0ffc80 | NagahShinawy/problem-solving | /geeksforgeeks/lists/ex4.py | 245 | 4.28125 | 4 | """
Python | Ways to find length of list
"""
from operator import length_hint
def length(items):
counter = 0
for _ in items:
counter += 1
return counter
print(length("test"))
print(len("test"))
print(length_hint("test")) |
84849b66d58cd42b444848f85cbfcc8feeb58ffa | katochanchal11/BestEnlistInternship | /Day 11/task11.py | 1,003 | 4.4375 | 4 | # Exercise 1 - Write a program using zip() function and list() function
# create a merged list of tuples from the two lists given.
nums1 = [40, 25, 398, 500, 125]
nums2 = [258, 89, 147, 22]
zipped_list = list(zip(nums1, nums2))
print(zipped_list, '\n')
# Exercise 2 - First create a range from 1 to 8. Then using... |
8945d5950aea49d6b6718d4c02da4811a4a37e61 | UwaisMansuri/DS590 | /Uwais_Mansuri_DS590_Assignment4.py | 1,466 | 3.671875 | 4 | import sys
class MaxHeap:
def __init__(self, max):
self.max = max
self.size = 0
self.BHM = [0] * (self.max + 1)
self.BHM[0] = sys.maxsize # For restricting the size of the list
def parent_node(self, i):
return i // 2
def left_child(self, i):
return 2 * i
... |
0d6681e6b4fdff2c44e832e9579e2e8f32c78298 | taikinaka/youngWonks | /python/Math_project/math.py | 26,465 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Spyderエディタ
これは一時的なスクリプトファイルです
"""
import threading
import random
import time
import signal
import os
class GameTimer(threading.Thread):
def restart(self):
self.my_timer = time.time() + 50
self.isOn = True
def turnOff(self):
self.isOn = False
def run(sel... |
92efea4153f4fd452c2ad4209cda157e1c36fcd4 | DenisFuryaev/PythonProjects | /papacode/word_shuffle.py | 555 | 3.65625 | 4 | import re
import string
def dict_from_str(str):
dict = {}
for char in str:
if char in ',.!?':
if char in dict:
dict[char] = dict[char] + 1
else:
dict[char] = 1
for word in re.split('[ ,.!?]+', str.lower()):
if len(word) == 0:
... |
b9e085aa7879f0d0e2eab7eb63e5e35699f373e6 | maxter252/Coding-Questions-Solutions | /10-Simple/reverse_int.py | 862 | 4.3125 | 4 | # Given an integer, return the integer with reversed digits.
# Note: The integer could be either positive or negative.
def reverse(input: int) -> int:
input = str(input)
if input[0] == '-':
return '-' + input[:0:-1]
else:
return input[::-1]
# print(reverse(-12345))
# For a given sentence... |
fe3f2e74236454aa09d5a66014b7814eaa77e59d | Proudfeets/Learning-python | /rock-paper-scissors.py | 930 | 4.3125 | 4 | import random
for x in range(1):
machine = random.randint(1,3)
player=raw_input("Choose rock (r), paper (p), or scissors (s):")
if ( player == 'r' ) : print("You choose rock.")
elif ( player == 'p' ) : print("You choose paper.")
elif ( player == 's' ) : print("You choose scissors.")
else: print("I don't understand.... |
06cf4f15aa2f7a0001dfa3984ab6d3098edaa2c9 | Eric-Xie98/CrashCoursePython | /CrashCoursePython/Chapter 10/StoringData.py | 3,415 | 4.65625 | 5 | ## Because we take a lot input data from users, it's usual that we want to save what they input for things
## such as settings for later use. A simple way to do this is to use a json module:
## We dump simple Python data structures into a file and upload it whenever the program is run. We can use this JSON module
## t... |
230c429f193db0c99918c39b396526e5ad81b419 | 05113/fastapi-testplatform | /demo/xunhuanDemo.py | 233 | 4 | 4 |
# 当n=0时代表false,(python中0代表false)跳出循环
n = 2
while 0:
print(n)
# 当n为None时代表false,跳出循环
k = None
while k:
print(1)
for item in range(10,1,-1):
print(item)
a = [1,2]
a[2] = 3
print(a) |
1fa8de66ba462395dec03b5fcbfbf6cc146565e5 | aristotekoen/datacamp-assignment-pandas | /pandas_questions.py | 5,073 | 4.125 | 4 | """Plotting referendum results in pandas.
In short, we want to make beautiful map to report results of a referendum. In
some way, we would like to depict results with something similar to the maps
that you can find here:
https://github.com/x-datascience-datacamp/datacamp-assignment-pandas/blob/main/example_map.png
To... |
ffb8fde191dc5392e9b75719eeef27bb0be18419 | Callum-Diaper/COM404 | /1-basics/3-decision/2-if-else/bot.py | 208 | 3.609375 | 4 | user_inp = str(input("Please enter the activity to be performed "))
if user_inp == "calculate":
print("Perofrming calculations...")
else:
print("Performing activity...")
print("Activity completed!") |
a52750e35093c8e79ef05bb085eb7ca8cde85336 | Aasthaengg/IBMdataset | /Python_codes/p03805/s180201282.py | 975 | 3.546875 | 4 | #グラフのパスを全探索する関数(再帰)
def dfs(now_node, depth):#deptt:今まで列挙した頂点数
if seen[now_node]:#探索済みであった場合はreturn
return 0
if depth == N:#全ての頂点を通っていた場合、1を返す
return 1
seen[now_node] = True #今から探索するノードを探索済みにする
connect_nodes = graph[now_node]
ans = 0
for node in connect_nodes:#全ての遷移先をチェックする
... |
748d2627fc5ec5766fa0104390d90912ca9967cb | andybloke/python4everyone | /User_Input.py | 193 | 3.84375 | 4 | print("Please enter your First Name")
firstName = input()
print("Please enter your Last Name")
lastName = input()
print("You entered:\nFirst Name: " + firstName + "\nLast Name: " + lastName)
|
c83dfc6baab997f0993a949d55cc7e1a717ad5d4 | supperllx/LeetCode | /530.py | 636 | 3.515625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
nums = []
def func(root):
if root:
... |
44fcd91e3bc764da0eeb9d96a31866516116e638 | vaspupiy/home_work | /lesson_02v2/lesson_2_task_3.py | 1,767 | 3.640625 | 4 | while True:
m = input("Введите месяц в виде целого числа от 1 до 12: ")
if m.isdecimal():
m = int(m)
if 0 < m <= 12:
break
print("Ошибка ввода")
l_s = [["зиме", 12, 1, 2], ["весне", 3, 4, 5], ["лету", 6, 7, 8], ["осени", 9, 10, 11]]
for i in l_s:
if m in i:
print(f"В... |
c971c6c24da77e70b771be6580b41702bfa80231 | Big-Brain-Crew/learn_ml | /coral_inference/camera.py | 6,031 | 3.640625 | 4 | ''' Classes to stream video from camera sources.
These classes create a background thread that continuously streams camera images.
Any number of other threads can tune in and receive new images. The class structure can
easily be extended by implementing a few package-specific functions. For example, the
OpenCVCamera ... |
d9854f02452ce97e24a80a0ce424894c9642a8fc | zack-carideo/pass_through_dir | /text_preprocessing.py | 756 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 23 17:15:28 2019
@author: zjc10
"""
import string
import re
def clean_sentence(sentence,PUNCTUATION=string.punctuation+"\\\\",stemmer = None, lower=False,stopwords = None):
sentence = sentence.encode('ascii',errors = 'ignore').decode()
sentence=re.sub... |
2da54bd6d62c3628adeb4145342b772a8cdb3afb | rdkr/advent-of-code | /2020/01.py | 383 | 3.75 | 4 | import itertools
import functools
import operator
def calculate(combo_length):
for combo in itertools.combinations(numbers, combo_length):
if functools.reduce(operator.add, combo) == 2020:
return functools.reduce(operator.mul, combo)
with open("01.txt") as _input:
numbers = [int(x) for x... |
7c5f8d6e58a400625a166b8c3e4af72d283aed5d | kcunning/gamemaster-scripts | /general/wounds.py | 2,133 | 3.96875 | 4 | import csv
from random import choice
def get_lines(fn):
''' Gets a bunch of lines from a CSV file
'''
lines = []
with open(fn) as f:
reader = csv.reader(f)
for line in reader:
lines.append(line)
return lines
def create_char_dict(lines):
''' Takes lines from a CSV fi... |
56b546219d38c559b1f39e0a16874b5307792b01 | patelp456/Project-Euler | /longest_product_series.py | 608 | 3.703125 | 4 | #!/usr/bin/env python
# ========= Import required modules =====================
# for using system commands
import sys
# for using os commands like list directeries etc
import os
# for mathematical functions specially matriices
import numpy as np
# for general maths
from math import *
fname = sys.argv[1]
data = n... |
46b22aca8ae5d4fb82c4e3f9a08771e8e0922925 | wbsjl/ftp-server | /Data/Link_list.py | 921 | 4.03125 | 4 | # class QueueError(Exception):
# pass
#
# class Node:
# def __init__(self,val,next=None):
# self.next=next
# self.val=val
#
# class Lsqueue:
# def __init__(self):
# self.last=self.first = Node(None)
#
#
#
# def is_empty(self):
# return self.first == self.last
#
# def ... |
500818f6f5610a84dacefa889ff1bde9c93df542 | yuri-flower/GoogleSTEP2020 | /week5/solver_exchangetwo.py | 2,737 | 3.640625 | 4 | #!/usr/bin/env python3
import sys
import math
import random
import copy
from common import print_tour, read_input
def distance(city1, city2):
return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
# greedy
def solve(cities,current_city,dist):
N = len(cities)
for i in range(N):
... |
abdfbe195debcb5f9b1e495c38267a9f72e9f254 | savsrin/cloudshell | /day-1/hello.py | 322 | 4.21875 | 4 | print("hello world")
print("4" + "3")
print("4"*3)
#string formatting
name = "savitha"
last = "srinivasan"
print(f"good day {name} {last} !!!!")
#built in function: operate/ action --> give you back value
print(len(name))
#concatenation: joining strings 2gether
print("good day " + name.capitalize())
#built in metho... |
e22f4de2ee32d74c6eb237c9e1d5d261df66d260 | RoslinErla/ekki | /count_instances.py | 475 | 4.03125 | 4 | # ● Count instances
# ○ Implement a recursive function that counts a specific value in a list
# ○ Takes a list and a single value as parameters
# ○ Returns an integer value
# ■ How many times does that value appear in the list?
def count(a_list,value):
if a_list == []:
return 0
if value == a_list... |
b53230030ba20080688007d5f89d2a627c8e7121 | Notheryne/Rapanalyze | /scraping/parts/counters.py | 2,518 | 3.78125 | 4 | from prettytable import PrettyTable
def count(file):
#count how many times each word appeared
with open(file, 'r', encoding = "utf-8") as readfile:
words = readfile.read()
#get words from file
words = words.split(" ") #make list from string
words = [word for word in words if word != ""] #... |
711faf6b666cd02f098fe35db3a1e6c5546f87a3 | foxcodenine/practice | /w2resource_python/classes/classes_question1_2.py | 1,673 | 4.375 | 4 | """1. Write a Python class to convert an integer to a roman numeral"""
"""2. Write a Python class to convert a roman numeral to an integer."""
class Convertion:
values = [
('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100),
('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9),
... |
ffe234ee3fe1d05ff4320c7bbc6f015163fdbbd3 | pawat88/learn | /PythonCrashCourse/ch5/practice3.py | 1,020 | 4.03125 | 4 | #Hello admin
users = ['big', 'boom', 'admin', 'pa', 'ma']
for user in users:
if user == 'admin':
print("F**, " + user.title())
else:
print("Hello, " + user.title())
#No users
users = []
if users:
for user in users:
if user == 'admin':
print("F**, " + user.title())
... |
89f987fe70f5ee7eb92335ba1c709af0ce50a90d | dhruvarora93/Algorithm-Questions | /Array Problems/balance_parantheses.py | 1,022 | 3.84375 | 4 | def balance_parens(string):
keep = [False] * len(string)
for idx,letter in enumerate(string):
if letter == '(':
for j in range(idx+1,len(string)):
if not keep[j] and string[j] == ')':
keep[idx] = True
keep[j] = True
... |
3fcad4e9e8fc1d9614a52f3098392c12829f6588 | TheNathanHernandez/PythonStatements | /Unit 4 - Back To Python/A2 - Loops/part1_countedloops.py | 567 | 3.875 | 4 | from ess import ask
print("FIRST LOOP")
for i in range(5):
print("Hello")
print("")
print("SECOND LOOP")
for j in range(3):
print("j =", j)
print("")
print("THIRD LOOP")
for i in range(6, 10):
print("i =", i)
print("")
print("ADDER")
total = 1
for i in range(4):
num = ask("Enter a number:")
total * num
p... |
87a25cff147b5e3c10e06deddda672dd6d75e9da | alexandraback/datacollection | /solutions_5690574640250880_0/Python/hannanaha/main.py | 11,064 | 3.53125 | 4 | import os
import time
import decimal
import functools
#===============================================================================
# Generic helpers
#===============================================================================
# TODO FOR 14 : rounding functions, graph manipulation, desert lion, AttrDict... |
ed6909792ec99771e1852b0bda092bbbf8dc0bfe | bolof2000/AutomationInPython | /test/zipFunction.py | 636 | 3.703125 | 4 |
class Car():
def __init__(self):
print("default construtor")
#define the functionalities of a car
def drive(self):
print("car drives")
def stop(self):
print("car stops")
def accelerate(self):
print("car accelerate")
#toyota inherits Car properties
class To... |
dd838864f3026b12c9737fcbc9fca6d8d2e34d8c | laxmanlax/Programming-Practice | /InterviewCake/25_kth_to_last_node.py | 801 | 4 | 4 | #!/usr/bin/env python
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def kth_to_last_node(k, head):
prev, curr = head, head
# Move curr k-1 nodes ahead of head/prev.
for _ in xrange(k - 1):
if not curr.next: raise Exception("List is too... |
b32ef7a040576a323702894e9d58f4bcc86a2381 | la-ursic/redtape | /operadores.py | 216 | 3.859375 | 4 | x = y = z = 5
print ("comenzando el programa, x era igual a",x)
print (y)
print (z)
a,b,c = 1,2*3,"Jose"
print (a)
print (b)
print (c)
x = x + 10
x += 10
print ("después de todos los cálculos, x es igual a",x,"") |
4bf324948d49fae967016defa1a95b8f2f95dd44 | mendesivan/Python-the-Basics | /Inheritance.py | 546 | 3.9375 | 4 | #Inheritance
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
... |
cd831087c3ab91c725ec85553658b83d28b0308d | blxnca/python | /kata challenges/detect_pangram.py | 470 | 4.1875 | 4 | # Given a string, detect whether or not it is a pangram.
# Return True if it is, False if not.
# Ignore numbers and punctuation.
import string
from string import ascii_lowercase
def is_pangram(s):
alphabet = "abcdefghijklmnopqrstuvwxyz"
chars = list(filter(lambda x: x in ascii_lowercase,s.lower()))
for ... |
ecf831580cd81836a15980aa1fd7de74ad12ecea | jj0hns0n/impactmap | /modules/cities_on_map.py | 2,173 | 3.6875 | 4 | import numpy
import os
from geodesy import Point
def cities_on_map(A, distance_limit=100):
"""Put selected cities on map.
Ensure that cities shown are at least dis_lim km apart.
Input
A: Selected cities sorted by intensity and population.
distance_limit: Minimum distance [km] between cit... |
b46ab1e5f70778aef60d7cea1d22d69360d01d9a | restavratof/python-cert | /sandbox/ex_iterator.py | 845 | 3.765625 | 4 |
def test():
print(__name__)
print('EXAMPLE:')
class I:
def __init__(self, var='samle'):
self.s = var
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i == len(self.s):
raise StopIteration
v = self.s[self.i]
self.i += 1
... |
f0c674ec2822d0b189e907539137941784cdb718 | andersondi/simple-games | /guess_a_number.py | 3,147 | 4.0625 | 4 | #!/usr/bin/env python
"""
Guess_a_number v.1
This is my first program (Hello world's like don't count, ok?!)
This is a classic one and allowed me to try some:
- Functions
- Loops and conditionals
"""
import random
def score_monitor(actual_score, secret_number, attempt, level):
how_far_was_the_attempt = abs(se... |
26fcd8a814e3172a4a6fdd4960267a71462f30e1 | HyunIm/Baekjoon_Online_Judge | /Problem/5361.py | 272 | 3.578125 | 4 | price = (350.34, 230.90, 190.55, 125.30, 180.90)
testCase = int(input())
for _ in range(testCase):
A, B, C, D, E = map(float, input().split())
part = [A, B, C, D, E]
cost = 0
for i in range(5):
cost += part[i] * price[i]
print('$%.2f'%cost)
|
76c8f11ad81f26940248528a09f52f915359fba3 | aleksandromelo/Exercicios | /ex080.py | 399 | 3.6875 | 4 | c = 0
v = []
ultimo = 0
anterior = 0
atual = 0
while c < 6:
n = int(input('Digite um valor: '))
if c == 0:
v.append(n)
ultimo = n
print('Adicionado ao final da lista...')
if c == 1 and n < ultimo:
anterior = n
v.insert(0, anterior)
else:
... |
2bd2b7357eee21b758249d56a3f81745382463d2 | qw632076202/9602skydataTool | /UI/DividingLine.py | 409 | 3.703125 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
#图形库包
from tkinter import *
class DividingLine:
fatherComponent = NONE
dividingLine = NONE
def __init__(self, fatherComponent, placeX, placeY):
self.fatherComponent = fatherComponent
super().__init__()
self.dividingLine = Label(self.fatherComponent, text='... |
4c4994aee2891c0b55b7da7f862037030bd41348 | fresjo/Prog-klass | /klasser.py | 678 | 3.5625 | 4 | class Pistol(object):
def __init__(self, antalskott):
self.magasin=antalskott
def skjut(self):
print "PANG"
self.magasin=self.magasin-1
if self.magasin<1:
print "Out of Ammo"
def reload(self):
print "reload"
self.magasin=20
def emptymag(self):
print "emtymag"
self.magasin=0
def info(se... |
e4c379eafa99ab0e2045b572e2c873b6422b2f02 | Agoming/python-note | /3.高级语法/协程和生成器、迭代器/生成器01-06/04.py | 287 | 4.34375 | 4 | # ʹyieldشgenerator
def odd():
print("step 1")
yield 1
print("step 2")
yield 3
print("step 3")
yield 5
o = odd()
print(next(o)) # ᷢÿµþͻǴһηصyieldпʼִ
print(next(o))
print(next(o)) |
be051f2b5e3fa61b4ca6087e9614f620c41189e8 | pyladies-sergipe/challenges-python | /desafios-py/iniciante/d0000-bem-vinda/d0000-bem-vinda-v1.py | 286 | 3.9375 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
########
#strip() remove espaços em branco no início e no fim da string
#capitalize() torna a primeira letra maiúscula
nome = input('Digite seu nome: ').strip().capitalize()
print(f'Bem-vinda, {nome}!')
|
06a8b8d558950dcc1cb8f0d30fcd81090abca41b | claraqqqq/i_c_s_p_a_t_m_i_t | /ps4/ps4_9.py | 7,883 | 3.5625 | 4 | # YOU AND YOUR COMPUTER (1 point possible)
"""
computer the give to need you word, a choose can computer your that Now
playGame the re-implements that code the Write play. to option the
in below described as behave to function the modify will You function.
HAND_SIZE the use should you before, As comments. function's ... |
1d36a0cec63d0a13f7db4f4d58c5f561160611cc | mrozsypal81/323-Compilers-Assignment-3 | /compiler/syntax_analyzer/syntax_analyzer.py | 2,676 | 3.515625 | 4 | class Syntax_analyzer (object):
def __init__(self, *arg):
self.lexemes = arg
# print('arg = ', arg)
# statemenize method - create statement list from lexemes
def syntaxA(self):
lexemes = list(self.lexemes[0])
begin = 0
tablestart = 5000
resultlist = []
... |
5648d09bec523551c32684e17e429960c4f95356 | Sophiall/ERGASIES | /Εrgasia2 PARENTHESEIS.py | 411 | 3.5625 | 4 | def Par(par):
stack = []
push = "({["
pop = ")}]"
for ch in par :
if ch in push:
stack.append(ch)
elif ch in pop:
if len(stack) != 0 :
top = stack.pop()
br = push[pop.index(ch)]
if top != br:
return False
else:
return False
return len(stack) ==... |
d57e1839c5846f7894508a009d5a2d06d5057ba2 | Danilo-mr/Python-Exercicios | /Exercícios/ex054.py | 201 | 3.9375 | 4 | maioridade = 0
for c in range(1, 8):
ano = int(input('Digite o ano de nascimento: '))
if 2020-ano >= 18:
maioridade += 1
print(f'{maioridade} pessoas já atingiram a maioridade')
|
04c9a101f3cf262751388c1f2fd48c94863a08b9 | dunitian/BaseCode | /python/2.OOP/3Polymorphism/1.isinstance.py | 438 | 4.03125 | 4 | # 判断一个变量是否是某个类型 ==> isinstance() or Type
class Animal(object):
pass
class Dog(Animal):
pass
def main():
dog = Dog()
dog2 = Dog()
print(type(dog) == Dog)
print(type(dog) == type(dog2))
print(type(dog))
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
# arg 2 must be... |
769f2490497fc3f87d17686d09024b9677fc616e | iznauy/LeetCode | /09.py | 966 | 3.65625 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
t = 1
while x / t >= 10:
t *= 10
p = t
while True:
if t * t <= p:
... |
8b7678294038764895325093d4fb4050414591e7 | wongcyrus/ite3101_introduction_to_programming | /lab/lab03/ch03_t06_grand_finale.py | 114 | 3.5 | 4 | from datetime import datetime
now = datetime.now()
print('%02d:%02d:%04d' % (now.hour, now.minute, now.second))
|
6e5934e75b34f05b98261b7374f067f4819a2c60 | kickbean/LeetCode | /LC/LC_longestCommonPrefix.py | 736 | 3.859375 | 4 | '''
Write a function to find the longest common prefix string amongst an array of strings.
Created on Feb 12, 2014
@author: Songfan
'''
''' compare each position of every string until unequal '''
def solution(strs):
n = len(strs)
if n == 0: return ''
if n == 1: return strs[0]
# find minimum le... |
f2813ba4cce38b0f7a6d9564f941bc85342d6fcb | FisicaComputacionalOtono2018/20180816-clase-diagramadeflujoparprimo-melilednav | /j.py | 232 | 3.796875 | 4 | def asfg(x):
if x<2:
flag=False
elif x==2:
flag=True
else:
flag=True
for i in range (2,x-1)=
if x%i==0:
flag=False
break
return flag
p=input("num")
if asfg(p):
print("es primo")
else:
print("no es primo")
|
f093312f730995cd054b1a01ea94ba3180767b89 | cohadar/learn-python-the-hard-way | /ex38.py | 554 | 3.8125 | 4 | ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there are not 10 things in that list. Let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) < 10:
one_stuff = more_stuff.pop()
stuff.append(one_stuff)
pr... |
316d5808dbeb89f2aea4726297a25e0c9ae066ce | ncfausti/python-algorithms | /MakeChange.py | 738 | 3.96875 | 4 | """Make change given the fewest amount of coins."""
Coins = {25, 10, 5, 1}
def make_change(amount):
"""Make change given the fewest amount of coins."""
coin_count = 0
while amount > 0:
if amount >= 25:
amount -= 25
coin_count += 1
continue
if amount < ... |
ea2d49babd0262534092875e6fce3a8cbab275d0 | rubengr16/OSSU | /ComputerScience/2_MIT6.00.1x_Introduction_to_Computer_Science/2_Core_Elements_of_Programs/happy_world.py | 164 | 4.15625 | 4 | # Print hello world if a number entered by the user is strictly greater than 2
happy = int(input('Enter a number: '))
if happy > 2:
print('happy world', happy)
|
5bd4237b2db53246110fd799bae01420f378ee9f | guiconti/workout | /crackingthecodeinterview/arrays/1-3.py | 328 | 4.09375 | 4 | # Replaces all spaces in a string with %20
# Solution 1 goes through each character in a string if it's a space put a %20
def Solution1(a):
a = list(a.strip())
for i in range(len(a)):
if a[i] == ' ':
a[i] = '%20'
return ''.join(a)
if __name__ == '__main__':
a = 'ab obo ra ameixa '
print(Solut... |
e9cca559ca1a1b820faa6ad989e2004d24b79e9e | lschanne/DailyCodingProblems | /year_2019/month_03/2019_03_08__maze_min_steps.py | 2,295 | 4.40625 | 4 | '''
March 8, 2019
You are given an M by N matrix consisting of booleans that represents a board.
Each True boolean represents a wall. Each False boolean represents a tile you
can walk on.
Given this matrix, a start coordinate, and an end coordinate, return the
minimum number of steps required to reach the end coordin... |
bfcfcbd925d38caec0e553c45e516355ea8d045b | Lunderberg/advent-of-code-2019 | /python/d17.py | 7,191 | 3.546875 | 4 | #!/usr/bin/env python3
from collections import defaultdict
import inspect
import math
import sys
import time
import util
class Memory(list):
"""
Implements a self-expanding memory of integers.
"""
def __getitem__(self,key):
if key < 0:
raise IndexError('Negative memory pos {} not ... |
7983ecb49a0c4fa1bb16825f23fbf287f4933aa0 | TayExp/pythonDemo | /05DataStructure/二叉树的深度.py | 721 | 3.59375 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
return self.IsBalanced(pRoot, 0)[0]
def IsBalanced(self, pRoot, depth):
... |
b39812f326c6d646907469fe657fb8aa3583868c | ashbwil/LeetCode | /28/implement_str.py | 539 | 3.515625 | 4 | class Solution(object):
def strStr(self, haystack, needle):
length_needle = len(needle)
n = 0
h = 0
if needle == "":
return 0
if needle not in haystack:
return -1
else:
while n < length_needle:
if haystack[h] == need... |
3ce2f087927640c36e56c1de07e268cc97ed0565 | mitamit/OW_Curso_Python | /metodos_string.py | 610 | 4.0625 | 4 | curso = "Curso"
my_string = "codigo facilito"
result = "{} de {}".format(curso, my_string)
print(result)
result = "{a} de {b}".format(b = curso, a = my_string) #con alias
#formato
#result = result.lower() #minusculas
#result = result.upper() #mayusculas
#result = result.title() #como titulo
print(result)
#busque... |
7769422afc47e67572b69f80342273a21f2ebd4c | Sajirimendjoge/Python-Assignments | /Task_1/a8.py | 447 | 3.84375 | 4 | # Q.8 If one data type value is assigned to ‘a’ variable and then a different data type value is assigned to ‘a’ again. Will it change the value. If Yes then Why?
#Answer = Yes
#demo:
a = 7
print(type(a))
#output = <class 'int'>
a = 2.5
print(type(a))
#output = <class 'float'>
#Reason:
'''
Because Python is a dym... |
76611440884dc79c9982baa28a16140642d85c54 | AlbertoGiampietrri/python-lessons | /18-fileIn-fileOut.py | 490 | 3.53125 | 4 | def readFile(fileName):
out = []
file = open(fileName)
r = file.readlines()
file.close()
for e in r:
out.append(e.replace("\n", ""))
return out
def saveFile(fileName, list):
file = open(fileName, "w")
for r in list:
file.write(str(r) + "\n")
file.close()
carrello = readFile("./18-input-fi... |
72bd46df9805409604c517c14214b173b67014ef | 1456121347/demo1 | /day03/中国工商银行账户管理系统.py | 8,402 | 3.921875 | 4 | import random
# 准备数据
bank = {} # 空的数据库
bank_name = "中国工商银行昌平回龙观支行"
def bank_addUser(account,username,password,country,province,street,door):
# 是否已满
if len(bank) > 100:
return 3
# 是否存在
if username in bank:
return 2
# 正常开户
bank[username] = { #1
"... |
e872ad22ef7217a5122440d568e387327f030426 | nyroro/leetcode | /LC212.py | 1,720 | 3.796875 | 4 | class Node(object):
def __init__(self):
self.next = {}
self.end = False
self.word = ''
class Solution(object):
def insert(self, word):
now = self.root
for character in word:
if character not in now.next:
now.next[character] = Node()
... |
926199223e402ef6e050d309a4460a52f21fa947 | Shridevi-PythonDev/quotebook | /day2_exercises.py | 690 | 4.03125 | 4 |
## 1. Exercise 1
name = "Ram"
height = 5.6
age = 30
print(name, height, age)
print(type(name), type(height))
print(type(age))
##2
x = 10
y = 20.1
z = 30
sum1 = x+y+z
print("sum of 3 variables: ", sum1)
### 3 Range
print(list(range(1, 11)))
###4
print(list(range(0, 30, 5)))
### 5
print(list(range(0, 11, 3)))
#... |
5995249305bd3a040b701b64087575adfe56f809 | swornim00/house_price_prediction | /house_price_prediction.py | 2,657 | 3.734375 | 4 | from csv import reader
import matplotlib.pyplot as plt
#Function to import csv file and make put the data into dataset list
def read_file(filename):
dataset = list()
with open(filename,'r') as file:
csv_reader = reader(file)
for row in csv_reader:
dataset.append(row)
r... |
5f322bdf26e570696db5d8c6461ae337d12d22e0 | aregmi450/MCSC202PYTHON | /Q1.py | 1,113 | 4.21875 | 4 | # A ball is thrown vertically up in the air from a height h 0 above the ground at an initial
# velocity v 0 . Its subsequent height h and velocity v are given by the equations
# h = ho + vo t− gt^2
# v = vo − gt
# where g = 9.8 is the acceleration due to gravity in m/s 2 . Write a script that finds the
# height h and v... |
cca40f9563f0dbeff1c91cce9519be81d0fe10fd | sehun4239/Python_Basic | /01_remind.py | 2,159 | 3.921875 | 4 | # my_range = range(10) # 시작, 끝, 증감치 지정이 필요함 - 걍 10만 쓰면 끝이 10이고 증감치 1
# print(my_range)
# print(my_range[1:4]) # range(1, 4) -> slicing은 원본 데이터 유형 그대로 따라감
# # my_range = range(1, 10, 3)
#
# print(list(my_range))
# print(len(my_range))
#
# sum=0
# for i in range(11):
# sum+=i
# print('총 합계는 %d입니다' %sum)
#
# print(... |
8afc5a11c0cfa541f21d5f525e1cd274c02483f9 | HangCoder/micropython-simulator | /tests/basics/string_join.py | 817 | 3.796875 | 4 | print(','.join(()))
print(','.join(('a',)))
print(','.join(('a', 'b')))
print(','.join([]))
print(','.join(['a']))
print(','.join(['a', 'b']))
print(''.join(''))
print(''.join('abc'))
print(','.join('abc'))
print(','.join('abc' for i in range(5)))
print(b','.join([b'abc', b'123']))
try:
''.join(None)
print(... |
2bfeb9ef91e036c2d21a02f1baa67ac77297c177 | silpaps/mypython | /self/guees_game.py | 177 | 3.828125 | 4 | sc="giraffe"
guess=""
print("it's an animal")
print("mostly found in east africa")
print("tallest animal")
while sc!=guess:
guess=input("give your guess")
print("you win")
|
9858017ed80aa63561be68f63dc08837d2e98622 | Hovden/tomviz | /tomviz/python/Shift_Stack_Uniformly.py | 784 | 3.515625 | 4 | #Shift all data uniformly (it is a rolling shift)
#
#developed as part of the tomviz project (www.tomviz.com)
def transform_scalars(dataset):
from tomviz import utils
import numpy as np
#----USER SPECIFIED VARIABLES-----#
#SHIFT = [0,0,0] #Specify the shifts (x,y,z) applied to data
###SHIFT###
... |
8dbdca87d3aa5b77c0b8b3f75addb2ba05a5a09b | zhaoww/python-notes | /study/test06.py | 734 | 4 | 4 | # -*-coding:utf-8-*-
# list生成式 [expr for iter_var in iterable if cond_expr]
list0 = [x * x for x in (range(1, 10)) if x % 2 == 0]
print(list0)
# 生成器[] -> ()
list1 = (x * x for x in (range(1, 10)) if x % 2 == 0)
print(list1)
for x in list1:
print(x, end = ' ')
# yield
# 函数是顺序执行,遇到 return 语句或者最后一行函数语句就返回。而变成 genera... |
0260224543d1b2f8b51e3cbf22530d176fa1a684 | Zane-ThummBorst/Python-code | /Factorial code.py | 1,117 | 4.21875 | 4 | #
# Zane ThummBorst
#
#9/9/19
#
# demonstrate recursiuon through the factorial
# and list length
def myFactorial(x):
''' return the factorial of x assuming x is > 0'''
# if x == 0:
# return 1
# else:
# return x * myFactorial(x-1)
return 1 if x==0 else x*myFactorial(x-1)
#print(myFactorial(... |
057c066c503ef3ccd285e2f8d3b36164a5a75a3a | Jayu8/Python3 | /INTRODUCTION.py | 1,278 | 4 | 4 | """Pyton interactive shell:
A shell in biology is a calcium carbonate "wall" which protects snails or mussels from its environment or its enemies.
Python offers a comfortable command line interface with the Python shell, which is also known as the "Python interactive shell".
Python Internals:
Python is both an interp... |
d06bec897147ed6cb62ec2bf0e79212d7a307840 | laurencepettitt/AusculNet-Classifier | /ausculnet/preprocessing/data_augmentation/__init__.py | 1,466 | 3.71875 | 4 | import numpy as np
import pandas as pd
def randomly_crop_recording_sample(sample, sample_rate):
"""
Crops the beginning and end (at random length) off a sample.
Args:
sample: floating point time series representing audio sample
sample_rate: sample rate of time series
Returns:
... |
d8d5cb8402eca71774efd6b1c494a035f6fd9617 | lamb-j/machine-learning | /hw/hw1/submit/id3.py | 5,270 | 3.703125 | 4 | #!/usr/bin/python
#
# CIS 472/572 -- Programming Homework #1
#
# Starter code provided by Daniel Lowd, 1/20/2017
# You are not obligated to use any of this code, but are free to use
# anything you find helpful when completing your assignment.
#
import sys
import re
# Node class for the decision tree
import node
import... |
0edd5f84d8d3e432b99aecc29ef8812e8b50294f | 23sarahML/projet2 | /exercies/ex2_bp_tree.py | 2,512 | 3.53125 | 4 | import json
def first(values):
return values[0]
def div_round_up(a, b):
return (a + b - 1) // b
def transpose(columns):
rows = [list(row) for row in zip(*columns)]
return rows
class BPTreeNode:
def __init__(self, keys: list, values: list, is_leaf: bool):
self._keys = keys
se... |
da23d032c17055b2698218d8c12668a8ff522a13 | gugarosa/textformer | /textformer/models/layers/position_wide_forward.py | 1,439 | 4.125 | 4 | """Position-Wide Feed-Forward layer.
"""
import torch.nn as nn
import torch.nn.functional as F
class PositionWideForward(nn.Module):
"""A PositionWideForward class is used to provide a position-wise feed forward layer for a neural network.
References:
A. Vaswani, et al. Attention is all you need. Ad... |
1d1fe9158510b6ce11957efafc0032da79cf5af7 | ClassyBrute/MetodyNum2020 | /lista1/zad2.py | 197 | 3.75 | 4 | import matplotlib.pyplot as plt
x0 = 0.1
lista = [x0]
n1 = range(0, 101)
for n in range(1, 101):
x0 = 3.5 * x0 * (1 - x0)
lista.append(x0)
plt.scatter(n1, lista)
plt.show()
print(lista) |
59d6f7e2aadff3bc9bd0bc82980a4417f7aeede6 | varunagrawal/advent-of-code | /2018/day5.py | 1,232 | 3.59375 | 4 | import string
def collapse(polymer):
i = 0
reaction = False
while True:
if i >= len(polymer) - 1:
if reaction == False:
break
i = 0
reaction = False
if polymer[i].isupper() and polymer[i].lower() == polymer[i+1]:
# print(i, ... |
5bbffe092bef4f21d89a79a44477d5bfc310fb60 | waltermblair/CSCI-220 | /circle_intersection.py | 959 | 4.28125 | 4 | import math
from graphics import *
print("This program computes the two points where your horizontal line intersects with my circle.")
r=eval(input("The radius of the circle: "))
y=eval(input("The y-intercept of the line: "))
try:
x1=math.sqrt(r**2-y**2)
x2=-x1
print("Points of intersect: (",x1,y,") and... |
7d0744f128e0a9e7eab73be99b73a7157b879038 | revolutionisme/ds-and-algo-nanodegree | /P1-Show-me-the-data-structure/Problem_4/T4-active-directory.py | 1,650 | 3.9375 | 4 | class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = []
self.users = []
def add_group(self, group):
self.groups.append(group)
def add_user(self, user):
self.users.append(user)
def get_groups(self):
return self.groups
def ... |
6e41b1985b855932d3ad9b046acfc3f056a6c12d | Heartbeatc/python3.6.6 | /dict/code/day005 ◊÷µ‰/02 作业讲解.py | 3,408 | 3.53125 | 4 | # li = ["alex", "WuSir", "ritian", "barry", "wenzhou", "eric"]
#
# l2=[1,"a",3,4,"heart"]
# # print(len(li))
# # li.append("seven")
# li.extend(l2)
# li.remove(li[2])
# li.pop(2)
# print(li)
# li = [1, 3, 2, "a", 4, "b", 5,"c"]
# # ["c"]
# print(li[-1:])
# lis = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "a... |
ad84c40f9f794115c8c8b92cc65353adef424631 | rahulbhatia023/python | /19_Arrays.py | 2,572 | 4.3125 | 4 | # An array is a collection of elements of the same type.
# We can treat lists as arrays. However, we cannot constrain the type of elements stored in a list.
from array import *
# we need to import array module to create arrays
vals = array('i', [1, 2, 3, 4, 5])
# Here, we created an array of int type. The letter 'i'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.