blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
67f8f51be67c254cbc8715cc7b3d9f967d50eb1f | vkagwiria/thecodevillage | /Python Week 2/Day 4/exercise1.py | 200 | 4.25 | 4 | # print all numbers between 0 and 100
# print "even" instead of the number if a number is even
for i in range(0,100+1):
if i % 2 ==0:
print("even")
else:
print(i)
|
c178b8e6c1b65d6387e0154f0b238a838d86a5ef | anuragakella/Algorithms | /karatsuba_multiplaication.py | 1,137 | 4.09375 | 4 | # python function to multiply 2 numbers using the karatsuba algorithm
# the example uses 2 - 64 digit strings to perform the operation
def karatsuba(m, n):
m_l = len(m)
n_l = len(n)
# length of each number
if m_l <= 1 or n_l <= 1:
# if the number is a single digit number, just return the product
print("... |
14b30c4ba1fc2e20e7f45f65fc60d9b747c7f15f | RituRaj693/Python-Program | /set_2.py | 636 | 3.59375 | 4 | ##############################update the set
#thisset = {'kohli','raina'}
#thisset.update(['dhoni','tendulkar'])
#print(thisset)
######get the lenght of set
#thisset = ('raina','dhoni','yuvraj')
#print(len(thisset))
######################### remove item from set
#thisset = {'dhoni','raina','jhdav'}
#this... |
c6e2d36b530c166448f12701ef4017d89b1667b4 | ertugrul-dmr/automate-the-boring-stuff-projects | /rockpaperscissors/rockpaperscissors.py | 2,665 | 4 | 4 | # This is a game tries to simulate rock, paper, scissors game.
import random
import sys
def maingame(): # Start's the game if player chooses to play.
wins = 0
losses = 0
draws = 0
while True: # Main loop
print(f'Wins: {wins}, Losses: {losses}, Draws: {draws}')
if wins ==... |
80d0db9bfc50007ad0200478bf50c162f8014190 | HLAvieira/Curso-em-Video-Python3 | /Pacote-download/aulas_python_cev/ex_36_avalia_emprestimo.py | 634 | 3.859375 | 4 | print('\033[1;31;40mBem vindo ao avaliador de empréstimo\033[m')
sal = float(input('Digite o valor da sua renda mensal: R$ '))
preco = float(input('Digite o valor do empréstimo desejado: R$ '))
num_parcelas = float(input('Digite o número de parcelas mensais que você deseja obter: '))
val_parcela = preco/num_parcelas
if... |
4b6e3679a824b285d52e11d48e9f5da87bca4678 | Edvandro-Nogueira/Calculo_Material_Simples | /Calculo_Material_Simples.py | 11,600 | 3.65625 | 4 | #Autor: Edvandro Nogueira de Souza
#Este algoritmo simples faz o cálculo de barras necessárias dado n quantidade de peças.
#Não leva em consideração um aproveitamento sofisticado, ele apenas ordena os elementos de forma decrescente e tenta alocar na barra com a medida dada.
# Imports
from copy import deepcopy
#arquiv... |
bd4c7df02cddc1430b167299adac52818b6fd35d | RobinMelcher/Projects | /PythonPractice2.py | 819 | 3.578125 | 4 | import random
def NSidedDie(n):
# finish this function
randomNumber = random.randint(1, n)
return randomNumber
def DiceRoller(n, t):
# finish this function
sum = 0
for i in range(t):
sum = sum + NSidedDie(n)
return sum
####TESTS - DO NOT MODIFY###
def ... |
d2aa7e4c549957747b527fbee340608a4f19966d | XiangSugar/Python | /multi_threading.py | 1,077 | 3.84375 | 4 | # coding = utf-8
import time, threading
# 新线程执行的代码:
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep(1)
print('thread %s ended.' % threading.cu... |
5d1b4c396a5de96c6e9b6f444dc689f2833c70ec | leodag/adventofcode2020 | /12/part2.py | 1,293 | 3.640625 | 4 | def read_file(name):
return open(name).read().splitlines()
def parse_instructions(lines):
instructions = []
for line in lines:
instruction = line[:1]
amount = int(line[1:])
instructions.append((instruction, amount))
return instructions
def move(position, direction, amount):
... |
9a4e4ffc7393acd24cfbbff3ea5e2029eeb23d6b | xiaohuanlin/Algorithms | /Leetcode/108. Convert Sorted Array to Binary Search Tree.py | 1,361 | 4.125 | 4 | '''
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One pos... |
0d6ef181fd39fd5e3ca628f7da8a724d3b75e16f | ANatanielK/AI_StrategyGame | /unit.py | 4,034 | 3.5 | 4 | from enum import Enum
import random
from configuration import *
attackClass = {'knight': KnightAttack, 'wizard': WizardAttack}
defenseClass = {'knight': KnightDefense, 'wizard': WizardDefense}
class Unit:
def __init__(self,player,ID,typeOfUnit):
'''Constructor: receives the type of The Un... |
3d1fcadfec16c19dc775df87f993fc0918dc1d7d | jcperdomo/182finalproject | /agent.py | 2,057 | 3.78125 | 4 | import operator as op
PASS = (0, -1)
class Agent(object):
"""The Agent base class to be overridden with each algorithm."""
def __init__(self, idx, hand):
"""Initializes an agent with its starting hand."""
self.idx = idx
self.hand = hand
def firstMove(self):
"""Plays all ... |
fbc7b9f4f255dd6f0dfa701c91e073f2b92ae4d6 | YileC928/CS_sequence_code | /CS_w:_application1/pa3_ngram/basic_algorithms.py | 3,969 | 4.03125 | 4 | """
CS121: Analyzing Election Tweets (Solutions)
Algorithms for efficiently counting and sorting distinct `entities`,
or unique values, are widely used in data analysis.
Functions to implement:
- count_tokens
- find_top_k
- find_min_count
- find_most_salient
You may add helper functions.
"""
import math
from util ... |
7c0e3f24bf9dc548e0bc35a86ff32f44813525aa | jungleQi/leetcode-sections | /classification/data structure/2-array/53-M. Maximum Subarray.py | 790 | 4.21875 | 4 | #coding=utf-8
'''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try cod... |
46ecaa0213ee924030dea9accc5c2cbb91d57f78 | gramschs/angewandte_informatik | /solutions/week07/aufgabe_07_01.py | 511 | 3.8125 | 4 | '''
Aufgabe 7.1
Schreiben Sie Code, der Ihren Vornamen abfragt und anschließend die Länge Ihres Vornamens bestimmt. Dann gibt das
Programm den Buchstaben aus, der als erstes im Alphabet vorkommt. Schreiben Sie einmal Ihren Namen komplett klein, also
z.B. "alice" und beim zweiten Mal mit großem Anfangsbuchstaben, also ... |
554977a2f6c1bb8dc4e3ba03691297879ab2a050 | hdert/python-quiz | /unused_components/db_create.py | 1,975 | 3.921875 | 4 | """See db_create.__doc__."""
from os.path import isfile
import sqlite3
from datetime import date
db_path = "main.db"
def db_create(db_path="main.db"): # noqa: D205, D400
"""Check that the database doesn't exist, create the database, create the
tables, finally connect to the database.
Use os.path.is... |
ce55317c2ccbb827b85c34d81b566c8436fd065e | Austin-Bell/PCC-Exercises | /Chapter_7/rental_car.py | 211 | 3.78125 | 4 | # Wrtie a program that ask that user what kind of rental car they would like.
prompt = input("What kind of car would you like to rent: ")
message = "Let me see what if I can find you a " + prompt
print(message) |
44f9d77bd8e1aa4cba920a7b90488e833a30ce1f | alinaka/stepik-algorithms-course | /divide_and_conquer/count_sort/__init__.py | 661 | 3.65625 | 4 | import sys
def count_sort(numbers, n, M):
helper = [0 for _ in range(M + 1)]
result = [0 for _ in range(n)]
for number in numbers:
helper[number] += 1
for i in range(2, len(helper)):
helper[i] = helper[i] + helper[i - 1]
for j in range(n - 1, -1, -1):
result[helper[numbers[... |
9330f5c264f0aba6a604def3c53440b45984c984 | daniellehu/pennapps-fall-2015 | /db/Python Scipts For Features/healthy_Corner_Stores.py | 891 | 3.546875 | 4 | import json
# Reads the corner store data and then creates a dictionary with the zip as
# a key and the number of stores as its val
def read(file):
with open(file) as json_data:
data = json.load(json_data)
zips = dict()
for i in xrange(len(data["features"])):
#Reading in the zi... |
25bd4552dabc3ee6a7e93f5049ea38fb79968140 | sowmenappd/ds_algo_practice | /arrays_strings/rearrange_pos_neg_array_with_extra_space.py | 509 | 4.1875 | 4 | print("Program to rearrange positive and negative numbers in an array\n");
# This algorithm doesn't maintain the relative order
def rearrange(array):
l = len(array)
idx = 0
for i in range(l):
if array[i] < 0:
array[idx], array[i] = array[i], array[idx]
idx += 1
p = id... |
796392b901db215ed053c25269aa0e5d181cd3fe | shashank1094/pythonTutorials | /InterviewBit/subset.py | 1,666 | 3.875 | 4 | # Given a set of distinct integers, S, return all possible subsets.
#
# Note:
# Elements in a subset must be in non-descending order.
# The solution set must not contain duplicate subsets.
# Also, the subsets should be sorted in ascending ( lexicographic ) order.
# The list is not necessarily sorted.
# Example ... |
805f2d795893591bd298cbae8bddda807cbbdea5 | BilboSwaggins33/Test | /20.py | 703 | 3.796875 | 4 | #history program; records history in list h
#records any undos into r, which allows for redos
h = []
r = []
while True:
print('Commands: undo, redo, else')
choice = input(">>>")
if choice == 'undo':
try:
#pops from history list into redo list
x = h.pop(len(h)-1)
p... |
44518e858ae97ea4cfb096d01c744ce1212cf532 | pwildani/Letter-Roller | /roller/testboard.py | 623 | 3.578125 | 4 | """
Generate a board and print it out.
"""
import board
import sys
class TermBoardUI:
def __init__(self, board):
self.board = board
def draw(self, out=sys.stdout):
for r in range(self.board.rows):
print >>out
for c in range(self.board.cols):
print >>out, self.board.letterAt(r, ... |
3ed3fee3cbc9c313eb4eeb0ef83231ccc4846519 | vijeeshtp/python22 | /inner1.py | 365 | 4.1875 | 4 |
def outer ():
def add (a,b):
return a+b
def diff (a,b):
return a-b
num1 = int(input("Enter num1#"))
num2 = int(input("Enter num2#"))
opr = input("Enter op::")
if (opr== "+"):
print (add (num1, num2))
elif (opr== "-"):
print (diff(num1, num2))
else :... |
f6388e57ca4594dcee409bac7ae2afa4265093ac | ElisaMtz/Python_101 | /Assignment Python 1-6.py | 269 | 3.765625 | 4 | y = int(input("Please write first number: "))
w = int(input("Please write second number: "))
if y >= w:
x = w
else:
x = y
while x > 0:
z1 = y % x
z2 = w % x
if z1 == 0 and z2 == 0:
print(x)
break
x -= 1 ### x = x - 1
|
d343dd2b8da73751e837c98ec58ec0fb7b734080 | AYSEOTKUN/my-projects | /python/hands-on/flask-04-handling-forms-POST-GET-Methods/Flask_GET_POST_Methods_1/app.py | 1,011 | 3.5625 | 4 | # Import Flask modules
from flask import Flask,render_template,request
# Create an object named app
app = Flask(__name__)
# Create a function named `index` which uses template file named `index.html`
# send three numbers as template variable to the app.py and assign route of no path ('/')
@app.route('/')
def index():... |
9078b5157122dc560a42bf76420a1eff12d30e27 | nthauvin/sqrt_sum | /sqrt_sum4.py | 3,763 | 4 | 4 | #!/usr/bin/env python3
"""
This modules combines neighbours cache and derecursion optimization
to solve the Square-sum problem
Computes the solutions from N=7 when no argument is passed
Computes the solution for N if passed as an argument
"""
import sys
import math
import time
import concurrent.futures
Max = 0
if ... |
aca927c3aa341664218629744610f80943a30464 | GMZDYZ/py-exercise | /base-exercise/guessNum.py | 575 | 4 | 4 | # -*- coding: utf-8 -*
"""
@Time:2019-12-26 15:02
@Version:1.0.0
@Author:Yincheats
@Description:猜数字
"""
from random import randint
targetNum = randint(1, 10)
print("guess a num for your glory 😡")
int_yourNum = int(input())
while int_yourNum != targetNum:
if int_yourNum < targetNum:
print("... |
c194b55e2baa67361a7d838e047c1856c20e1991 | ryancheunggit/tensorflow2_model_zoo | /mnist_mlp_eager.py | 5,378 | 3.546875 | 4 | """Example program training/inference on digit recognition problem with tensorflow 2.0."""
import argparse
import cv2
import os
import tensorflow as tf
from tensorflow import keras
from datetime import datetime
# The model here is Multilayer peceptron/Fully connected network with 2 hidden layers.
# The encoder/feature... |
2b0ac0a91670caa7cd4dff5a4124bca56a6fb9f0 | mpralat/notesRecognizer | /staff.py | 668 | 3.734375 | 4 | class Staff:
"""
Represents a single staff
"""
def __init__(self, min_range, max_range):
self.min_range = min_range
self.max_range = max_range
self.lines_location, self.lines_distance = self.get_lines_locations()
def get_lines_locations(self):
"""
Calculates ... |
b6d600cefbef4ba2ed03fd103a5fc448a6b39f96 | rmanojcse06/java-patterns | /src/main/py/bubbleSort.py | 400 | 4.09375 | 4 | def bubble_sort(arr):
if arr:
for i in range(len(arr) - 1):
for j in range(len(arr) - i - 1):
if arr[j+1] < arr[j]:
arr[j+1],arr[j] = arr[j],arr[j+1];
return arr;
def print_arr(arr):
if arr:
for e in arr:
print(e);
mya... |
bff9ebd79ba241364b9e2b37cfa2bc9d40dd68df | marbibu/node | /SegmentIntersection/LineIntersect.py | 3,057 | 3.734375 | 4 | '''
python 2.7
Marek Bibulski 2015
Program implementuje algorytm do sprawdzania czy dwa odcinki na plaszczyznie,
przecinaja sie.
Pierwsze klikniecie na okno spowoduje utwrzenie pierwszego punktu odcinka,
Drugie... drugiego.
Dalsze klikniecia od nowa rozpoczna definiowanie punktow rysowanego odcinka.
Wyniki przeciec... |
7d16d6aebb2a3e598b03074d8cf64862d66e5334 | sanika2106/sanika2106 | /guessing game.py | 948 | 4.28125 | 4 | # Now, we will make a game using loops. We will call this game a guessing game.
# In this game we take any number, let us suppose this number is number 5.
# After this we take any number as an input from the user between 1 to 10. The user tries to guess
# this number.
# Suppose the user gives 3as an input. We will the... |
6304d87b40a414daefaba10adf13ff1442fbf025 | zyx124/algorithm_py | /python/sort.py | 2,770 | 4.28125 | 4 | # sort algorithms
# The default python sort() method uses merge sort.
# Bubble Sort: compare the two adjacent number and make the larger one "float"
def bubbleSort(array):
if not array:
return array
for i in range(len(array)):
for j in range(len(array) - 1):
if array[j] > arr... |
c9282c80fcd12b0762ad10854a8cdb174f262ad7 | aditidesai27/wacpythonwebinar | /DAY01/datatype.py | 176 | 3.703125 | 4 | # name = "neeraj sharma"
x = 5 #int
y = 5.2 #float
z = "neeraj sharma" #string str
p = '5.5'
# q = True / False boolean bool
# print("x")
# print(x)
print(p)
|
42e95062e5f04bc6b21a80b39ca93c0949b09183 | AnkitaPisal1510/assignemt_repository | /pythonpart1.py | 224 | 3.90625 | 4 | user_input=int(input("enter a number:-"))
index1=1
print("")
while index1<=user_input:
print(" ---"*user_input)
print(f"| {0} "*user_input+"|")
index1+=1
if index1==user_input+1:
print(" ---"*user_input)
|
1db502042c35527194bcbcd7cb402454fdf77eaf | beaupreda/domain-networks | /utils/graphs.py | 1,527 | 4 | 4 | """
functions to make accuracy and loss graphs.
author: David-Alexandre Beaupre
data: 2020-04-28
"""
import os
from typing import List
import matplotlib.figure
class Graph:
def __init__(self, savepath: str, fig: matplotlib.figure.Figure, ax: matplotlib.figure.Axes, loss: bool = True):
"""
repre... |
5ddddd3c516d93b4412319fde0c497bc178903d7 | knparikh/IK | /Strings/palindrome_pairs.py | 800 | 3.78125 | 4 | # Given a list of words, find palindrome pairs
# inp: {race, cat, dog, god, car, ma, dam} N, M length
# output : {racecar, doggod, madam, goddog}
# Brute force : O(n2) combine all words
# Approach 2: Hash table: Put every word's reverse in hash table. If word exists
# as prefix in hash and its remaining is palindrome,... |
296ce0e00c7078c1866a1dc30889dd3138fbbf88 | tyrionzt/new_web | /sudoku.py | 6,517 | 3.640625 | 4 | import re
from Tkinter import *
from collections import defaultdict
from random import choice
import tkMessageBox as mb
class Solution: # judge sudoku is avaiable
def isValidSudoku(self, board):
for i in range(9):
locals()["sudoku" + str(i)] = []
for i in range(9):
row = [... |
1856c7327a3fd6e2a4ca7babbadfeb7a10e51e9a | MonCheung/learn_python | /test.py | 24,994 | 4.1875 | 4 | '''
def fact(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * fact(n - 1)
print("intermediate result for ", n, " * fact(", n - 1, "): ", res)
return res
print(fact(20))
'''
'''
#递归算法的实现
def fact(n):
result=1
for i in ran... |
2f544a0f0928ce4faef6169ede372c7c4b595b81 | Eric-programming/PythonTutorial | /PyBasics/5_collections.py | 865 | 3.875 | 4 | from collections import Counter, OrderedDict, deque
# Counter (Count items)
my_str = "abcabca"
my_counter = Counter(my_str) # {a:3, b:2, c:2} => (dict)
most_common_item = my_counter.most_common(1) # (a,3)
my_list = [1, 1, 2, 2, 3, 1]
my_counter = Counter(my_list) # {1:3, 2:2, 3:1} => (dict)
most_common_item = my_c... |
629b704f64a414c81083b252fde1b5d79b707764 | iamharshverma/APIMicroServiceForWordDocFrequencyCount | /WordsCountCLIVersion.py | 4,930 | 3.578125 | 4 | import os
import WordTokanizer
import sys
# Declaring global dict to be used in program
# docToWordsCount : This will store key as docID and value as map of word with frequency
# docID_to_absolute_filepath_dict : This stores key as docID i.e filename and value as full absolute path of file,
# just in case if we want t... |
65b8c519bd6b9516f6766811b034d63404c781bb | iamanobject/Lv-568.2.PythonCore | /HW_6/Andriana_Khariv/Home_Work6_Task_3.py | 208 | 4.21875 | 4 | list_att = input('enter anything: ')
def number_of_characters():
for i in list_att:
print("Character", i, "included", list_att.count(i), "in a given string", list_att)
number_of_characters()
|
e8e610c321d86bb4c5fffc69eb2271115858fb63 | AleByron/AleByron-The-Python-Workbook-second-edition | /chap-5/ex111.py | 213 | 3.703125 | 4 | n = int(input('Enter an integer:'))
na = []
na.append(n)
for i in na:
n = int(input('Enter another integer:'))
if n == 0:
break
na.append(n)
na.reverse()
for i in na:
print(i) |
d57162eb524e1f36dad8cb6f67a2a4d88e15f30e | GanSabhahitDataLab/PythonPractice | /python Statement.py | 1,940 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
# create a Statement that will print out words that start with 's':
st = 'Print only the words that start with s in this sentence'
print(st)
for elm in st.split() :
if elm[0] == 's':
print(elm)
# In[13]:
# print all the even numbers from 0 to 10
for num... |
93e07a3ce41ad717ecfd2785d1f71ae7eaf1cfe3 | yangzongwu/leetcode | /archives/leetcode/0005. Longest Palindromic Substring.py | 2,032 | 4.03125 | 4 | '''
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
'''
#####################Memory Limit Exceeded
#####################Time Limit Exce... |
18c2b3d1e330b9174aa2771ca085f1c3f25008a5 | swatia-code/data_structure_and_algorithm | /trees/transform_to_sum_tree.py | 4,388 | 4.09375 | 4 | '''
PROBLEM STATEMENT
-----------------
Given a Binary Tree of size N , where each node has positive and negative values. Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0.
For example, the following tree
... |
43ad426b59053a8a545cbf6c394517e806797075 | dpk3d/HackerRank | /EqualSignalLevel.py | 1,652 | 4.125 | 4 | """
Two signals are generated as part of a simulation. A program monitors the signal.
Whenever two signals become equal, then frequency is noted. A record is maintained for maximum
simultaneous frequency seen so far. Each time a higher simultaneous frequency is noted this variable
maxequal is updated to higher frequenc... |
de43274dd497a3017b6fe11683a78495b1dd2de3 | rosiehoyem/dsp | /python/advanced_python_dict.py | 3,118 | 3.96875 | 4 | import sys
import csv
import operator
import itertools as it
### Part III - Dictionary
####Q6. Create a dictionary in the below format:
'''
faculty_dict = { 'Ellenberg': [['Ph.D.', 'Professor', 'sellenbe@upenn.edu'], ['Ph.D.', 'Professor', 'jellenbe@mail.med.upenn.edu']],
'Li': [['Ph.D.', 'Assistant Pr... |
7a3ce124d254f451bec498aa8c399bf9b1177b39 | piketan/pike-s-python | /Python/ex29/ex29.py | 421 | 3.875 | 4 | people = 20
cats = 30
dogs = 15
if people < cats :
print("猫太多了世界注定要灭亡")
if people > cats :
print("没那么多猫这个世界安全了")
if people < dogs :
print("全世界都垂涎三尺")
if people > dogs:
print("世界都变干燥了")
dogs += 5
if people >= dogs :
print("123")
if people <= dogs :
print("1231212")
if people == dogs :
... |
446750c547062583a671e48711a68bc29ebf82b1 | flame4ost/Python-projects | /additional tasks x classes/class Transport.py | 2,573 | 3.609375 | 4 | from __future__ import unicode_literals
class Vehicle(object):
def __init__(self, speed, max_speed):
self.speed = speed
self.max_speed = max_speed
print('Было создано транспортное средство')
def accelerate(self,x):
self.speed = self.speed + x
if self.speed > self.max_sp... |
4096dc72e06ba5465915a513397e564eb0174d8e | cdeanatx/FCC-Projects | /Scientific Computing with Python/boilerplate-budget-app/budget.py | 4,417 | 3.796875 | 4 | import math
class Category:
#initialize Class with defaults set to empty or 0.
def __init__(self, name, ledger = None, credit = 0, debit = 0):
if ledger is None:
ledger = []
self.name = name
self.ledger = ledger
self.credit = credit
self.debit = debit
#D... |
b7662bba5e83c6ad11be25a85e7871cc61332e38 | sunnyyeti/HackerRank-Solutions | /Algorithms/Interview_Preparation_Kit/Searching/Minimum Time Required.py | 2,524 | 4.46875 | 4 | # You are planning production for an order. You have a number of machines that each have a fixed number of days to produce an item. Given that all the machines operate simultaneously, determine the minimum number of days to produce the required order.
# For example, you have to produce items. You have three machines ... |
d54c73b58e613723a9e8ea78d54c65b85bddc411 | rupathouti/SimplePrograms | /fileopen2.py | 97 | 3.53125 | 4 | myfile=open("test.txt","r")
for data in myfile.readlines():
print("test.txt contains->", data)
|
e709bc719728e496dbaae2d165fbce2187428d71 | chengjingjing1992/pyone | /test39.py | 535 | 4.125 | 4 | #coding=utf-8
# 给写成这样 string', 'a', 'is', 'it'
# str=" it is a string "
# list=str.split()
# list1=[]
# for i in range(1,len(list)+1):
# list1.append(list[-i])
#
# print(list1)
# 对给定的字符串去空格处理
# str="it is a string "
# # print(str.replace(" ",""))
# 使用一个空字符串合成列表内容生成新的字符串
# str=" def xyz abc ... |
3dafc00fcdec5f35f5b2faf7172bf7dbd784ead9 | MelvinPeepers/Sprint-Challenge--Algorithms | /robot_sort/robot_sort.py | 10,573 | 4.5625 | 5 | """
#### 4. Understand, plan, & implement the Robot Sort algorithm _(6 points)_
You have been given a robot with very basic capabilities:
- It can move left or right.
- It can pick up an item
- If it tries to pick up an item while already holding one, it will swap the items instead.
- It can compare the item it's hol... |
464e11cf9934c5254fe1e56f11c50837d7ba47c7 | DaehanHong/Algorithmic-Thinking-Part-2- | /Algorithmic Thinking (Part 2)/Week 6/project3.py | 6,366 | 3.96875 | 4 | """
Student template code for Project 3
Student will implement five functions:
slow_closest_pair(cluster_list)
fast_closest_pair(cluster_list)
closest_pair_strip(cluster_list, horiz_center, half_width)
hierarchical_clustering(cluster_list, num_clusters)
kmeans_clustering(cluster_list, num_clusters, num_iterati... |
bfc1ccaf6885b4068086057cf0a2d08226b19922 | RodrigoPasini/PYTHON | /pythonExercícios/ex013.py | 319 | 3.765625 | 4 | #Exercício Python 13: Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento.
salario=float(input("Informe o salário do funcionário R$ "))
aumento=salario+(salario*(15/100))
print("O novo salário do funcionário com aumento de 15% é de R$ {:.2f}".format(aumento))
|
0ca90604fba217ba3ffe462a5b79ad8536cf134f | KurnakovMaks/GOST_28147_89_Magma | /gost_28147_89.py | 5,860 | 3.703125 | 4 | def convert_base(num, to_base=10, from_base=10):
# first convert to decimal number
if isinstance(num, str):
n = int(num, from_base)
else:
n = int(num)
# now convert decimal to 'to_base' base
alphabet = "0123456789abcdefgABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < to_base:
return a... |
ed8677c6b5bd96677480b3339ec31399fe93101b | saidsalihefendic/online-programming-school-2021 | /drugo_predavanje/if_kontrolne_strukture.py | 720 | 4.09375 | 4 |
""" Konvertovanje prosjek ocjena
5 -> A
4 -> B
3 -> C
2 -> D
1 -> F
"""
prosjek_ocjena = int(input("Unesite vas prosjek ocjena: "))
print("Vas prosjek ocjena je:", prosjek_ocjena)
konvertovani_prosjek_ocjena = None # tip None
if prosjek_ocjena == 5:
konvertovani_prosjek_ocjena = "A"
elif prosjek_ocjena == 4:
... |
b10ca30f5219935902403726120c53cbd0482d65 | dhavalKalariya/The-Art-of-Doing-Projects | /Conditionals/Problem17-CoinFlipApp.py | 1,056 | 4.21875 | 4 | #Coin Flip App
import random
print("Welcome to the Coin Flip App")
print("\nI will flip a coin a set number of times.")
number = int(input("\nHow many times would you like me to flip the coin: "))
heads = []
tails = []
flips = []
for i in range(1,number+1):
#fliping coin using random library
flip = random... |
9bbd5a19586ff1c2c02e2d37d0f8ae388c6392a4 | Ran05/basic-python-course | /day3_act2.py | 1,009 | 4.09375 | 4 |
#Activity 2 of Day 3:
emp_Name = input("Enter employee name: ")
yrs_in_service = input("Enter years of service: ")
office = input("Enter office: ")
o = f"""
=======Bunos Form========================
"""
print(o) # divider
if int(yrs_in_service) >= 10 and office == "it" :
print("Hi" + " " + emp_Name + "," +... |
7dff81f1dfaaf68b049d1491baf4932fe27040ec | sauravjain2304/exercism_solutions | /grains/grains.py | 161 | 3.625 | 4 | def square(number):
if number <= 0 or number > 64:
raise ValueError("error")
return 2 ** (number - 1)
print(square(64))
def total():
return 2**64 - 1 |
9af5cb757cb1a736d822dd1b323b167b3cd8a1f8 | mtian0415/PythonAndDjangoDepolyment | /conditionals.py | 367 | 3.96875 | 4 | x = 10
y = 13
if x == y:
print(f'{x} is equal to {y}')
elif x > y:
print(f'{x} is greater than {y}')
else:
print(f'{x} is less than {y}')
# not
if not(x == y):
print(f'{x} is not equal to {y}')
numbers = [1,2,3,4,9]
if x in numbers:
print(x in numbers)
if x not in numbers:
print... |
7a20b77e51cbb21904fef20904d21b7dfc5586cc | rodrigobmedeiros/Udemy-Python-Programmer-Bootcamp | /Codes/class_objects.py | 489 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 21:56:03 2020
@author: Rodrigo Bernardo Medeiros
"""
class people():
specie = 'Human'
def __init__(self,name, age,city):
self.name = name
self.age = age
self.city = city
def get_details(... |
fdc5f061cad8dcad1097da2b47b4330f1b29e53a | Surmalumi/homework5 | /work6.py | 696 | 3.578125 | 4 | # Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество.
import re
dict = {}
with open('work6.txt','r', encoding='utf-8') as file:
new_file = file.readlines()
for discipline in ... |
c650cd102eb0103092506ffdc22b9bd972f4c19f | vardis/python-algorithms | /src/graph_cycle.py | 3,577 | 3.59375 | 4 | __author__ = 'giorgos'
"""
Determines if a graph contains a cycle. The graph is expected to be
in adjacency list representation.
Uses depth first search to explore the graph, if a vertex is visited
twice then a cycle exists.
Runs in O(n + m) time where n is the number of vertices and m is the
number of edges.
"""
c... |
686ef20781b44c274a597522ffe87897515c31f7 | NekoPlusPro/pythonProject | /NCRE/4/PY202.py | 658 | 3.75 | 4 | # 以下代码为提示框架
# 请在...处使用一行或多行代码替换
# 请在______处使用一行代码替换
#
# 注意:提示框架代码可以任意修改,以完成程序功能为准
fo = open("PY202.txt","w")
data = input("请输入课程名及对应的成绩:") # 课程名 考分
di={}
sum=0
while data:
t=data.split(' ')
di[t[0]]=t[1]
sum+=eval(t[1])
data = input("请输入课程名及对应的成绩:")
li=list(di.items())
li.sort(key=lambda x:x[1],revers... |
dc2432b535d79062ae007417aecbefee9424d4fd | WenyueHu/python | /advance/04-装饰器.py | 310 | 3.578125 | 4 |
def w1(func):
print('---1---')
def inner():
print('---w1---')
func()
return "w1 + " + func()
return inner
def w2(func):
print('---2---')
def inner():
print('---w2---')
func()
return "w2 + " +func()
return inner
@w1
@w2
def f1():
print('---f1---')
return "hahaha"
ret = f1()
print(ret)
|
59c34966ce1f708290dd9627f2b9a58ed6a966c1 | stephenjfox/py-scratch | /probability/problem_sets/binomial_distribution_2.py | 2,165 | 3.890625 | 4 | """
Day 4: Binomial Distribution II
A manufacturer of metal pistons finds that, on average, 12% of the pistons they manufacture are
incorrectly sized. What is the probability that a batch of 10 pistons will contain:
1. No more than 2 rejects?
2. At least 2 rejects?
Print the answer to each question on its own line:
... |
8b72ec898d778563abe817c2fb1cedc62ea2cdbf | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4476/codes/1747_1531.py | 233 | 3.734375 | 4 | from math import*
x = eval(input("digite o numero: "))
k = int(input("digite o numero: "))
soma = 0
i = 0
sinal = +1
while (i<=k-1):
soma = soma + sinal * x**(2*i)/factorial(2*i)
sinal = - sinal
i = i + 1
print(round(soma, 10))
|
7ace8355b1ae9d55e64e182f9126e1a3df43f575 | AbinDaGoat/coding-summer-session2 | /notes/week_2/conditional_statements.py | 3,235 | 4.15625 | 4 | """
boolean logic is very necessary in order to better understand how conditional statement works
but what are conditional statements?
conditional statements are also known as branching statements, and they evaluate a different block of code
depending on the boolean expressions that are present
NOTE: conditional stat... |
2d3efdbbb2d181108eff2ccff72e577093dbe8d9 | mindful-ai/oracle-june20 | /day_02/code/11_understanding_functions_and_modules/project_b.py | 386 | 3.875 | 4 | # Project B
# Find all the prime numbers between a user
# given range
import project_a_new
# Inputs
start = int(input("Enter the start : "))
end = int(input("Enter the end : "))
# Process
primes = []
for num in range(start, end + 1):
if(project_a_new.checkprime(num)):
primes.append(nu... |
d781329eb6a8881b329aca7082715d33c35d7740 | turo62/exercise | /exercise/sorting_basic.py | 586 | 3.953125 | 4 | def sorting_nums(numbers):
print(numbers)
N = len(numbers)
for i in range(N):
for j in range(N - 1):
if numbers[j] > numbers[j + 1]:
temp = numbers[j + 1]
numbers[j + 1] = numbers[j]
... |
ccf7d2989ce67f8d49449c6a9cacc74c98a63b53 | bam0/Project-Euler-First-100-Problems | /Problems_41-60/P51_Prime_Digit_Rep.py | 5,236 | 4.4375 | 4 | '''
Problem: Find the smallest prime which, by replacing part of
the number (not necessarily adjacent digits) with the same digit,
is part of an eight prime value family.
One of the first things we should try to do in order to solve this
problem is narrow down how many digits we need to replace. If we
replace 1 or 2 d... |
25f6613cb81b58f1c87d087cfe4bbaf8532d20d7 | yaHaart/hometasks | /Module21/06_deep_copy/main.py | 1,240 | 3.5 | 4 | from copy import deepcopy
site = {
'html': {
'head': {
'title': 'Куплю/продам телефон недорого'
},
'body': {
'h2': 'У нас самая низкая цена на телефон',
'div': 'Купить',
'p': 'Продать'
}
}
}
def parsing_dict(struct, telephone_nam... |
686fa642a5c45545bc4ff53f5c42c588e409581c | RevathiM25/python-programming | /beginner/hello.py | 68 | 3.84375 | 4 | n=int(input("enter"))
for i in range(n):
i="hello"
print(i)
|
997b82e5511470dee620e58c0ad3c027ab62a1e6 | Yao-Phoenix/TrainCode | /listtest.py | 297 | 3.765625 | 4 | #!/usr/bin/env python3
import sys
if __name__ == '__main__':
a_list=[]
b_list=[]
for argv in sys.argv[1:]:
if len(argv) <= 3:
a_list.append(argv)
elif len(argv) > 3:
b_list.append(argv)
print(' '.join(a_list))
print(' '.join(b_list))
|
78b230ce7f3cb10fe2025c299f0e4433ac85adaf | WenzheLiu0829/Extreme_computing | /assignment2/task2/reducer.py | 701 | 3.53125 | 4 | #!/usr/bin/python
import sys
import heapq
#create heap queue
top_10_question = [ ]
heapq.heapify(top_10_question)
for line in sys.stdin: # for ever line in the input from stdin
line = line.strip() # Remove trailing characters
id, value = line.split("\t", 1)
value = int(value)
# populat... |
010255f865f36158408d94aa34f431e40122afe7 | niqaabi01/Intro_python | /Week7/Support.py | 1,072 | 3.90625 | 4 | #creating an automated tech response to single inputs = key words
#Saaniah Blankenberg
#2020/06/17
def intro():
print('Welcome to the automated technical support system.')
print('Please describe your problem.')
def add_input():
return input().capitalize()
def main():
intro()
problem = add_in... |
f77eaf310c9d0bb9b2ac30dec25fe254af61a69f | matthewschaub/ToPL | /P5/check.py | 3,349 | 3.828125 | 4 | from lang import *
# Implements the typing relation e : T, which
# is to say that every expression e has some type
# T. If not, the expression is ill-typed (or
# sometimes ill-formed).
# The (only) boolean type
boolType = BoolType()
# The (only) integer type
intType = IntType()
def is_bool(x):
# Returns true if x... |
16794e14b0b22a43d25e81f71957a94abea14908 | kinsei/Learn-Python-The-Hard-Way | /ex19-1.py | 315 | 3.703125 | 4 | # This was written for python 2.7
# This is a part of Learning Python The Hard Way exercise 19
# The pourpose of this exercise is is to write a function and run it 10 different ways
start_number = int(raw_input("Enter PC NUM:"))
def add_number(start_number):
print start_number + 1
add_number(start_number)
|
7cf73f2928c0ec9032b67a26a08ccf46b3664ac0 | serhiistr/Python-test-telegram | /classmethod.py | 1,581 | 4.0625 | 4 | # Class
# Название класса пишутся с большой буквы
class Dog():
# __init__ специальный метод, который автоматически выполняется при создании
# каждого нового экземпляра класса. Т.е. отвечает за базовый функционал,
# который будет отрабатываться каждый раз при создании нашего обьекта (собака :))
# self - указывает, чт... |
1fa0d64ee01cc9e19651b695e80bbcb816c41d52 | mike171001/ALLESVANPYCHARM | /Al het huiswerk/4. Functie met if 2.0.py | 245 | 3.75 | 4 | def new_password(oldpassword, newpassword):
if len(newpassword) <6:
print(True)
newpassword = input("What will be your new password?")
oldpassword = input("what was your old password? ")
new_password(oldpassword,newpassword) |
e8e4bdeb81de49ade6793c0dfbb215736c75804e | gabrielponto/eletronics | /main.py | 1,668 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
num1 = sys.argv[1]
num2 = sys.argv[2]
def get_bin_string(number):
return bin(int(number)).replace('0b', '')
bin_num_1 = get_bin_string(num1)
bin_num_2 = get_bin_string(num2)
def portAND(input1, input2):
return '1' if int(input1) and int(input2) else '0'
... |
629d01e074ffd1d5c7278775f3d75870016e4f40 | vedantshr/python-learning | /practice/Doubly_Linked_List.py | 2,349 | 4.125 | 4 | class Node:
def __init__(self, data=None):
self.next = None
self.prev = None
self.data = data
class doublylinkedlist:
def __init__(self):
self.head = None
def Insert(self, newdata):
NewNode = Node(newdata)
if self.head is None:
self.head = NewNode
... |
78f4f464de53e50f6eda9b803ad99d3f80304132 | pabloApoca/PYTHON-COURSE | /functions.py | 341 | 3.90625 | 4 | def hello(name="Person"):
print("Hello world " + name)
hello("Pablo")
hello("Martin")
hello()
def add(n1, n2):
return n1 + n2
print(add(10, 30))
print(len("Hello"))
# lambda son funciones anonimas que resiben un numero de argunmento pero que solo resiven una expresion
add = lambda num1, num2: num1 + num2... |
3ab1e960084727d2c8d4d34b992529cdc33bba10 | HanSeokhyeon/Baekjoon-Online-Judge | /code/9663_n-queen.py | 994 | 3.75 | 4 | def n_queen(chess, case, n):
if n == 0:
case.append(1)
return
for i, row in enumerate(chess):
for j, v in enumerate(row):
if v == 0:
place_queen(chess, j, i)
n_queen(chess, case, n-1)
pass
def place_queen(chess, x, y):
f... |
5a5a5b1783811e8f35bda9114c4a663a015d99e3 | M4573R/udacity-1 | /cs262/problems/exam/problem5.py | 3,458 | 3.734375 | 4 | __author__ = 'dhensche'
# Turning Back Time
#
# Focus: Units 1, 2 and 3: Finite State Machines and List Comprehensions
#
#
# For every regular language, there is another regular language that all of
# the strings in that language, but reversed. For example, if you have a
# regular language that accepts "Dracula", "Was... |
7f675cd84ec04f14c559fcf77178a070b466f155 | dharmit01/competitve_coding | /110A.py | 110 | 3.59375 | 4 | s = input()
li = (4,7)
for str in s:
if str not in li:
print("NO")
exit
print("YES") |
af26b72bee59c984337d6b52d3792cd0960c3c70 | Peng-Zhanjie/The-CP1404-Project | /Work4/list_exercises.py | 1,157 | 3.9375 | 4 | usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob']
def main():
numbers=[]
Count=0
read=True
while (read!=False):
try:
number... |
54b1293e0f16953bb35739c1a9998dd07d3314b0 | LiaoU3/CodeWars | /4kyu/VigenèreCipherHelper.py | 1,374 | 3.515625 | 4 | # https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3/train/python
class VigenereCipher(object):
def __init__(self, key, alphabet):
self.key = key
self.alphabet = alphabet
def encode(self, text):
key_string = ''
encoded = ''
num = 26 if self.alphabet[0] == 'a' else... |
e2a9f38f5ee7fbe4dd84bd999714333d8000fa1f | fantastic001/fluidsim | /lib/draw.py | 468 | 3.734375 | 4 |
def draw_from_function(grid, n, m, func, params={}):
"""
Draws boundary
if func(x,y) is True, then it will be solid, fluid otherwise
"""
for i in range(n):
for j in range(m):
grid[i][j] = func(j,i,n,m, **params)
def border_draw(grid,n,m):
"""
Draws solid borders
... |
fac8c470e62413e1766aca7408c9643c73abaaef | vrublevskiyvitaliy/verification | /ordered tests/stack.py | 811 | 3.921875 | 4 | class Stack():
def __init__(self):
self.__items = []
self.__index = 0
def __len__(self):
return self.__index
@property
def is_empty(self):
return self.__index == 0
def peek(self):
if self.is_empty:
raise IndexError("Cannot peek from an empty st... |
03b7d925d78d284e5b32fae30d825c40dcfcb5ec | nbiadrytski-zz/python-training | /p_advanced_boiko/visibility/closure_example.py | 345 | 4 | 4 | def maker(N): # outer function that generates and returns a nested function, without calling it
def action(X):
return X + N
return action
nested_func = maker(3) # nested_func is actually action() returned by maker(); pass 3 to arg N
print(nested_func(2)) # pass 2 to X, N remembers 3: 2 + 3 = 5
pri... |
269a283f1f9ea9f1955064eceb19929c89ae6d02 | dodieboy/Np_class | /PROG1_python/coursemology/Mission51-VitalityPoints.py | 1,887 | 4.125 | 4 | #Programming I
#######################
# Mission 5.1 #
# Vitality Points #
#######################
#Background
#==========
#To encourage their customers to exercise more, insurance companies are giving
#vouchers for the distances that customers had clocked in a week as follows:
#########################... |
1d47cac60cafbd9bc8193419447e19be0a2115ec | raybrightwood/-Python | /homework1-6.py | 266 | 3.84375 | 4 | a = int(input("Введите результат спортсмена за первый день"))
b = int(input("Введите необходимый результат спортсмена"))
day = 1
while a < b:
a = a * 1.1
day = day + 1
print (day)
|
2f0280abbfe3776ae00d19a37cf50c5824817ddd | bigeyesung/Leetcode | /160. Intersection of Two Linked Lists.py | 1,202 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA, headB) -> ListNode:
p1, p2 = headA, headB
while p1 != p2:
# if p1:
# print("p1:",p1.val)
... |
fd0ce75c48c705b16c5a3b3f843a338ecb541db5 | JiniousChoi/encyclopedia-in-code | /languages/figuredrawer/circle.py | 301 | 3.75 | 4 | from PIL import Image, ImageDraw
SIZE = 256
r = SIZE / 3
image = Image.new("L", (SIZE, SIZE))
d = ImageDraw.Draw(image)
for x in range(SIZE):
for y in range(SIZE):
is_inner = (x - SIZE//2)**2 + (y - SIZE//2)**2 <= r**2
d.point((x,y), is_inner * 255)
image.save('./circle.jpg')
|
ad9acb3c76717a00980265af26c69ea735f5b3ea | asharkova/python_practice | /UdacityAlgorithms/lessons1-3/binarySearchAlgorithm.py | 1,196 | 4.21875 | 4 | """You're going to write a binary search function.
You should use an iterative approach - meaning
using loops.
Your function should take two inputs:
a Python list to search through, and the value
you're searching for.
Assume the list only has distinct elements,
meaning there are no repeated values, and
elements are in ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.