blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c856254295dfe0dfe2e8cd40554bf127a8dfef32 | UAL-AED/lab5 | /aed_ds/queues/adt_queue.py | 745 | 4.375 | 4 | from abc import ABC, abstractmethod
class Queue(ABC):
@abstractmethod
def is_empty(self) -> bool:
''' Returns true iff the queue contains no elements. '''
@abstractmethod
def is_full(self) -> bool:
''' Returns true iff the queue cannot contain more elements. '''
@abstractmethod
... |
6f26cbdbc4352a6a01f735f41ede7dcd3cf847e8 | lewie14/lists_sorting | /lists2.py | 2,684 | 4.28125 | 4 | list1 = range(2, 20, 2)
#Find length of list1
list1_len = len(list1)
print(list1_len)
#Change the list range so it skips 3 instead of 2 numbers
list1 = range(2, 20, 3)
#Find length of list1
list1_len = len(list1)
print(list1_len)
print()
#------------------------------------------------------
#indexes
employees =... |
3fb0654ae23110d3b8f07803f147218c259bf2d9 | TheRohinth/resnet50 | /src/DL_model_files/blocks.py | 4,557 | 3.75 | 4 | from keras.layers import Conv2D # Conv2D() is used to apply a convolution to the input.
from keras.layers import BatchNormalization # BatchNormalization() is used to normalize the input.
from keras.layers import Activation # Activation() is used to apply an activation function to the input.
from ker... |
e9e219ddd527b54fa935129706a87adbe878d2a5 | zach-wahrer/ztm | /python/exercises/find_duplicates.py | 213 | 3.9375 | 4 | check_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = list()
for char in check_list:
if check_list.count(char) > 1 and char not in duplicates:
duplicates.append(char)
print(duplicates)
|
2654ef6171fb9e0d3d797a4751be3d53c967353b | zach-wahrer/ztm | /python/exercises/random_game.py | 1,629 | 3.96875 | 4 | from sys import argv
from random import randint
def main():
num1, num2 = cl_input_checking()
random_number = randint(num1, num2)
try:
while True:
guess = guess_validation(input("What is your guess?: "), num1, num2)
if guess_result(guess, random_number):
bre... |
45ed6639bf1c4d20eec91434bafe3d49f4a50c6f | zach-wahrer/ztm | /python/snippets/basic_gui.py | 324 | 3.5 | 4 | picture = [
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0]
]
fill, empty = '8', ' '
for row in picture:
for input in row:
char = fill if input else empty
print(char, end="")
print(... |
882b935289852482cb9a7a565eb612b683f26af2 | Tananan-Jee/exp_ict_34 | /18B09784-03-05_a.py | 4,262 | 3.5625 | 4 | # -*- coding: utf-8 -*-
#プログラミング言語:Python version 3.8.0
#コンパイル方法:python3 18B09784-03-05_a.py
#実行方法:ターミナル上で python3 18B09784-03-05_a.py を実行
import math
import numpy as np
def plus(array1,array2):
array=[]
for i in range(len(array1)):
array_ele=(int(array1[i])+int(array2[i]))%2
array.append(arra... |
a88e7634baaf93cf807f1d31e9ce0aa032ae75ef | iai-group/UserSimConvRec | /simulation/user/user.py | 636 | 3.765625 | 4 | """
Base (abstract) user class
==========================
Author: Krisztian Balog, Shuo Zhang
"""
from abc import ABC, abstractmethod
class User(ABC):
"""Base user class."""
def __init__(self):
pass
@abstractmethod
def init_dialog(self):
"""Initiates dialog with the conversational ... |
4939a2111784c1cacd25cbf16edf75c00b385852 | CrisBMoya/GDP_Project | /RequestFun.py | 4,995 | 3.734375 | 4 | import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
import pandas as pd
#Offline Variables
#CountryName="Estonia"
#CountryYear="2017"
#Percent=0.005
def Get_Similar_GDP(CountryName, CountryYear, Percent):
#Read DF
GDP_DF=pd.read_excel("/home/tobal/GithubProjects/Dynamic_GDP/GDP_1... |
16c90b7e533f9850501bfcdf034f1a815d6b1e84 | Goodleey/PraktikaPython5 | /Praktika5.py | 1,062 | 3.734375 | 4 | import time
# декаратор времени
def time_this(NUM_RUNS=n): # число прогонов функции(n)
def decorator(func): # декаратор, который принимает в значение другую функцию
def func(*args, **kwargs): # нам не известно, сколько и какие будут аргументы у функции
avg = 0
for i in range(NUM_RUNS... |
aa5434598598bf161cabc556367474b56a541e6b | nunezpaul/practice_problems | /sum_linked_lists/solution.py | 2,785 | 3.78125 | 4 | class ListNode(object):
def __str__(self):
return self.__repr__()
def __repr__(self):
return '{val} -> {next}'.format(val=self.val, next=self.next)
def __init__(self, val):
self.val = val
self.next = None
class LinkedList(object):
def __str__(self):
return self... |
fdd7341145ec07fc448bbcafa2a8dc67532c0b92 | Saliegh-Dien/python-task-manager | /Task_manager/task_manager-task-25.py | 19,770 | 3.875 | 4 | import datetime
from datetime import date
#this is the section login section--------------------------------------------------------------------------------------
#empty strings
user_names = ""
pass_words = ""
#opens files
file = open("user.txt", "r")
user_file = file.readlines()
#this loop gathers the... |
11c025fa5151fdee7b644dbf07a4dba9f17fcd95 | Yufei-Kang/plato | /plato/utils/decorators.py | 590 | 3.734375 | 4 | """ Useful decorators. """
import time
from functools import wraps
def timeit(func_timed):
""" Measures the time elapsed for a particular function 'func_timed'. """
@wraps(func_timed)
def timed(*args, **kwargs):
started = time.perf_counter()
output = func_timed(*args, **kwargs)
end... |
5feadeba85d180dca1c7a7f0445a32692dc3b9c6 | MichaelrMentele/LearnPythonTheHardWay | /ex18.py | 566 | 4.25 | 4 | def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_one(arg1):
print "arg1: %r" % arg1
def print_none():
print "I got nothin'."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("Fir... |
63330f97af4844146e13700f5fc5624f4eaf8f87 | UCHMS19-20/final-project-morganwhitney | /main.py | 8,304 | 4.34375 | 4 | #wakeup
print ("It's 5 am. Your alarm goes off, waking you up after a mere 4 and a half hours of sleep.")
wakeup_options = [" 1: Hit snooze",
" 2: Turn the alarm off, you'll wake up on time naturally",
" 3: Drag yourself out of bed, a little exhaustion never hurt anyone."]
for choice in wakeup_options:
print... |
3b5ba0a4b17eb8bb5d067f8e457af955af1f7133 | positiveoutlier/PythonProjects | /alphabetical order substring.py | 2,812 | 4.03125 | 4 | """ Created by Chantal Worp, 24/01/2017
Solution to Problem Set 1
Introduction to Computer Science and
Programming using Python (EDX)
Problem Set 1:
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabeti... |
557afd18a13c8f9f1bdf133267b85a9dd81352c1 | positiveoutlier/PythonProjects | /tuples and such.py | 411 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 23 11:39:00 2018
@author: positiveoutlier
"""
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
oddTuple = ()
for index in range(len(aTup)):
if index % 2 == 0:
oddTuple = oddTuple + a... |
9d1e099faa919669a9aa5b94bcf2238dc3bc4a61 | positiveoutlier/PythonProjects | /bob_counter.py | 326 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 13 21:50:28 2018
@author: positiveoutlier
"""
s = 'bobobobobobobobobob'
bob_counter = 0
for index in range(len(s)):
if index + 3 <= len(s):
if s[index: (index + 3)] == "bob":
bob_counter += 1
print("Number of times bob occurs is: " + str(bob_coun... |
9457a0d8d6498e50cbc248eee270875bc2024f17 | chloe-w/Little_Games | /Stopwatch.py | 1,561 | 3.5625 | 4 | # template for "Stopwatch: The Game"
import simplegui
# define global variables
t = 0
A = 0
B = 0
C = 0
D = 0
x = 0
y = 0
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
global A, B, C, D
A = t // 600
S = (t - A * 600) // 10
B = S /... |
1801c12b1078e9ee15ddfd5c33e574e4bc7bccf7 | CuriousG102/stay-in-your-lane | /prediction.py | 3,675 | 3.8125 | 4 | import enum
import math
import numpy as np
import track_floor_utils
CAR_AXLE_FRONT = .127
CAR_AXLE_BACK = - .16
CAR_LENGTH = abs(CAR_AXLE_BACK) + abs(CAR_AXLE_FRONT)
class Circle:
class CircleSide(enum.Enum):
LEFT = 1
RIGHT = 2
def __init__(self, radius, side):
self.radius = radius
... |
9094793bfb7d2a74e8194310c44167d211d32530 | joacru/python | /matriz_inversa.py | 2,054 | 3.59375 | 4 | def init_matriz(m, n):
ret = [[0 for i in range(n)] for j in range(m)]
return ret
def cargar_matriz():
m = int(input('Ingresa la cantidad de filas y columnas: '))
n = m
ret = init_matriz(m, n)
for i in range(m):
fila = input(f'Ingresa los valores de la {i + 1}° fila separados por un espacio: ').split('... |
c4e106fdc5a9dc05f7d189ec3fd043edb634c8de | seanaleid/cs-bw2 | /Day_03/pascals_triangle.py | 984 | 3.703125 | 4 | def generate(numRows):
rows = []
for i in range(numRows):
# First row
if i == 0:
rows.append([1])
# Second row
elif i == 1:
rows.append([1,1])
# General case rows
else:
... |
8986a1273dab2750550c95c3bcc59c13acb389fc | abeeki16/GOACapstoneProject | /Robot.py | 2,020 | 3.640625 | 4 |
class Robot:
def __init__(self):
self.canCooperition=False
self.objectInfo={"Totes":{"lift":"","push":"","Stack Height":0,"flip":""},"Bins":{"lift":"","push":"","Stack Height":0,"flip":""}}
self.objectInfo["Litter"]={"lift":"","push":""}
self.driveSystem=""
def updateObjectInfo(self,item):
... |
148071aa899d692b071b1f5fd0e09b1425a3e336 | JacobLinCool/School-Code | /SR/20200109/1/02.py | 134 | 4.03125 | 4 | while(1):
x = int(input())
r = x % 2
print(r)
if r:
print("奇數")
else:
print("偶數")
|
87531ace77c329a66dcad2d2eab8687e41c30229 | JacobLinCool/School-Code | /SR/20200409/1/02.py | 214 | 3.671875 | 4 | while 1:
a = int(input())
if (a % 400) == 0:
print("閏年")
elif (a % 100) == 0:
print("平年")
elif(a % 4) == 0:
print("閏年")
else:
print("平年") |
1d20d77f92ed3464c5848a2895d62e49cca9f034 | FluffyFu/UCSD_Algorithms_Course_3 | /week4_paths_in_graphs2/1_minimum_flight_cost/dijkstra.py | 2,721 | 4.0625 | 4 | # Uses python3
import sys
from queue import PriorityQueue
from typing import List, Tuple
def distance(adj, cost, s, t):
spt = ShortestPathTree(adj, cost)
return spt.shortest_path_weight(s, t)
class ShortestPathTree:
"""
Given a directed graph (possibly with cycles) with no negative weights. Find th... |
5bbf9ec0ed4353c7bdeeda3094a020fe1fe2b25f | FluffyFu/UCSD_Algorithms_Course_3 | /week2_graph_decomposition2/1_cs_curriculum/acyclicity.py | 1,516 | 3.890625 | 4 | # Uses python3
from typing import List, Set
import sys
def acyclic(adj):
graph = Graph(adj)
has_cycle = graph.has_cycle()
return 1 if has_cycle else 0
class Graph:
"""
Object to store the graph and perform operation on the graph.
"""
def __init__(self, adj: List[List[int]]):
s... |
609ce39d37e5fba558675c7cd212f662923480a2 | pinnertw/Jam2020 | /qualification/Q1.py | 985 | 3.640625 | 4 | #!/bin/python3
# input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Kickstart problems.
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
size = int(input())
mat = []
for j in range(size):
mat.append([in... |
963b20a52ee5ff350872cc42d29301f0545d7656 | jgslunde/knowit_julekalender_2020 | /luke6/Python/luke6.py | 676 | 3.734375 | 4 | """
Approach
Add the total number of candy in all boxes. Then move backwards one box at a time, remove the number of candy in that box from the total.
For each box, check if the total number of candy is now divisible by the number of elves.
"""
import numpy as np
num_elves = 127
boxes = np.loadtxt("../data/godteri.tx... |
b382e04ffd0f7ec4d7234ad7cd99c07c8f492be0 | Honglongwu/bioinformatics-scripts | /build_matrix.py | 1,162 | 3.859375 | 4 | #!/usr/bin/env python
"""
Build matrix - creates a 2d matrix of a given
number of rows and columns in length and outputs
to a file. Useful for working with DupliPHY.
"""
# module imports
import sys, os, re, time
# set start time
start_time = time.time()
# get arguments
args = sys.argv[1:]
# check... |
a3dc23b1db8920c3110fedf709cce2e720b4c494 | mverdicchio/gencyber-refactor | /DateCalculator2.py | 654 | 3.984375 | 4 | # step 2: factor out the method
class DateCalculator2:
@staticmethod
def convert(days):
year = 1980
while days > 365:
if DateCalculator2.is_leap_year(year):
if days > 366:
days -= 366
year += 1
else:
... |
43bd9e42e7590c64f6a0eb815abad92c4ef71d7f | nkwib/leetcode | /easy/1295.py | 307 | 3.5625 | 4 | from typing import List
class Solution:
def findNumbers(self, nums: List[int]) -> int:
def isOdd(num: int):
return len(str(num))%2 == 0
count: int = 0
for n in nums:
if isOdd(n): count += 1
return count
Solution().findNumbers([23,15,2,2,631,24]) |
4e64bca7a0e823c2f8963551e248eaf496bb295d | Abasshiekh/ga-learner-dsb-repo | /Mohd-Abas-Shiekh/code.py | 1,280 | 3.8125 | 4 | # --------------
# Code starts here
class_1 =['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 =['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
print("Concatenated list is :\n",new_class)
new_class.append('Peter Warden')
print("Appended list :\n",new_class)
... |
ac6687f26257c0812952a4fa00a26af0fae84704 | TatianaShalia/Python_Stepik_course | /avg_sum/avg_lite.py | 128 | 4.03125 | 4 | a = int(input('Enter your first value '))
b = int(input('Enter your second value '))
a += -a%3
b -= b%3
avg = (a+b)/2
print(avg) |
ee16c8d3ffbda28aa7d99e4c370bc9f98bf599fe | emilyjcosta5/numerical_analysis | /project_1.py | 11,080 | 4.0625 | 4 | '''
Project 1 for Numerical Analysis, MAD 3401, at Florida
International University. This code is posted for the
sake of turning in to the professor-- please, no
plagarism.
This project includes function that determine roots
or fixed points of a function using various numerical
methods.
Citations
---------
All code ... |
2d0c41f4f1e73659d39f318038f6bf7344d66112 | durgeshiv/py-basic-scripting-learning | /com/durgesh/software/slicing.py | 768 | 4.21875 | 4 | x='LetsSliceThisString'
# we have defined a string as above, lets try to slice it and print 'ThisString'
# [] -> is the syntax for slicing
#
slicedString = x[9:] # Here, this starts at index 9 and : means we haven't specified end
# index thus everything until end would be taken
print(slicedString) # give o/p as 'Thi... |
9c4f0e038a61883c3eb6626e922c87bea8d7059c | dftmckeon/vthsgpa | /vthsgpa.py | 15,546 | 3.5625 | 4 | #VTHS GPA Calculator, Developed By: Daniel McKeon
from Tkinter import *
class Application(Frame):
''' VTHS GPA Calculator
'''
def __init__(self, master):
''' Initialize the Frame
'''
Frame.__init__(self, master)
self.grid()
self.button_clicks = 0 #count bu... |
a3bd72a4f86653946331505e4b8157675cc3e153 | irskep/mrjob_course | /solutions/wfc_job.py | 1,293 | 4.125 | 4 | """
Write a job that calculates the number of occurrences of individual words in
the input text. The job should output one key/value pair per word where the key
is the word and the value is the number of occurrences.
"""
from collections import Counter, defaultdict
from mrjob.job import MRJob
class MRWordFrequencyCou... |
01a9c172d87928a8bcb4030a5544c5e830a3460c | Dibouni-Abdelkader/Python-Scripts-examples | /rayon.py | 235 | 4 | 4 | from math import pi
def cube(n):
return n**3
def volumeSphere (r):
return 4*pi*cube(r)/3
r=input("entrez la valeur du rayon: ")
print ("la volume de cette sphere vaut ",volumeSphere(float(r)) )
print(cube(4))
|
2ce182029e57f766f85dfe4c54d7a05517c33b91 | Dibouni-Abdelkader/Python-Scripts-examples | /textanlyze1.py | 1,026 | 3.828125 | 4 | class ana:
def __init__(self,fellname,char):#defin a constractor
self.fellname=fellname #somme attributes
self.char=char
def __str__(self):
count=0
try:
with open (self.fellname)as f: #opening a file from your pc as named 'f'
text=f.read() #read... |
c3f981451387791f80ba69fff17afe7b97577389 | morsisko/Minesweeper | /logic/board.py | 4,499 | 3.625 | 4 | import random
from .field import Field
class Board:
"""Klasa reprezentująca planszę"""
DIRECTIONS = [(-1, -1,), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
def __init__(self, width, height, mines):
self._width = width
self._height = height
self._mines = mine... |
43c79ccc3e78ab2b38cd3f1e1f220fc5d957c107 | kaushalkrishna2000/BillSplitter | /Bill Splitter/task/billsplitter.py | 1,160 | 3.71875 | 4 | from random import randint
d = {};
a = []
def creator():
n = int(input("Enter the number of friends joining (including you):"))
if (n <= 0):
print("\nNo one is joining for the party")
return 0
else:
print("\nEnter the name of every friend (including you), each on a new line:")
... |
98815d02b2b32a065ef7daf466ee5e503e4aed62 | meghasn/py4_everyone_solution | /question9.py | 255 | 4.34375 | 4 | #using a while loop read from last character of a string and print backwards
word=input("enter the string:")
index=len(word)-1
while index>=0:
a=word[index]
print(a)
index=index-1
#enter the string:banana
#a
#n
#a
#n
#a
#b |
04c4400203e7f8a2a077972e2926855557db9dd9 | ckguo/logicAI | /Player.py | 905 | 3.53125 | 4 | class Player:
def __init__(self, position):
self.position = position
self.gameView = GameView()
def pass_card(self, gamestate):
""" returns the index of the card to pass """
raise Exception('Unimplemented pass_card')
def guess_card(self, gamestate):
""" returns a tu... |
f80257589e18717b2fb1081b341433241e4c1a1c | basilcea/Algorithms | /recipe_batches/recipe_batches.py | 768 | 4 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
batches = []
quantity = None
try:
for i in recipe:
if(ingredients[i]):
quantity = int(ingredients[i]/ recipe[i])
batches.append(quantity)
maxBatches = min(batches)
return maxBatches
except:
maxBatc... |
8cbdc4fedbe19d502ad740fa86418ba7b3ef821e | soumyachat/python-code-practice | /classes/python_class_example.py | 379 | 3.75 | 4 | '''
Python Class example
Testing the scope of variables
'''
class FirstClass():
data = "spam"
def __init__(self,value):
self.data = value
def display(self):
print "Instance = ", self.data, "\t Class = ", FirstClass.data
def main():
x = FirstClass("abc")
y = FirstClass("31.8")
print "x:"
x.display()
... |
e5bab78a3d3d335d9f29cdb20488b017b479c404 | pkubier/Python-Scripts | /Scraping/Applications Scrape/applications.py | 2,346 | 3.53125 | 4 | import pandas as pd
import warnings
warnings.filterwarnings('ignore')
#reading in the data
movie_df = pd.read_csv('applications.csv')
#let's remove duplicates first
movie_df['dup'] = movie_df.duplicated(subset=None, keep='first')
movie_df = movie_df[movie_df['dup'] == False]
print(movie_df)
del movie_df['dup']
pr... |
4e77d007b959db29dab0632925702137e792f4d2 | MotherTeresaHS/ICS3U-2017-Group8 | /tutorial_scene.py | 6,848 | 3.515625 | 4 | from scene import *
#from main_menu_scene import *
import sound
import random
import math
A = Action
class TutorialScene (Scene):
def setup(self):
# Set the center of screen coordinates to placeholders
self.screen_center_x = self.size.x / 2
self.screen_center_y = self.size.y / 2
# Setting up background des... |
5dbf1aba29216b6f6d444eecac10c86717de5dfe | sm-wilson/euler | /1-100/009.py | 420 | 4.15625 | 4 | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
for c in range(334,500):
for a in range(1, int((1000-c)/2)):
... |
8020336c54f223edc92891c3689c880483e6085f | wingateep/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 894 | 4.28125 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
# TBC
#base case
count = 0 # sets ... |
38be726dba68be2b3fca02078fcfa877fa61dcbf | da-foxbite/KSU121 | /Python/lab2 [2, 5, 7, 12, 17]/t5 [FUN].py | 755 | 4.03125 | 4 | # 141, Суптеля Власлав
# 【Дата】:「24.02.20」
# 5. Дано ціле число. Вивести його рядок-опис виду «від'ємне парне число», «нульове число», «додатне непарне число» і т. д.
print("Умова: Вивести рядок-опис.")
n = int(input("Значення「n」: "))
if n > 0:
str1 = "додатнє "
else:
str1 = "від'ємне "
if n == 0:
str1 = "... |
b7f45c60fd07b48dde5572e9d0f728d13fec1bee | da-foxbite/KSU121 | /Python/lab1 [1-19]/t6.py | 494 | 4.125 | 4 | # 141, Суптеля Владислав
# Дата: 19.02.20
# 6. Даний рядок. Отримайте новий рядок, вставивши між кожними двома символами вихідної рядки символ *. Виведіть отриманий рядок.
string = input("「Введите строку」: ")
str2 = ''
for i in range(0, len(string)):
if i % 2 == 0:
str2 += string[i]+'*'
else:
s... |
b63fe2db805b0cb26df56e6c93119e1e2ce6bcad | da-foxbite/KSU121 | /Python/lab4 [2, 6, 7, 12, 14]/t7.py | 1,123 | 4.03125 | 4 | # 141, Суптеля Владислав
# 【Дата】:「09.03.20」
# 7. Написати рекурсивну функцію, що визначає, чи є симетричною частина рядка S, починаючи з i-го елемента і закінчуючи j-м.
def simline(S, i, j):
if (i == j or j-1 == i): # парное или непарное кол-во элементов
return 1 ... |
83d712506b7f834eef5b04e2f94f6664833c31a0 | da-foxbite/KSU121 | /Python/lab2 [2, 5, 7, 12, 17]/tz17.py | 479 | 3.84375 | 4 | # 141, Суптеля Владислав
# 【Дата】:「24.02.20」
# 17. Дано ціле число N (> 1). Знайти найменше ціле число K, при якому виконується нерівність 3K> N.
print("Умова: Знайти найменше ціле число K, при якому виконується нерівність 3K > N.")
n = int(input("Значення「N」: ")); k = int(1)
while 3*k <= n:
k+=1
print("【НЦЧ k】 =>... |
eeeea9fab95fa794fe3b2139dfa8f78c50ba13d6 | da-foxbite/KSU121 | /Python/lab1 [1-19]/tz16.py | 595 | 3.640625 | 4 | # 141, Суптеля Владислав
# Дата: 20.02.20
# 16. Відомо, що X кг цукерок коштують A гривень. Визначити, скільки коштує 1 кг і Y кг цих же цукерок.
print("Умова: Відомо, що X кг цукерок коштують A гривень. Визначити, скільки коштує 1 кг і Y кг цих же цукерок.")
x, a, y = map(int, input("Значення「X」(кг), 「A」(грн), 「Y」(кг... |
614f6c29f0e2abf62f9680e46eb5da225665a13d | lkklimas/bootcamplucek | /xxx.py | 257 | 3.671875 | 4 | liczba = int(input('podaj liczbę:'))
lista = [1,2,3,4,5,6,7,8,9,10]
for x in lista:
if x%2 == False:
print(f'liczby podzielne przez 2:{x}')
for x in lista:
if x%3 == False:
print(f'liczby podzielne przez 3:{x}')
|
b67f6068d26ffaf10da6342713df5ccf10b7a637 | jdwinfodesign/dita-python | /fixDoctype.py | 5,352 | 3.59375 | 4 | import os
import sys
import pyinputplus as pyip
from lxml import etree
import shutil
##REPLACE THE DOCTYPE DECLARATIONS IN A SET OF XML FILES
# Step 1: VERIFY THE INPUT (CHOSEN WHEN THE PROGRAM STARTS)
# THEN ENTER THE OUTPUT DIRECTORY AND START PROCESSING
def verifyDirs(inDir):
print('You wa... |
df338e233535d1774c0853b0c128d2cda3fa0d95 | kermen1972/Python | /lesson01_normal.py | 1,797 | 3.78125 | 4 | # Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа
a=input("Введите число: ")
m = max([int(i) for i in str(a)])
print("самая большая цифра этого числа",m)
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значен... |
754f753fac111a8a2cbd6315732cdec2bcc71594 | kellyrf/IS452AOFinal | /Example Instructional Code.py | 25,423 | 4.15625 | 4 | # To start, these are comments! Be sure to explain that "hashtags"/pound key is used to make comments in code that doesn't
# run as actual code, and act as a way to make notes in your code.
# Open workshop with this video as context: https://www.youtube.com/watch?v=o0u4M6vppCI
# # Before you begin:
# - review thi... |
5cdae915e0f6793a4102351712cbbe334df456ec | rainamra/TA_Project | /FlowControlExercises.py | 2,382 | 3.96875 | 4 | #1
def max_(x,y) :
if x > y :
print(x)
else:
print(y)
max_(5,4)
#2
def max_of_three (x, y,z):
if x > y:
if x > z :
print(x)
elif y > x and y > z:
print(y)
else:
print(z)
max_of_three(1,2,3)
#3
def length (arrayName):
x = 0
for i in a... |
ce104d33cf814b30b478b02115d4546766cae889 | duckness/CG3002-blindman | /using_navigator.py | 5,681 | 3.609375 | 4 | from navigator import Navigator
class UsingNavigator:
def __init__(self):
self.navigator = Navigator()
#testing for while loop variables below
#self.x = ""
#self.y = ""
#self.heading = ""
def setup_and_run(self):
check_map, check_start_node, check_end_node = sel... |
0b812f26b0162537c367c202e3182b92c17664da | matandiener/POPular_music_genre_ranking_system | /RankingData.py | 898 | 3.6875 | 4 | # Class that will hold all of the data that comes from the crawling services and be used
# in the ranking algorithm (each service will update the class with more relevant data)
BILLBOARD_KEY = "billboard"
YOUTUBE_KEY = "youtube"
class RankingData(object):
"""
songs = dict that contains the songs search in all... |
3c627a2bd3cdd61b02461c50b24a3c8ce1e76731 | zahras09/Assessment_2-object-orientation-7-17-2016 | /assessment.py | 3,460 | 4.6875 | 5 | """
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
-Abstraction: Hiding details that's not needed and focus on what is needed.
-Encapsulation: Keeping everything together. The data and functions should be paired together.
-Po... |
1ee0eac2b1e6982699619b29c16c750915ed91fe | OswaldEkwoge/CESAR-Challenge | /question7.py | 4,577 | 3.78125 | 4 | """
Write a method that receives two singly linked lists and returns the intersecting
node of the two lists (if exists). Intersection is defined by reference, not value
"""
# Create class node with data and pointer to next node
class Node:
def __init__(self, data):
self.data = data
self.next = None
... |
1bdf86a9891ac7937b39c37d5b6c6641a7e82203 | olagodavid/Top_Skills | /shell.py | 2,228 | 4.0625 | 4 | import sys
notstudied_list = []
studied_list = []
def add_skill():
print ("Enter Skill Starting with 'studied' for skills you have studied or 'notstudied' for skills not studied ")
print ("Example: studied HTML")
skill = input ("add skill: ")
#split string into list
temp_list = skill.split()
... |
3ba6b75c171b8b166d277b3cfc56ae9e737d75fb | ahmed-d8k/MyJackCompiler | /filemediator.py | 1,726 | 3.953125 | 4 | import os
def extract_file(file_name):
""" Takes a file and returns a list of its contents
:param file_name: (String) Name of file
:return: (List) made up of all the lines of text within the file
"""
file_contents = []
with open(file_name, 'r') as f:
for line in f:
file_co... |
8670b8b7bcec9e350c24c26b7dfb41e0c5dfef29 | UNR-Teaching/class-activity-3-pritzkow-qin3 | /CheckWinner.py | 1,402 | 3.625 | 4 | class CheckWinner(object):
def has_winner(self, board):
"""
Checks to see if there is a current winner of the game
"""
if self.col_check('X', board):
return True, 'X'
elif self.row_check('X', board):
return True, 'X'
elif self.diag_check('X', ... |
1ed2aa380654c752442b8ca0edf7fa0a26d0290b | lizator/OldWorldBestiary | /OldWorldBeasts/window test.py | 390 | 3.625 | 4 | import tkinter as tk
def create_window():
window = tk.Toplevel(root)
window.minsize(400,120)
window.title = "hello"
root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()
root.minsize(400,120)
root.mainloop()
frame = Frame(root, height=50, width=200, c... |
7f53bd1899e7323c2195c2b0fe7b18faee5f7b1f | daehanchoi-dev/BOJ-BAEKJOONALGORITHM | /프린터.py | 879 | 3.546875 | 4 | def solution(priorities, location):
answer = 0
# 인쇄 대기목록이 남아있다면 반복
while len(priorities) != 0:
# 1. 대기목록의 가장 앞에있는 문서가 나머지 문서들보다 중요도가 높은 경우
if priorities[0] == max(priorities):
answer += 1
priorities.pop(0) # 먼저 인쇄 == 가장 앞에있는 것 삭제
if location == ... |
e2440887e50d9b84a8344da67b49ded34be9a9ff | shovonis/data_science_python | /practise/week_one/csv_reader.py | 1,021 | 3.578125 | 4 | #!/usr/bin/env python
import csv
_author_ = "rifatul.islam"
with open("mpg.csv") as csv_file:
mpg = list(csv.DictReader(csv_file))
print(mpg[:10])
print(len(mpg))
print(mpg[0].keys())
print(sum(float(d['weight']) for d in mpg) / len(mpg))
# Avg mpg per cylinder
cyl = set(d['cylinders'] for d in mpg)
print(cyl)... |
24cf98488a425f47124dad9d236ff03d638f9616 | pranay77738/tkinter_projects | /Py_projects/calendar_GUI.py | 1,106 | 4.09375 | 4 | from tkinter import *
from calendar import calendar
# fuction to show the calender of the year
def showCalendar():
cal=Tk()
cal.config(background='grey')
cal.title('Calendar of the year')
# cal.geometry("550x600")
year=int(year_field.get())
cal_content=calendar(year)
calYear=Label(cal,text=... |
21e3fba95bd4f521b72e74d480e26e0d064d0543 | wqzhang0/python_stu | /icode/enum/enum_test.py | 1,163 | 3.53125 | 4 | from enum import Enum, unique
# @unique装饰器可以帮助我们检查保证没有重复值。
@unique
class Weekday(Enum):
Sun = 0 # Sun的value被设定为0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = '5'
Fri_int = 5
Sat = 6
if __name__ == '__main__':
print(Weekday.Sat.value)
print(type(Weekday.Sat))
print(type(Weekday... |
473e591f29ea9dbb794c6ab09d41d87c1b2525aa | wybosys/n2 | /bin/asc2bin.py | 314 | 3.734375 | 4 | #!/usr/bin/env python
i = 0;
while (i < 256):
if i <= ord('f') and i >= ord('a'):
print '0x' + chr(i) + ','
elif i <= ord('F') and i >= ord('A'):
print '0x' + chr(i) + ','
elif i <= ord('9') and i >= ord('0'):
print '0x' + chr(i) + ','
else:
print '0,'
i += 1
|
1cb7aafcbd8df93fafc22e6047ef790c47ef9bad | Maybyte/Python-Examples | /String to Binary.py | 244 | 3.578125 | 4 | myString = input("Input a string: ")
binFile = open("Binary Message.txt", 'w')
for letter in myString:
ordNum = ord(letter)
binNum = bin(ordNum)
binNum = str(binNum)
binNum = binNum.replace("b", "")
binFile.write(binNum)
binFile.close()
|
449fcc6dd8c50ff972a52b0b1fa664c13b89488b | JohnyTheProgrammer/Kiril_Vorobyov | /venv/Include/Home_LessonsKB11/functions/validate_password.py | 2,627 | 4.0625 | 4 | """Функция принимает пароль строкой и проверяет его тремя функциями
1. содержит только a-z, A-Z ,0-9
2. Содержит четное колличество букв
3. Содержит нечетное колличество цифр
основная функция возвращает True если пароль валидный
если пароль не валидный возвращает лист стрингов, в которых причины неуспешной проверки
[... |
153cf42ba8cc07694a856905206c57cb8929a05d | JohnyTheProgrammer/Kiril_Vorobyov | /venv/Include/4Lesson/List_work.py | 1,452 | 3.6875 | 4 | """list.append(x) Добавляет элемент в конец списка
list.extend(L) Расширяет список list, добавляя в конец все элементы списка L
list.insert(i, x) Вставляет на i-ый элемент значение x
list.remove(x) Удаляет первый элемент в списке, имеющий значение x. ValueError, если такого элемента не существует
list.pop([i]) Удаляет ... |
a23e63114c2de8267083e3af2153dfc0c1abbde0 | hanshuo11/my_python | /test/test10.py | 604 | 3.59375 | 4 | #!/user/bin/env python
# -*- coding: utf-8 -*-
# Author:HanShuo
# def not_empty(s):
# return s and s.strip()
#
# print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])))
# 过滤回数
# def is_palindrome(n):
# if n>11:
# return str(n)==str(n)[::-1]
# else:
# next
#
# outprint=filter(is_pa... |
7453a06a38e3bf944e23404bd38d442d690ee800 | thekrampus/nmt-neuralnet-labs | /project1/dataset/noisy_data.py | 2,058 | 3.5 | 4 | #!/usr/bin/python2
#
# Noisy Data Generator
# author: Rob K
# For use with Neural Nets project 1.
#
# Given an input "prototype" vector, this script produces a distorted image by
# applying additive white pseudorandom binary noise. This can be used to produce
# a set of independently noisy vectors.
#
# For example:
# ... |
cf300b93a0b11bcc547f8e59a36489512e73e37d | RoRu/Python_git | /Function/gisto.py | 250 | 3.703125 | 4 | #number 5 (2 mas)
from random import randint
arr = []
add = []
for i in range(20):
arr.append(randint(43, 81))
print(arr)
for i in arr:
add.append(i // 10)
for i in range(20):
for j in range(add[i]):
print("*", end="")
print() |
fa647b52c468eda7f465247748511b4d2ae92346 | RoRu/Python_git | /classwork/mccme/354.py | 282 | 3.578125 | 4 | n = int(input())
arr = []
for i in range(n):
arr.append([0 for i in range(n)])
for i in range(0, n):
arr[i][n - i - 1] = 1
for i in range(0, n):
for j in range(0, n):
if j > i:
arr[n - i - 1][j] = 2
for i in range(0, n):
print(arr[i])
input() |
9873c0efb64a4956ba4c64ac1bd0685898ad71ee | RoRu/Python_git | /Function/Bin_search.py | 487 | 3.78125 | 4 | arr = str(input("Enter array: ")).split(" ")
for i, item in enumerate(arr):
arr[i] = int(item)
arr.sort()
search = int(input("Enter number: "))
start = 0
end = len(arr)
mid = int((start+end)/2)
while start != end:
if(search > arr[mid]):
start = mid+1
mid = int((start+end)/2)
continue
... |
e868127a04be3ace190bbf90466914e3e45d3c7f | Acliu1498/8wocReversiChallenge | /ReversiSolution.py | 2,868 | 3.90625 | 4 |
import json
import argparse
import sys
def main():
"""Returns a new board with the move having taken place"""
# Gets input
args = parse_arguments()
begin_state = json.load(args.infile)
# Gets the current board
board = begin_state['board']
# sets move equal to the given move input
m... |
58286c63bc7796e8f249af8e22f91959f70da002 | jonathadd27/RumusKasir | /RumusKasir.py | 821 | 3.96875 | 4 | #Sourcecode
#----------------------
#Inputan
nama = str(input("Masukan Nama Barang : "))
harga = int(input("Masukan Harga Barang : "))
jumlah = int(input("Masukan Jumlah Barang : "))
#RumusKair
hitungbayar = harga*jumlah
#MenghitungRumus
if hitungbayar > 100000 :
potongan = hitungbayar * 0.10
... |
75c0bd9ab877748fa5bb10c92ad9c92932fbcd58 | laxmanbharate20/CLI-MyCart | /customer.py | 5,602 | 3.609375 | 4 | from os import system, name
import time
basket = {}
stock = {}
def Choice(i):
switcher = {
1: view_basket,
2: view_stock,
3: add_product,
4: search_in_stock,
5: remove_from_basket,
6: display_invoice
}
switcher.get(i, lambda: 'Invalid')()
return
def v... |
36823f452047f9662af33ec41f25d838794b32e7 | zeinabmostafavi/pythoncourse-tamrin6 | /2.py | 678 | 3.8125 | 4 | import random
n = int(input("enter n: "))
m = int(input("enter m :"))
k = int(input("enter k:"))
mt1 = [[random.randint(1, 10) for i in range(n)] for j in range(m)]
mt2 = [[random.randint(1, 10) for i in range(k)] for j in range(n)]
result = [[0 for i in range(len(mt2[0]))]for j in range(len(mt1))]
print("m... |
1e2d51b46bc155d9400ff9aa9994bac52d0471be | Vision1983/Training-materials | /Tensorflow + Keras/part1.py | 1,563 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 1 10:29:23 2018
@author: te122613
https://pythonprogramming.net/introduction-deep-learning-python-tensorflow-keras/
ukazkový program - jak snadno vytvořit ML s KERAS s MNIST databazi rucne psaných číslic
"""
import tensorflow as tf
print(tf.__version__)
mnist = tf.ke... |
c5cfd2c7028432af67e3833d63f004ac224a20d4 | Joe-Sun-1116/guess-num | /guess.py | 236 | 3.71875 | 4 | import random
r = random.randint(1,100)
while True:
guess = input('請輸入數字 : ')
guess = int(guess)
if guess > r:
print('比答案大')
elif guess < r:
print('比答案小')
elif guess == r:
print('猜對了!')
break |
0aeb19c8991c50e41af8b123f8467b29932860da | marianassales/python3-curso-em-video | /Módulo 1/exercicio32_ano_bissexto.py | 372 | 3.84375 | 4 | # Faça um programa que leia um ano qualquer e mostre se ele é bissexto.
ano = int(input('Qual ano você quer analisar? '))
# Quando o ano é divisivel por 4 é bissexto, exceto anos múltiplos de 100 que não são multiplos de 400, logo:
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print('O ano é bissexto.... |
d570e060a09ea9223199db6dfa2aebb2d20154c7 | somair/word_dump | /wd | 515 | 3.5 | 4 | #!/usr/bin/env python
"""Small script to spit out random words."""
from argparse import ArgumentParser
from termcolor import cprint
from worddump import juxtapose
parser = ArgumentParser(description="Juxtapose random, disparate words.")
parser.add_argument('number', metavar='N', type=int, nargs='?', default=1)
if _... |
d27d107183029fb8230b6bc84ea6856f4a4f54ba | apekshyakh/roomGame | /mygame01.py | 4,690 | 4.125 | 4 | #!/usr/bin/python3
# Replace RPG starter project with this code when new instructions are live
# --------------- AUTHORS: Apekshya and Abelardo -------------------------
def showInstructions():
#print a main menu and the commands
print('''
RPG Game
========
Commands:
go [direction]
get [item]
''')
def showS... |
7bdd6912148e971df2cc6fde278be91dcedbac01 | Song-Q/Learn-python | /recur.py | 600 | 4.28125 | 4 | #为解决递归调用使用尾递归优化
#然后python并没有对尾递归做优化,实际过深的递归还是存在栈溢出
#计算n!
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num==1:
return product
return fact_iter(num-1, num*product)
#practice 汉诺塔
#将递归问题拆解为二阶递归,考虑最后一步干什么,重复的步骤,和最后之前一步干什么
def hanoi(n, a, b, c)
if n == ... |
9cc9fa08a66e0d79b46790ed5232c66f934933f0 | rachelmccormack/PythonRevision-Tutoring | /Homework/Solutions/furtherFileReading.py | 875 | 4.15625 | 4 | """
A list of words is given in a file words.txt
For this file, please give the number of times each word appears, in the form {word:number}
Please display the longest word
How many words are in the list? (Don't peek) What percentage of the words are unique?
"""
file = open("words.txt")
words = file.readlines()
file.c... |
f01918e592528706fd339fd576e339fb81148f41 | rachelmccormack/PythonRevision-Tutoring | /CodeExamples/ListWithinList.py | 110 | 4.09375 | 4 | """
Append to a list within a list
"""
startList = [1, 2, [3, 4], 6]
startList[2].append(5)
print(startList)
|
ac0792f282322dc080a62a79f83b57aad55a4d38 | rachelmccormack/PythonRevision-Tutoring | /Homework/shoppinglist.py | 795 | 4.21875 | 4 | # Fill out Shopping List Program
print("Welcome to the shopping list program...")
shoppingList = []
finalise = False
def finaliseList():
print("Your final list is: ")
for item in shoppingList: print(item)
print("Thank you!")
return True
"""
Here we need functions for adding to the li... |
96d187a72f30f6a9ab253cc04d2cd9053dc2deb1 | jogo279/pzlpal | /server/find_grid.py | 4,571 | 3.5 | 4 | # Example Usage:
# python find_grid.py puzzles/basic.jpg 21 21
# from http://stackoverflow.com/questions/16975556/crossword-digitization-using-image-processing
import cv2
import numpy as np
import math
import sys
img_path = sys.argv[1] # first parameter is image path
width_squares = int(sys.argv[2]) # second parame... |
bf76c9d5e48ddb3eef3e46d5b17aca8609418b76 | Yonnghohoy/programmers | /Lv.1/Num_String.py | 193 | 3.546875 | 4 | def solution(s):
numbers = ['zero','one','two','three','four','five','six','seven','eight','nine']
for i, num in enumerate(numbers):
s = s.replace(num, str(i))
return int(s) |
091e749031a5027e79708ce9b4b8fe70b3dd7934 | Yonnghohoy/programmers | /Lv.1/pkmon.py | 221 | 3.6875 | 4 | def solution(nums):
answer = 0
_nums = set(nums)
numbers = len(nums)/2
if len(_nums) >= numbers :
answer = numbers
elif len(_nums) < numbers :
answer = len(_nums)
return answer |
17569b41cb8d6caf178a268d2623c92fb634eee2 | seckcoder/lang-learn | /python/type_use.py | 822 | 3.5 | 4 | #! /usr/bin/env python
def __init__(self):
self.message = 'hello world'
def say_hello(self):
print self.message
def __str__(self):
return 'hello world'
attrs = {'__init__':__init__, 'say_hello':say_hello, '__str__':__str__}
bases = (object,)
Hello = type('Hello', bases, attrs)
print 'Hello:', Hello
h = Hello()
h.... |
b50ddb00c6e4cdbad66dee749d2ae61fe59b66f5 | seckcoder/lang-learn | /python/nose/test.py | 625 | 3.796875 | 4 | import unittest2
def add(a,b):
return a+b
def test_add():
#simple test functions
assert add(2,3) == 5
class TestCase(unittest2.TestCase):
def test_add(self):
"""Test case subclasses can also be detected by nose"""
assert add(2,3) == 5
class TestClass(object):
"""Test class is a... |
0c731fe401365ee6a1f4a83d4e7e6c4f4cc06a33 | seckcoder/lang-learn | /python/greenlet_user.py | 999 | 3.609375 | 4 | from greenlet import greenlet
def introduction():
def test1():
print 12
gr2.switch()
print 34
def test2():
print 56
gr1.switch()
print 78
gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()
def switch():
"""
g.switch(*args, **kwargs)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.