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 |
|---|---|---|---|---|---|---|
f9aadfa2010ddc67bf004e3f782bc55f22d3ed6f | akashjain15/hackerrankpythonpractice | /word-order.py | 208 | 3.5 | 4 | from collections import *
ord = defaultdict(lambda : 0)
for i in range(int(input())):
x = input()
ord[x] += 1
print(len(ord))
for i,j in ord.items():
print('{} '.format(j),end='')
|
e901d845e099fa7da03fcc37458ce4ee03ac16c4 | Ncastro878/SolvedProgrammingProblems | /Code Abbey/#10 - LinearFunction.py | 479 | 3.765625 | 4 | def lin(input):
nums = input.split()
nums = [int(num) for num in nums]
answer = ''
pairs = nums[0]
nums.remove(nums[0])
#basically calculate slope, then solve
#for b, and cast as ints
for i in range(0, len(nums), 4):
x1, y1, x2, y2 = nums[i], nums[i+1], nums[i+2], nums[i+3]
... |
3ce46d355495febb19e8573ee68eafd1909b7689 | iamanobject/Lv-568.2.PythonCore | /HW_6/serhiiburnashov/Home_Work6_Task_1.py | 465 | 4.375 | 4 | def largest_number_of_two_numbers(first, second):
"""This function returns the largest number of two numbers."""
largest_num = max(first, second)
return largest_num
first_number, second_number = (
int(input("Enter first number: ")),
int(input("Enter second number: "))
)
largest_number = largest_n... |
05bcbac3575ffca88099e05f03ea0326a488d696 | Sebbenbear/ctci | /data-structures/Q2_1_RemoveDups.py | 1,937 | 3.796875 | 4 | # Write code to remove duplicates from an unsorted linked list.
# FOLLOW UP How would you solve this problem if a temporary buffer is not allowed?
class SinglyLinkedList:
def __init__(self):
self.head = None
def insert(self, val):
if self.head:
self.head.appendToTail(val)
... |
bac45bb74114fb08fa477558141ce9be13edc7b9 | MT500-1/Jenkins-project | /calculator.py | 104 | 3.8125 | 4 | def add(x, y):
return x + y
def subtract(x, y):
return x - y
add_answer = add(2, 2)
print(add_answer)
|
6495d0426072f1ac51d687abcf2d9572f8cf1f37 | Jirapongs55/CP3-Jirapong-Sirichottanawong | /functionLoginPriceVat_Jirapong_S.py | 1,285 | 3.828125 | 4 | def login():
usernameInput = input("Username : ")
passwordInput = input("Password : ")
username = "jirapongs"
password = "Jirapong24"
if usernameInput == username and passwordInput == password:
return True
else:
return False
def showMenu():
print("Welcome !!!")
print("-" ... |
9e0d970ab3f63939e13a9119a00cb05a29ed687b | julianaldi53/bfor206_fall2021 | /1pm/pandas_intro.py | 1,793 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 29 13:18:50 2021
@author: leespitzley
"""
#%% imports
import numpy as np # this is an alias
import pandas as pd # also an alias
# from matplotlib.pyplot import hist
#%% create a random matrix
matrix = np.random.randint(0, 100, size=(100, 4))
p... |
30e2ebbff6ce689e764e415941c9870b60e05028 | emmyblessing/alx-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 192 | 3.640625 | 4 | #!/usr/bin/python3
for i in range(10):
for j in range(i + 1, 10):
print(
"{}{}".format(i, j),
end=", " if int(str(i) + str(j)) < 89 else "\n"
)
|
9874afd53373360ccbcfb9da81557a5d39cfc934 | bhanu-python/Python-Data | /script_que/palindrome_str.py | 142 | 3.96875 | 4 | stri=input(" enter the string : ")
if stri == stri[::-1]:
print("string is paindrome: "+stri)
else:
print("String isnt palindrome")
|
00aa781c6a2cf927f72fe68ba0fa87928a880149 | benevolentblend/ClipGrouper | /ClipGrouper.py | 2,178 | 3.78125 | 4 | """
Author: Benjamin Thomas
Major: Software Development
Creation Date: April 5th, 2019
Due Date: April 5th, 2019
Course: Independent Study
Professor: Dr. Frye
Filename: CliperGrouper.py
Purpose: The program will look in the directory passed for mp4 or mov files,
... |
f42a03c7ea871f9b23795034b048cd2198db023d | m358807551/Leetcode | /code/questions/261~270/261.py | 830 | 3.65625 | 4 | """
https://leetcode-cn.com/problems/graph-valid-tree/
"""
from collections import defaultdict
class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
adj = defaultdict(dict)
for a, b in edges:
... |
313c73d343e9fc210ea26ec5777a0b1a95f67d2a | Galogico/OBI-exercices | /OBIEX1.py | 153 | 3.6875 | 4 | distancia = int(input())
if distancia <= 800:
print (1)
if distancia > 800 and distancia <= 1400:
print (2)
if distancia > 1400:
print (3) |
9210a20750e890296a76ab5bbd8cdcc9d0961080 | mgermaine93/python-playground | /python-coding-bat/logic-2/round_sum/test_module.py | 4,657 | 3.53125 | 4 | import unittest
from round_sum import round_sum
class UnitTests(unittest.TestCase):
def test_16_17_and_18_returns_60(self):
actual = round_sum(16, 17, 18)
expected = 60
self.assertEqual(
actual, expected, 'Expected calling round_sum() with 16, 17, and 18 to return "60"')
... |
ea9e2fb4116c2324a76944d9a6f410b76da03d6b | mmveres/python05_12_2020 | /ua/univer/lesson02/task_if/task04.py | 489 | 3.640625 | 4 | # 4. Даны имена 2х человек (тип string). Если имена равны,
# то вывести сообщение о том, что люди являются тезками.
def namesake(name1= "anonim", name2="anonim"):
if name1 == name2:
print('The names are the same')
else:
print('Names are different')
def task04_tezki():
n1 = (input('Enter f... |
f7547a874a44b700bfdacc2e873cca6e2ccd7d9e | Ederbal/python_algoritmos | /2016.1/estruturas/medias.py | 745 | 3.5 | 4 | qtd_alunos = 1
qtd_notas = 3
alunos = []
def calc_media(notas):
media = 0
for nota in notas:
media += nota
return media/len(notas)
for aluno in range(qtd_alunos):
print('-----------------------')
print('ALUNO Nº'+str(aluno+1))
print('-----------------------')
nome = input('Nome:... |
04b020041a3fc001b8c991a089cf731643b2037b | commanderkid/codeabbey | /Blackjack Counting.py | 1,688 | 3.6875 | 4 | # codeabbey
#codeabbey_my_attempts
#The game of Blackjack has very simple rules: players should take cards one by one trying to collect more points than opponents, but not exceeding 21 (refer Wikipedia for complete rules).
#The deck contains all cards from 2 to 10 inclusive, which are counted according to their value,... |
fc09097d3be62c80b2072cba63db8e4fbb5650d3 | Qasim-Habib/Rush-Hour | /rush_hour.py | 27,924 | 3.828125 | 4 | import sys
from queue import PriorityQueue
import copy
import time
def list_to_string(arr): #convert list to string
str_node=''
for i in range(0, Puzzle.size_table):
for j in range(0, Puzzle.size_table):
str_node += arr[i][j]
return str_node
def print_array(ar): #print the array in the ... |
85ec92d8527899770c6690213e6733b6b62c01f3 | hkdeman/algorithms | /python/data-structures/btnode.py | 1,408 | 3.578125 | 4 | class BTNode:
def __init__(self,elem=None,left=None,right=None,parent=None):
self.elem = elem
self.left = left
self.right = right
self.parent = parent
def get_elem(self):
return self.elem
def get_left(self):
return self.left
def get_right(se... |
29f6a0226958b4213d864dff6c75c2034629c6f7 | AbelRapha/Python-Exercicios-CeV | /Mundo 1/ex0022 Analisador de Textos.py | 354 | 3.96875 | 4 | name = str(input("Digite seu nome completo ")).strip()
nomeMaiusculo = name.upper()
nomeMinusculo = name.lower()
letras = name.replace(" ", "")
first_name = name.split()
print(f"Seu nome com letras maiusculas: {nomeMaiusculo}\n Em minusculas {nomeMinusculo}\n O nome tem ao todo {len(letras)} letras\n O primeiro nome... |
14a22cafee3c397a16237e9d7727bdeea5459429 | NikiDimov/SoftUni-Python-Fundamentals | /lists_basics_05_21/invert_values.py | 94 | 3.59375 | 4 | values = input().split()
invert_values = [int(el) * -1 for el in values]
print(invert_values)
|
476220e7d8c891c297d2261a3ee9182c18057e21 | luckyguy73/wb_homework | /4_week/reverse_nodes_in_k_group.py | 560 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if head:
node = head
for _ in range(k - 1):
node = node.... |
789971441be75a33a5b8a05153b43820408e748e | DSehmi/Data14Python | /files_and_errors/hello_text_files.py | 3,431 | 4.125 | 4 | # file = open("order.txt")
# TYPE OF ERRORS
# ZeroDivision error
# Indentation error
# Name error
# ModuleNotFound error
# Syntax error
# Type error
# Key error
# Attribute error
# Index error
# Assertion error
# Recursion error
# try:
# print("Trying to open the file...")
# file = open("order.txt")
# pr... |
dadeac951912318b37b40c3191007d7feaa2ff3c | mateus-ocabral/exercicios-prog | /exercicios/ex078i.py | 470 | 3.90625 | 4 | lista = []
for i in range (0,5):
num = int(input(f"Digite um valor para a posicao {i}"))
if i == 0:
menor=num
maior=num
lista.append(num)
else:
if num > maior:
maior = num
lista.append(num)
if menor > num:
menor = num
... |
ecf8662b8ff8dfba7dd8c81b493ef73e5c5f2cb2 | mightyfrog80/Project_Euler | /Experiments.py | 2,250 | 4.34375 | 4 |
#Lab Insights:
#Lab 5
'''
1. dict.copy(), list.copy(), set.copy() all copy without aliasing
2. dictionary comprehensions-
dict = {1:2, 3:4}
dict2 = {x: dict[x] for x in dict.keys()}
3. How to retrieve an element from a set:
a = set([1,2,3])
... |
3a9e7b86b24621d6d1bac92244f23c37e941bae3 | IAmAbszol/DailyProgrammingChallenges | /DailyProgrammingBookChallenges/Review/solution.py | 725 | 3.546875 | 4 | from collections import defaultdict
def problem(arr, compare):
char_count = defaultdict(int)
for c in compare:
char_count[c] += 1
missing = len(compare)
min_left, min_right = 0, len(arr)
l_idx = 0
for r_idx, element in enumerate(arr):
if char_count[element] > 0:
missing -= 1
char_count[element] -= 1
... |
c7515e8153958a6efa3ebee7c640d4fc2867f9b3 | cshintov/python | /think-python/ch15.Classes/ex4_draw.py | 3,596 | 4.375 | 4 | '''
exercise 15.4 Draw Rectangle and Circle
'''
from swampy.World import World
class point(object):
'''a point with attributes
x and y coordinates'''
class rectangle(object):
'''a rectangle with attributes
leftbottom corner,height,width'''
class circle(object):
'''a circle with attributes
center ... |
7e7b4f1c1817c98f20737859abc8e50273ecd5bc | eltechno/python_course | /Functions.**kwargs.py | 240 | 3.59375 | 4 |
def print_all(**kwargs):
"""Print out key-value pairs in **kwargs"""
#print out the key-value pairs
for key, value in kwargs.items():
print(key + ":" + value)
print(print_all(name = "paulo", direccion = "guatemala")) |
95f4a1dd90c62847c8f8e98d7934742a756ff43b | Joydeepgill/PracticeProblems | /Leetcode/kidsWithCandies.py | 455 | 3.71875 | 4 | def kidsWithCandies(candies, extraCandies):
#base case A) empty list
if(candies == []):
return candies
newArr = []
flag = False
for item in range(len(candies)):
if(candies[item] + extraCandies >= max(candies)):
newArr.append(True)
else:
newArr.append(False)
continue
return newArr
print(kidsW... |
dd430a410728b2bee1e7ba52927791886ec21c2d | drjod/coderesourcesandwastereservoir | /pyMunich2016/tdd/code/changeMachine.py | 2,200 | 3.9375 | 4 |
class Coins():
def __init__(self, twenty, ten, five, two, one):
if not int(twenty) is twenty or not int(ten) is ten or not int(five) is five or not int(two) is two or not int(one) is one:
raise ValueError("Values must be integer")
if twenty < 0 or ten < 0 or five < 0 or two < 0 or one <... |
fa0b6dadb2ed2a32ff649e5542b7261bee3dfefa | padovese/python-projects | /intermediate/tuples.py | 484 | 3.796875 | 4 | #list: ordered, immutable, allow duplicate elements
import sys
myTuple = ("Bruno", 29, "Padovese")
print(myTuple)
print(type(myTuple))
item = myTuple[0]
print(item)
for i in myTuple:
print(i)
if "Padovese" in myTuple:
print("yes")
else:
print("no")
print(len(myTuple))
myList = list(myTuple)
print(myLi... |
05145ae09df2f2b15201cfbd5ee26a00acccdb23 | yoontrue/Python_work | /Python_day04/ex11_clickEvt.py | 797 | 4 | 4 | from tkinter import Tk
from tkinter.ttk import Label
x = 120
y = 80
def leftClick(event) :
global x
x -= 10
lbl.place(x=x, y=y)
def wheelClick(event):
global x
x = 120
lbl.place(x=x, y=y)
def rightClick(event):
global x
x += 10
lbl.place(x=x, y=y)
def scroll... |
cd142a32268f3a936b67e484892ce110d0fcb2b0 | Bunce-Jaymes/Python-Programs | /Piggy Bank 1.0.py | 2,072 | 3.921875 | 4 | #Piggy Bank 1.0
import time
print ("Hello welcome to Piggy Bank 1.0!")
print()
name= input("Hello what is your name?")
print ()
def main():
print ("Hi,"+name+" nice to meet you!")
print ()
pennies= eval(input("How many pennies do you have: "))
print ()
pennies= pennies*.01
#round (penni... |
8693bb136df081475aef2d72fbd56eef8e0ef23c | lchoward/Practice-Python | /DP/ClimbingStairs.py | 1,036 | 3.984375 | 4 | # background: You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
# Note: Given n will be a positive integer.
from typing import List
class Solution:
def climbStairs(self, n: int) -> int:
# check for... |
fcd1f97d9a9c4f511ece04fba00f91910891aad3 | EionLight/Python_Learning | /Lists.py | 104 | 3.765625 | 4 | num=[0,10,22,23,45,55,32,444]
max = num[0]
for x in num:
if x>max:
max = x
print(max) |
5850e464f9b29785ecf93c66c11ac6391a7d1741 | Pastutia/Generatory_hasel | /Generator_hasel_2.py | 486 | 3.71875 | 4 | #Python 3.9 Generator Haseł 2
import random
import string
długość = int(input("Wpisz długość hasła: "))
password = "".join([random.choice(string.ascii_letters) for _ in range (długość)])
print("Wygenerowane hasło (litery duże i małe): ", password)
password = "".join([random.choice(string.ascii_letters + string.punc... |
394878cb9f863fdfa16d2e49e4fef80c67a4a038 | IanMadlenya/BYUclasses | /CS_598R/Week1/lagrange_4square.py | 659 | 3.59375 | 4 | from math import sqrt, pow
import sys
def n_4_squares(nn):
"""
Determine the number of ways the number n can be created as the
sum of 4 squares.
"""
how_many = 0
n = nn
for a in xrange(0, int(sqrt(n)) + 1):
for b in xrange(0, min(a, int(sqrt(n - pow(a, 2)))) + 1):
for c... |
065f93bc6814aa302435a600128657857054ebaf | michielderoos/EmojiKeygen | /emojikeygen/shorteners/util.py | 1,433 | 3.53125 | 4 | ## Utility functions for shortening functions
import random
import hashlib
import baseconvert
from emojikeygen import config
from emojikeygen.shorteners import alphabet
def generate_random_list(length):
""" Generates list of n random values between 0 and len(alphabet) (e.g. 3 => [4, 22, 21])"""
return [random... |
38bcc984f928597b1383f96947a9f66c5a774f62 | eduardoml93/sem-pacman-python-fork | /oop/pieces.py | 2,322 | 3.84375 | 4 | import random
class Piece:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def is_ghost(self):
return False
def is_wall(self):
return False
def is_pill(self):
return False
def is_pacman(self):
return False
def is_empty(self):
... |
561b7c71e1b0b9130a8c1f8d3df07685f080cf9b | zihaoj/LCPractice | /Array/245.py | 1,846 | 4.0625 | 4 | '''
245. Shortest Word Distance III
This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
word1 and word2 may be the same and they represent two in... |
c6b0b0559f7a9025aa530bda15fba10bd953b10b | bea03/learnpythonhardway3 | /ex17.py | 978 | 3.609375 | 4 | from sys import argv #this imports the argv for use.
from os.path import exists #this imports exists() for use in checking t/f if exists?
script, from_file, to_file = argv #these are variables being assigned for the args in script command line
print(f"copying from {from_file} to {to_file}")
#no mode arg given for op... |
ed963c98a5fc422d79646e08c54c8a1f476ce206 | dsayan1708/Python | /ClassMethod.py | 719 | 3.640625 | 4 | class Laptop():
count_instance = 0
def __init__(self, brand_name, model_name, price):
#initializing instance varaibles
self.bn = brand_name
self.mn = model_name
self.p = price
Laptop.count_instance+=1 #counting the number of instances
def apply_disc(self, di... |
6b4bb4c3ebd9be505856b1608144bd2f37327bfe | Aeternix1/Python-Crash-Course | /Chapter_7/7.1_rental_car.py | 221 | 3.859375 | 4 | #Write a proram that asks the user what kind a rental car they want and prints
#Out a message about that car
car = input("What kind of rental car would you like? ")
print("Let me see if I can find you a " + car.title()
|
4adbd2a5c9b762a7b5e1553b0d06c541dfc14d0d | santiagoahc/coderbyte-solutions | /easy/min_diff.py | 412 | 3.578125 | 4 |
def CountingMinutesI(str):
def to_minutes(t):
h, m = map(int, t[:-2].split(':'))
if t[-2] == 'p':
h += 12
return h * 60 + m
t1, t2 = map(to_minutes, str.split('-'))
if t1 < t2:
return t2 - t1
else:
return ( t2 + 24*60) - t1
assert CountingMinutesI('9:00am-10:00am') == 60
assert ... |
316cb572c6abd50c32e711add6502843f5ba8d5f | Tom-Jager/bayesian-umis | /bayesumis/umis_data_models.py | 21,508 | 3.609375 | 4 | """
Module containing all the data models for the UMIS diagram, not
mathematical models
"""
import sys
from typing import Dict
class Uncertainty():
"""
Superclass for representating uncertainty around a stock or flow value.
Representations must have an expected value to use for display
Attributes
... |
40167c0aadeb6c1c5220a3eb803a06a84a9c40e2 | AmericanEnglish/CS240 | /cbarajas_hw11.py | 6,367 | 3.703125 | 4 | import tkinter
import tkinter.filedialog as dialog
import tkinter.messagebox as mbox
class Field:
""" Generates a Field object which is used as the backbone for other
Field-like objects."""
def __init__(self, frameZ, entrylabel, buttonlabel, n, commandvariable):
"""(Field, Frame, str, str, Int) ->... |
90b7f7a336fce599630c86006329154769102433 | 824zzy/Leetcode | /A_Basic/String/L0_2299_Strong_Password_Checker_II.py | 702 | 3.59375 | 4 | """ https://leetcode.com/problems/strong-password-checker-ii/
simulate the password check by a few booleans
"""
class Solution:
def strongPasswordCheckerII(self, A: str) -> bool:
if len(A)<8: return False
has_low, has_upper, has_digit, has_special = False, False, False, False
special = set("... |
0c0d930873f23896def6bc7533461f0f6cb08985 | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv21.py | 541 | 3.625 | 4 | # 21. O Sr. Manoel Joaquim acaba de adquirir uma panifcadora e
# pretende implantar a metodologia da tabelinha, que já é um
# sucesso na sua loja de 1,99. Você foi contratado para desenvolver o
# programa que monta a tabela de preços de pães, de 1 até 50 pães,
# a partir do preço do pão informado pelo usuário, conforme... |
1f835495ddf5cf6cdce80e1d78c4ec9837f22187 | RIMPOFUNK/FirstLyceumCourse | /Lesson 12 (Знакомство со списками)/Classwork/1. Список покупок.py | 119 | 3.65625 | 4 | size = int(input())
lst = []
for i in range(size):
elem = input()
lst.append(elem)
for i in lst:
print(i) |
4f8559af4ca961f08dcb2d23484cb8d1591b6355 | harris112/UniProjs | /football1.py | 482 | 3.84375 | 4 | '''number_of_pupils / total_teams / pupils_remaining'''
''' 150 30 0 '''
''' 167 33 2 '''
''' 149 29 4 '''
number_of_pupils = int( input ("Please enter the number of pupils in school") )
total... |
c20d52bbef994a25219fb353b9723c0b63ac6414 | rohegde7/competitive_programming_codes | /cchef-JAN_LC'18-Maximum_Score.py | 1,472 | 3.96875 | 4 | # Author: https://www.github.com/rohegde7 (Rohit Hegde - hegde.rohit7@gmail.com)
# https://www.codechef.com/JAN18/problems/MAXSC
# Problem Code: MAXSC
# status: sub-task1: 1/2 passed, sub-task2: 1/4 passed
"""method:
Sort all the rows of the matrix in decending order.
Assign the max, i.e. 1st el... |
30cb35e9c9805a3d538e5043e28c7c60cbbffc63 | roozbehsaffarkhorasani/assignment4 | /13.py | 226 | 3.515625 | 4 | a = int(input('First number is '))
b = int(input('Second number is '))
c = max(a, b)
d = min(a, b)
for i in range(1, (c * d)):
if ((c * i) % d == 0):
answer = (c * i)
break
print(answer) |
24aab5ad15bdc82acafdefa08df3043b8e9e1a58 | NicholasDowell/Matrix-Calculator | /MatrixOperations.py | 5,881 | 4.15625 | 4 | # The MatrixOperations class includes a group of methods that allow the matrix to be used for row reduction operations
# prints out all values stored in the matrix to the console
import MatrixExceptions
from MatrixExceptions import RowSizeException
# Prints out each value stored in the mateix
def printout(a):
row... |
30e5d347c0644f06fd84cb8e4a3fa0f2053795bd | MeltedHyperion7/regex-matcher | /nfa.py | 726 | 3.5 | 4 | class State:
def __init__(self, transitions=[], is_accepting=False):
self.transitions = transitions
self.is_accepting = is_accepting
def add_transition(self, character: str, state):
# check if the transition doesn't already exist
for transition_char, transition_state in self.tr... |
585776292ea75afc7d4473aeaf3c10a8a0407e06 | Kafka-21/Econ_lab | /Week 4/Python Basics/Frac_12.py | 551 | 3.65625 | 4 | """
from itertools import product
K, M = map(int,input().split())
N = (list(map(int, input().split()))[1:] for _ in range(K))
results = map(lambda x: sum(i**2 for i in x)%M, product(*N))
print(max(results))
"""
"""
N = []
for _ in range(k):
# get input and split into list
l = input().split()
# turn list of strin... |
df61bd1034c7e183921bfb72ec8984a19d979f09 | vnareddy0724/5143-201-OpSys-Nareddy | /assignments/shell/cmd_pkg/history.py | 434 | 3.75 | 4 |
"""
Name: history
Description:
It stores the history of all commands executed.
Params:
*cmd:List of input commands is an argument.
Returns: None
"""
def history(*cmd):
f=open("/home/opsys_group10/Python34/history.txt",'r')
count=len(f.readlines())
count=count+1
f=open("/home/... |
1aef19c1fdfd4c44c413dc29c597fbbf7c17e046 | raptorinsurance/hanabiClone | /test_hand.py | 497 | 3.671875 | 4 | #!/usr/bin/env python
import unittest
from hand import Hand
from card import Card
class TestHand(unittest.TestCase):
def test_new_hand(self):
hand = Hand()
cards_in_hand = hand.get_cards()
self.assertEqual(cards_in_hand, [])
def test_add_card(self):
hand = Hand()
car... |
f67e45cd4f5b7d1c4ab919e0a7e855808c6994a6 | aarti95/MarvellousInfoSystem | /Assignment-1/Assignment1_6.py | 311 | 4.46875 | 4 | # Write a program which accept number from user and check whether that number is positive or
# negative or zero.
print("Enter number: ")
number = int(input())
if number < 0:
print("Input number is Negative")
elif number > 0:
print("Input number is Positive")
else:
print("Input number is Zero")
|
35c712ce5419ab0d55124981ab048d4c0321dc62 | anthonybotello/Coding_Dojo | /Python/Algorithms/singly_linked_list.py | 1,567 | 3.84375 | 4 | class Node:
def __init__(self,val):
self.value = val
self.next = None
class SList:
def __init__(self):
self.head = None
def addtoFront(self,val): #adds value to front of list
new_node = Node(val)
new_node.next = self.head
self.head = new_node
... |
181639a0ee2b09303acc450d2464f35d223ab3d1 | ae-freeman/Hackerrank-challenges | /climbing-the-leaderboard.py | 833 | 3.765625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the climbingLeaderboard function below.
def climbingLeaderboard(scores, alice):
scores_set = sorted(set(scores))
counter = 0
n = len(scores_set)
alice_positions = []
for i in alice:
while (n > counter and ... |
6ca6a1f8aa710b99d3a0dbc3326a6b56d66ea897 | Ynkness/leetcode-python | /29_28_Pascal's Triangle2.py | 356 | 3.71875 | 4 | def getRow(rowIndex: int):
ret = [1] * (rowIndex + 1)
print(ret)
for i in range(2, rowIndex + 1):
print('i:',i)
for j in range(i - 1, 0, -1):
print('j:',j)
ret[j] += ret[j - 1]
print(ret)
return ret
print(getRow(3))
fo... |
e4464b544c8b40b1378c7dc555a7e8600a5fc275 | jknightihiji/project_euler | /problem12/solution.py | 766 | 3.90625 | 4 | #!/usr/bin/env python
#this is the solution for problem #12
from math import sqrt
def triangle_number(n):
return sum(range(1,n+1))
def find_divisors(n):
divisors = [1,n]
i = 2
while i < sqrt(n) :
if n % i == 0 :
divisors.append(i)
divisors.append(n/i)
i+=1
... |
04d81f9a7190f3edc6492884eabafcacac5c88dd | rrpb/automatic-spoon | /problems-set-one/range_sum_bst.py | 723 | 3.515625 | 4 | class TreeNode(object):
def __init__(self,val=0,left=None,right=None):
self.val=val
self.left=left
self.right=right
def get_sum_range(root,low,high):
sum=0
stack =[root]
while stack:
current_node = stack.pop()
if current_node:
if current_node.val >= l... |
a89cc45440852b08c92a22ebeae766f30cef88aa | Wcent/learn-python | /21_tcpip_demo.py | 3,534 | 3.90625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'cent'
'''
a demo about tcp/ip network shows how to program with socket.
TCP:通信双方建立可靠连接,以流形式发送接收数据
UDP:面向无连接
'''
import socket
import threading
# test tcp in client
def tcp_in_client():
# 创建一个socket,AF_INET: IPv4 (AF_INET6: IPv6), SOCK_STREAM:面向流TCP协议... |
d3810429bb22d4e6e77bfad27cee64c1277416be | camano/Aprendiendo_Python | /condicionales/condicionales2.py | 197 | 3.859375 | 4 | print("Verificacion de acceso")
edad_usuario=int(input("introduce tu edad :"))
if edad_usuario<18:
print("No puede Ingresar")
else:
print ("Puede Pasar")
print("El programa ha finalizado")
|
ab2bbd2d67905354da4f6e0f3fe82e2c7347b827 | hoops92/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 1,299 | 4.125 | 4 | def intersection(arrays):
"""
Find intersection between different lists of integers
"""
# Create a cache to save "seen" integers
cache = {}
# Your code here
# Get the total # of lists to look through
num_list = len(arrays)
# Create a lsit to save the intersection values
result =... |
8fa1aa6ac556e32a5a3bc7de3f17744edebe71d3 | Divyamop/HACKTOBERFEST2021_PATTERN | /Patterns/chandu6111.py | 390 | 3.71875 | 4 | n=int(input())
st=n #stars
sp=0 #spaces
for i in range(n):
for k in range(sp):
print(" ",end="")
for k in range(st):
print("*",end="")
print()
sp=sp+2
st=st-1
sp=sp-2
st=st+1
for i in range(n-1):
sp=sp-2
st=st+1
for k in range(sp):
print(" ",end=... |
a04e4ff4a7a00e8fd94fa1236d22080173d486b1 | dagbay/SIT210_Task8.1D_RPi_I2C | /master.py | 791 | 3.546875 | 4 | from smbus import SMBus
addr = 0x8 # Address of where the byte will be sent to.
bus = SMBus(1) # Uses Port I2C1
num = 1
try:
while num == 1:
try:
led_state = int(input("Enter your choice (1/0): "))
except:
continue
if led_state == 1:
b... |
812fd3d22a2f8a314fae7dc49da02698dd57c934 | RekhaKendyala/MLFoundations | /datastructures.py | 1,142 | 4.125 | 4 | # Define the remove_duplicates function
#original_list = []
def remove_duplicates(org_list):
new_list = []
for item in org_list:
if item not in new_list:
new_list.append(item)
return new_list
dup_list = ['a', 'b', 'c', 'a', 'b', 'd', 'd']
print(remove_duplicates(dup_list))
#Sets - Col... |
59b5fb7f3ca807eb0a8194c519d1eebb141f127b | cowboy331/100day_exercises_in_ML | /d3_MLR.py | 1,445 | 3.6875 | 4 | # encoding: UTF-8
# 1 data preprocessing
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv('../datasets/50_Startups.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 4].values
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelEncoder = LabelEncoder(... |
6701275aa985018df2a41f5b570e339f35103e1f | m-niemiec/space-impact | /settings.py | 2,063 | 3.859375 | 4 | import pygame
chosen_resolution = input(
"""Choose resolution in pixels (game will run in a window, so resolutions are lower):
A - Width: 1152px Height: 648px
B - Width: 1792px Height: 1008px
C - Width: 3712px Height: 2088px
"""
)
if chosen_resolution.upper() == 'A':
resolution_width = 1152
re... |
03c8b2e2edecde71ff6366e80d3feb33356c0896 | detech/WsSmarts | /mtik_ws_main.py | 1,345 | 3.515625 | 4 | from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()
import pandas as pd
from datetime import date
import os
#Reference: https://medium.com/@jouneidraza522/yahoo-finance-api-to-get-stocks-tickers-data-in-python-c49820249a18
#https://www.youtube.com/watch?v=eSpH6fPd5Yw
# Stock tickers for... |
071fa4c772ca3d0f1d6d79395e0a96b85277eee5 | gjlmotea/LeetCode | /Python/未整理/LEETCODE 30天挑戰_2020-04/First Unique Number.py | 3,196 | 3.515625 | 4 | from typing import List
import collections
class FirstUnique:
def __init__(self, nums: List[int]):
self.deque = collections.deque()
self.lookup = {}
for num in nums:
self.add(num)
self.remove(num)
def showFirstUnique(self) -> int:
if len(self.d... |
9d4a222a5375e8ad56924f5deb0512634c0c87f7 | hollymillea/Y2Tutorials | /Week9/Solutions/solutions.py | 2,943 | 4.03125 | 4 |
#############################
# TASK 1
#############################
def Swap(List,i,j):
# If we are swapping the elements in List = [2,3] the list would be updated as so:
# List = [2,3]
# List = [5,3]
# List = [5,2]
# List = [3,2]
List[i] = List[i] + List[j]
List[j] = List[i] - List[j]
... |
b69f784f6d49e4f563b1a3cd840c816a33fe0f90 | 09305295654sh/python-code-seri-2 | /mashin hesab t1.py | 1,151 | 3.875 | 4 | import math
while True:
a = int(input())
b = int(input())
print('wellcome to sajjadb univercity ')
print('1) jam')
print('2) afright')
print('3) zarb')
print('4) taghsim')
print('5) sin')
print('6) cos')
print('7) tan')
print('8) cot')
print('9) log')
op... |
c53a0615040e21fab8f909bde84bcbe063ba0e76 | vpuller/GTR_sitespec | /permutations.py | 1,138 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 17:17:17 2015
@author: vpuller
"""
def permute_list(L):
# print L
'''Permutations of the elements of list L of different elements'''
if len(L) == 2:
perms = [L,L[::-1]]
else:
perms = []
for element in L:
Lred = list(... |
2461ffe24aae3eeb31f88b51170da243229f0148 | ace7chan/leetcode-daily | /code/202012/20201208_842_splitIntoFibonacci.py | 1,383 | 3.59375 | 4 | from typing import List
class Solution:
def is_valid_num(self, S, left, right):
if right > len(S):
return False
if int(S[left:right]) > 2147483647:
return False
if S[left] == '0' and right - left > 1:
return False
return True
def is_fibonacc... |
52d41c4c0b0a64dc976f2677badad6a7f899b0cf | nurseiit/comm-unist | /data-science-not/weeks/m04_trees/p0/heap_priority_queue.py | 3,620 | 3.6875 | 4 | # Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of... |
b791b9a721765f0b5325d90f45cc409e4ef6601a | batermj/data_sciences_campaign | /ProgrammingLanguagesPortal/Python/Algorithms/py/bit/find_missing_number.py | 1,531 | 3.984375 | 4 | """
Returns the missing number from a sequence of unique integers
in range [0..n] in O(n) time and space. The difference between
consecutive integers cannot be more than 1. If the sequence is
already complete, the next integer in the sequence will be returned.
"""
import unittest
import random
def fin... |
b46de0b702d42ae214de61825a2a5b9f11383e31 | YiseBoge/competitive-programming | /weeks/week-2/day-5/intersection_of_two_arrays.py | 767 | 3.984375 | 4 | # Copyright (c) 2021. This code is licensed to mire
# Copying and / or distributing without appropriate permission from author is
# illegal and would mount to theft of intellectual resource.
# Please contact developer at miruts.hadush@aait.edu.et prior to
# copying/distributing to ask and get proper authorizations... |
4e3cc5f5b39cee2af6ff81db3d44cebbdb1a0536 | jsqwe5656/MyPythonNote | /py_def/demo_def2.py | 250 | 3.859375 | 4 | # -*- coding: utf-8 -*-
#python第二个例子 函数返回多个值
import math
def move(x,y,step,angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx,ny
x,y = move(100,100,60,math.pi/6)
print(x,y)
z = x,y
print(z) |
72d0bcbe7ca40d8695ee6815c41fd58f3ad2171c | sy1wi4/ASD-2020 | /geometric algorithms/point_location.py | 610 | 3.859375 | 4 | '''
Położenie punktu p1 wzgledem p2 w układzie współrzędnych - liczymy iloczyn wektorowy wektorów od 0 do p1 i od 0 do p2,
jeżeli dodatni to zgodnie z ruchem wskazówek zegara, ujemny - przeciwnie, a równy zero oznacza współliniowość
iloczyn wektorowy to pole powierzchni równoległoboku (0,p1,p2,p1+p2) - wyznacznik maci... |
7c6fd3c6f316a76dbd1d691df413c2ff596cb705 | teaisawesome/Szkriptnyelvek_Python | /ora4/tuple.py | 514 | 3.578125 | 4 | # tuple is immutable - pont ugy mint a string
# lehet benne különböző tipusu elemeket is tarolni
# ugyanugy van lekérés elemekre: tup[0]
# ugyanugy van szeletelés - utolso ketto tup[:2]
def get_movie_info():
return ("Total Recall", 1990, 7.5)
def main():
title, year, score = get_movie_info() # <- value unpa... |
4749253da0e9244e34e8863217cd12a8dfe1b2c6 | aerwemi/toxicCommentsClassifier | /Model_make/wordFreqFilter.py | 236 | 3.640625 | 4 | def wordFreqFilter(Num, freqdist):
print('Number of words: ')
freqdistEd={k: v for k, v in freqdist.items() if v>Num}
wordsF = [i for i in freqdistEd.keys()] # output words Features
print(len(wordsF))
return(wordsF)
|
38c1334fa6cc3b6d04552c793e815116e6a0458d | VinuSreenivasan/Attrition-Rate-Analysis | /ols.py | 1,218 | 3.578125 | 4 | import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import linear_model
df = pd.read_csv('hr_data.csv')
#print df.head()
y = df.left
X = df.ix[:,('satisfaction_level','last_evaluation','average_montly_hou... |
a89a769182eedb8a8fe115121861ca56929fff60 | nikhillahoti/LeetCode_Solutions | /UglyNumbers.py | 407 | 3.8125 | 4 |
# Problem Number : 263 LeetCode
def isUgly(num):
if num <= 0: return False
div = 2
while num > 1:
if num % div == 0:
num = num / div
else:
if div == 2:
div = 3
else:
if div == 3:
div = 5
... |
e32c75851f465e4a63558b534744783aba7c9af9 | MajeroRuf/geekbrains_homework | /lesson_1/hw_1_2.py | 354 | 3.59375 | 4 | sec = input("Веедите колличество секунд:")
sec = int(sec)
hh = sec // 3600
dd = hh // 24
mm = (sec - (hh * 3600)) // 60
ss = (sec - (hh * 3600)) % 60
if dd > 0:
hh = sec // 3600 % 24
stroka = f"Time: {dd} дн {hh:02}:{mm:02}:{ss:02}"
print(stroka)
else:
stroka = f"Time: {hh:02}:{mm:02}:{ss:02}"
print... |
78ad269bdf60ecdc4c7bcec7e397e23d658b1bdb | patrykszwed/itai | /ConstraintSatisfactionProblem/puzzle/Field.py | 595 | 3.640625 | 4 | class Field:
def __init__(self, value, x, y):
self.value = value
self.x = x
self.y = y
self.contained_words = []
def add_word_to_contained_words(self, word):
if word not in self.contained_words:
self.contained_words.append(word)
def remove_word_from_cont... |
7449bab0e368c613a83984927a5e0dd443606a9d | franmauriz/python_django_flask | /Fundamentos/tarea_lista.py | 178 | 4.125 | 4 | #Iterar una lista de 0 a 10 e imprimir sólo los números divisibles entre 3
numeros = [0,1,2,3,4,5,6,7,8,9,10]
for numero in numeros:
if numero%3==0:
print(numero) |
d54ac361d0a5ad0993fc49998f0e92233ef92a5c | dimitlee/FlapAI-discretization | /heatmap.py | 5,647 | 3.5 | 4 | import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import json
import os
def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
textcolors=["black", "white"],
threshold=None, **textkw):
"""
A function to annotate a heatmap.
Parameters
-------... |
4a1f1af453177d1876c6218ae8fa946ecc42371f | EthanSantosWong/web_development_assignments | /Optimized_Photos/Python_Homework/Lab/Lab_3_Language.py | 759 | 4.1875 | 4 | lang = input("Please enter the name of a language:")
if (lang == "English"):
print("Good day.")
elif (lang == "Chinese"):
print("你好")
elif (lang == "Swedish"):
print("Hallå")
elif (lang == "Latin"):
print("Salve")
else: print("I am sorry, I do not recognize that language")
lang2 = input("Please ent... |
c9f6aa7a24796ef30069012ee6df708bfb2e81d7 | josephthegreat-hub/wakaba | /calculator.py | 636 | 3.640625 | 4 | class calculator:
income tax rate=
def __init__(self, basicsalary, pension, benefits, b):
self.a=a
self.b=b
def get_addition(self):
addition=(self.a+self.b)
return addition
def get_subtraction(self):
subtraction=(self.a-self.b)
return subtraction
def g... |
1dcf122553bc78ca5ffbd2e41931b9ead87f0a6c | django-group/python-itvdn | /домашка/essential/lesson 8/Pavel K/hw_16_2.py | 744 | 3.59375 | 4 | # Модифицируйте решение предыдущего задания так, чтобы оно работало не с текстовыми, а бинарными файлами.
import random
a = [random.uniform(-100000, +100000) for a in range(10000)]
print(a)
with open('D:\\random.dat', 'wb') as k: #меняем расширение файла на dat и ставим флаг 'b'
for i in a:
k.write(by... |
b482ed26d075e55575a780df905cf7b4790f12f6 | acarcher/lpthw | /ex48/ex48/lexicon.py | 1,190 | 3.953125 | 4 | lexicon = {
'direction': ['north', 'south', 'east', 'west', 'down', 'up',
'left', 'right', 'back'],
'verb': ['go', 'stop', 'kill', 'eat'],
'stop': ['the', 'in', 'of', 'from', 'at', 'it'],
'noun': ['door', 'bear', 'princess', 'cabinet']
}
def swap_lexicon(lexicon):
swapped = {}
... |
99840526c2cb14c04c42ff7edf12ecb170ea12e2 | aaronyangca/TheRunaway | /TheRunaway1.py | 6,954 | 3.953125 | 4 |
import time
age = eval(input("HOW OLD ARE YOU?"))
if age < 5:
print("UH OH! YOU NEED TO BE 6 OR OLDER TO PLAY.")
quit()
print("DO NOT SPAM ENTER.")
print("PLEASE ENTER OUT THIS FORM.")
fav_weapon = input("WHAT'S YOUR FAVORITE CLOSE-RANGED WEAPON? ")
fav_far_weapon = input("WHAT'S YOUR FAVORITE FAR-RANGED WEAPO... |
d99a77e543d32fdab32126f82ca4a3854da7cbb2 | TM0428/suudoku | /number.py | 10,373 | 3.6875 | 4 | import copy
# x座標,y座標,数字のデータを格納するためのクラス
class Number:
x = 0
y = 0
data = 0
# possibility[0]は使用しない
possibility = []
def __init__(self, x: int, y: int, data: int = 0):
self.x = x
self.y = y
self.data = data
self.possibility = [True] * 10
def __str__(self):
... |
6b2f7c272ca9b075a61dff6b6ff10d025aba38ce | efgalvao/Practice | /Python - 1/Enumerable Magic #5.py | 399 | 3.84375 | 4 | """
ask
Create a function called one that accepts two params:
a sequence
a function
and returns true only if the function in the params returns true for exactly one (1) item in the sequence.
"""
def one(sq, fun):
def one(sq, fun):
times = 0
for n in sq:
if fun(n) == True:
t... |
3b9f02623ebcbea6638ced22b8b917daa3201145 | my0614/python | /codeup_4532.py | 173 | 3.8125 | 4 | num = int(input())
num2 = int(input())
a_1 = num2 // 100
a_2 = num2 % 100 // 10
a_3 = num2 % 100 % 10
print(num * a_3)
print(num * a_2)
print(num * a_1)
print(num * num2)
|
8ef01fb09e6979f3a2ac722143dbec1f1f36beaf | valeman/vest-python | /vest/transformations/sma.py | 343 | 3.5625 | 4 | import pandas as pd
import numpy as np
def SMA(x, n: int):
""" Simple Moving Average
:param x: a numeric sequence
:param n: period for the moving average
:return: np.ndarray
"""
if not isinstance(x, pd.Series):
x = pd.Series(x)
x_sma = x.rolling(n).mean()
x_sma = np.array(x_... |
322ed27c9b4ab825bd21f8638ab3fcda615216f9 | AshaS1999/ASHA_S_rmca_s1_A | /ASHA_PYTHON/3-2-2021/q11lambda.py | 303 | 3.859375 | 4 | import math
r_area = lambda h,b: 1/2*b*h
#print(r_area(2,4))
s_area = lambda s:s*s
#print(s_area(2))
print("triangle")
h=float(input("enter height of the triangle"))
b=float(input("enter base"))
print("area=",r_area(b,h))
print("square")
s=float(input("enter side"))
print("area=",s_area(s)) |
80e21f51b9a577d26a6eb19821919232feda2ca6 | Wdiii/LeetCode-exercise-start-from-easy | /easy-Valid Mountain Array.py | 525 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
class Solution:
def validMountainArray(self, A):
if len(A)<3:
return False
max_place=A.index(max(A))
if max_place == 0 or max_place == len(A)-1:
return False
for i i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.