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
428fd8714cd7c2542af1000822bf90da9dd58847
linleysanders/algorithms
/Homework Week One (Average of Averages)/Linley Sanders Week One Homework.py
2,609
4.28125
4
# coding: utf-8 # # Lede Algorithms -- Assignment 1 # # In this assignment you will use a little algebra to figure out how to take the average of averages. # In[1]: import pandas as pd import matplotlib.pyplot as plt import requests get_ipython().run_line_magic('matplotlib', 'inline') # First, read in the tita...
cb01fa3f3fea34c85dd2373c6130478be7cbde25
SuprovoDas/Dream_Work
/multiple_iinheritance.py
1,022
4.03125
4
"""class father: def height(self): print('height is 6 feet') class mother: def color(self): print('color is dark') class child(father,mother): pass c = child() c.height() c.color()""" class A(object): def __init__(self): self.a = 'a' print(self.a) ...
cafb9aeb9a9da703325dc2979a1e21a098e56bb7
D-Code-Animal/CTI110
/P2T1_SalesPrediction_EatonStanley.py
311
3.53125
4
# CTI-110 # P2TI-Sales Prediction # Stanley J. Eaton Sr. # June 15, 2018 # Get the projected total sales. total_sales = float (input ('Enter the projected sales:')) # Calculate the profit as 23 precent of total sales. profit = total_sales * 0.23 # Display the profit. print ('The profit is $', format (profit, ',.2f'...
080664c2e54275b4268edb64b140559fa4d07f57
LiouYiJhih/Python
/cheap01_ Basic_operations.py
2,344
3.9375
4
# 註解的重要性 hourly_salary = 125 # 設定時薪 annual_salary = hourly_salary * 8 * 300 # 計算年薪 monthly_fee = 9000 # 設定每月花費 annual_fee = monthly_fee * 12 # 計算每月花費 annual_savings = annual_salary - annual_fee # 計算每年儲存金額 print(annual_savings) # 列...
ea09333e3af913cd33bd6df2ecaf7d4b84525a71
pradloff/analysis-framework
/common/node.py
1,290
3.640625
4
class node(): def __init__(self,parents,children,__item__): self.__item__ = __item__ self.parents = [] self.add_parents(*parents) self.children = [] self.add_children(*children) #self.__ancestor__ = {} #self.__decscendants__ = {} def add_parents(self,*parents): for parent in parents: if par...
f21fd0a9ca55cf2b6a0d298ff7b25390e3bb5e50
jboenawan/MIS3615
/src/calc.py
1,066
3.96875
4
# print(2017 - 1998) # print(2**10) # minutes = 42 # seconds = 42 # # print('The time duration is', minutes * 60 + seconds, 'seconds.') # # r = 5 # jess = (4 / 3) * r ** 3 * math.pi # print(jess) # len_of_number = len(str(2 ** 1000000)) # How many digits in a really BIG number? # print(len_of_number) # # import rando...
9ac9210e2616b578f13b22d03315cb473e5e0c61
globality-corp/microcosm-resourcesync
/microcosm_resourcesync/toposort.py
1,825
3.765625
4
""" Topological sort. """ from collections import defaultdict def toposorted(resources): """ Perform a topological sort on the input resources. Resources are first sorted by type and id to generate a deterministic ordering and to group resouces of the same type together (which minimizes the number o...
d333b5c8fa654a867c5e54f599f2ca5a5c68746d
zhezhe825/api_test
/cases/test_1.py
1,297
4.5
4
''' unittest框架:单元测试框架,也可做自动化测试,python自带的 unittest:管理测试用例,执行用例,查看结果,生成 html 报告(多少通过,多少失败 ) 自动化:自己的代码,验证别人的代码 大驼峰命名:PrintEmployeePaychecks() 小驼峰:printEmployeePaychecks() 下划线命名:print_employee_paychecks() 类:大驼峰命名 其他:小驼峰,下划线命名 class:测试的集合,一个集合又是一个类 unittest.TestCase:继承 继承的作用:子类继承父类(TestExample 继承 TestCase),父类有的,子类都有 ''' ...
3375441b180ccb3af8ed21c1dc59918f1a9ad339
AMANGUPTA2000/ML_Projects
/Assignment_2/sum_diagonal.py
240
3.546875
4
import numpy as nm arr=nm.array([[1,2,3,4],[3,4,5,6],[6,7,8,9],[9,0,1,2]]) print(arr) arr_diagonal_element = arr.diagonal() print("\nDiagonal element:",arr_diagonal_element) print("\nSum of Diagonal elements:",nm.sum(arr_diagonal_element))
488db3e736f5b837e0dda27689d60d167734a963
jcastiblanco/mintic2022memories
/Reto1.py
1,025
3.8125
4
#Importación de modulos necesarios para librerias matematicas import decimal import math #******************************** #**Código Principal de ejecucion #******************************** # main () #Variables salarioBase=176 pcthorasExtras=1.25 horasExtras=0 pctbonificacion=0.065 salarioBase=0 salarioE...
1e77dfff1db0174ed2a6695864eefecae7e1326c
xwj0813/lectcode
/com/xwj/code/No17letterCombinations.py
736
3.6875
4
# -*- coding:utf-8 -*- ''' 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合 ''' def letterCombinations(digits): dict = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '...
a7f6a75f106e7d866e56d5f4f2b522d99390d1ee
xwj0813/lectcode
/com/xwj/code/No4_MedianTwoSortedArray.py
2,382
3.546875
4
# -*- coding:utf-8 -*- ''' 给出两个有序的数字列表,长度分别为m,n。找到这两个列表中的中间值 ''' import time def findMedianSortedArrays(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ # 创建新列表,并将所有元素初始为0 nums3 = [0] * (len(nums1) + len(nums2)) # 指定三个列表的索引,初始值为0 l_i, r_i, i = 0, ...
cbd8f93e9f6e1adbeebe0d612865c3d306ada0a1
ritaly/python-6-instrukcje-warunkowe
/Odpowiedzi/2.py
988
4.125
4
# -*- coding: utf8 -*- """ Do kalkulatora BMI z lekcji "Python 1 zabawy w konsoli" dodaj sprawdzanie czy BMI jest prawidłowe Niedowaga | < 18,5 Waga normaln | 18,5 – 24 Lekka nadwaga | 24 – 26,5 Nadwaga | > 26,5 W przypadku nadwagi sprawdź czy występuje otyłość: Otyłość I stopn...
b7fe479f010694f71b4dbc5df0e07cd3a3c08449
DMRathod/_RDPython_
/Simple_estimation_CrowdComputing.py
894
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 12:53:40 2019 @author: Dharmraj Rathod """ from statistics import mean #from scipy import stats #let we have the bottle filled with marbels and we have to guess how many number of marbles are #there in the bottle """total number of marbles in the bottle is 36""" #imp...
6f3c61f8c2d26f3e112b9853319633d0aa5c2cde
DMRathod/_RDPython_
/Coding Practice/Basic Maths/Factorial.py
179
4.09375
4
def fact(number): if(number <=1): return 1 else: return (number * fact(number-1)) number = int(input("Enter number for factorial:")) print(fact(number))
976f3ae5ea8e924d2fd0838cdfbf5981a0195e48
DMRathod/_RDPython_
/Coding Practice/Basic Maths/FindMeetingRoomlist.py
1,089
3.734375
4
# meeting room details which is dictionary of room number as key and value is list of two values starting and ending time of the meeting # OccupiedRoomDetails = {0 : ["9AM", "11AM"], 1: ["10AM", "12AM"], 2: ["11AM", "12AM"], 3: ["9AM", "10AM"]} # Assuming requested meeting is only of 1 hour. def FindMeetingRoomlist(s...
61a496dde5f1d6faa1dfb14a79420f3730c0727f
DMRathod/_RDPython_
/Coding Practice/Basic Maths/LeapYear.py
441
4.21875
4
# leap year is after every 4 years, divisible by 4. # Every Century years are not leap years means if it is divisible by 100. # we need to confirm if it is divisible by 400 or not. year = int(input("Enter The Year :")) if(year%4 == 0): if(year%100 == 0): if(year%400 == 0): print(str(yea...
1d9d07543fdcded06e83687de0279e2660a3c53f
DMRathod/_RDPython_
/Coding Practice/Sorting/SS.py
532
3.671875
4
ns = [4, 5, 1, 22] # selection sort will just find the one element and put that element at its right position # here i have taken max element and putting at its right psition each time in each iteration def SSort(ns): for i in range(len(ns)): mx = ns[0] j = 1 k = 0 while(j < len(n...
4e2950045c5f2f36d9655585f48f5d9260ce1a6b
rwinklerwilkes/Python
/knn.py
2,210
3.703125
4
#A short messy implementation of a 2-dimensional kth nearest neighbor algorithm import math class Point: def __repr__(self): return "Point" def __str__(self): return "x1: %d\nx2: %d\ny1: %s\n" %(self.x1,self.x2,self.y1) def __init__(self, x1, x2, y1): self.x1 = x1 self.x2 =...
406a2927197d804de0300c98c678d44d90d8155d
cpowicki/Settlers-Of-Catan-Generator
/devcards.py
591
3.5
4
from random import shuffle class developmentCard: def __init__(self, type): self.type = type class deck: def __init__(self): self.cards = [] for i in range(19): self.cards.append(developmentCard('Knight')) for i in range(5): self.cards.append(develo...
529ed8b188e4ecb5a05d28a5b431150aae425239
Sakina28495/Fashion
/demo.py
215
3.53125
4
def codemaker(urstring): output=list(urstring) print(output) for index,letter in enumerate(urstring): for vowels in 'aeiou': if letter==vowels: output[index]='x' return output print(codemaker('Sammy'))
3456da0d36a1771bce68108957a7e6713aea83b4
eltobito/devart-template
/project_code/test2.py
515
3.828125
4
import Image picture = Image.open("picture.jpg") # Get the size of the image width, height = picture.size() # Process every pixel for x in width: for y in height: current_color = picture.getpixel( (x,y) ) print current_color #################################################################### ...
7dd133e44d846b84c1cda13c84ff3dc50aed1148
jadynk404/CMPT120-Project
/dictionary.py
1,169
3.984375
4
#Worked with Emmanuel Batista def main(): title = "Interactive Dictionary" print(title) myFile = input("Please input the name of your file: ").strip() myFile = myFile.lower() with open(myFile, "r") as myFile: #reads file and assigns value to variables dictionary = myFile.readlines() ...
7db722bc3d5e417139bb055937e9315289f90b52
cgraaaj/PracticeProblems
/Add two numbers as a linked list/main.py
1,176
3.796875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: result = None def addTwoNumbers(self, l1, l2, c=0): v1 = [] v2 = [] res = [] while l1: v1.append(l1.val) ...
fbb3938b667cba8afe5144c023cacbd833028f03
crashtack/exercism
/python/clock/clock.py
1,144
4.34375
4
class Clock(object): """ A Clock class that ignores date """ def __init__(self, hours=0, minutes=0): """ Initialize the Clock object """ self.hours = hours % 24 self.minutes = minutes self.time_min = (self.hours * 60) + self.minutes self.time_min = self.time_min % 1440 ...
11aad31a77cdbca35a0961b5cfb1c46d56c438c4
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/11-input-2.py
562
4.03125
4
# Formulamos los mandatos que debe cumplir el usuario pregunta = '\nAgrega un numero y te dire si es par o impar ' pregunta += '(Escribe "Cerrar o cerrar" para salir de la aplicacion) ' # Variable booleana que mantendra el while iterandose preguntar = True while preguntar: numero = input(pregunta) if numero...
f877815460bf804c8756d2dbb49cbe2cea568e10
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/14-clases-5.py
2,681
3.9375
4
class Restaurante: def __init__(self, nombre, categoria, precio): # Por defecto estas variables estan publicas # self.nombre = nombre # self.categoria = categoria # self.precio = precio # Para hacerlas PROTECTED unicamente al inicio del nombre # del atributo le agr...
11743b0257a83b0df21ab3daadcb2483468eaa83
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/05-numeros-2.py
401
3.828125
4
def suma(a=0, b=0): print(a + b) suma(2, 3) suma(4, 1) suma(8, 12) suma() def resta(a=0, b=0): print(a - b) resta(2, 3) resta(4, 1) resta(8, 12) resta() def multiplicacion(a=0, b=0): print(a * b) multiplicacion(2, 3) multiplicacion(4, 1) multiplicacion(8, 12) multiplicacion() def division(a=0, b...
87267ed67fb71ac07755fff6f81fb02f2f7b4a95
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/10-diccionarios-1.py
1,528
3.875
4
# Creando un diccionario (objeto) simple cancion = { # llave : valor (Para agregar mas valores los separamos por comas) 'artista': 'Metallica', 'cancion': 'Enter Sandman', 'lanzamiento': 1992, 'likes': 3000 } # Imprimir todos los valores print(cancion) # Acceder a los elementos del diccionario pr...
0f9b703805d7afabd6a9d0313076f003f0d16b3a
bobbyscharmann/flypy
/examples/main.py
714
3.796875
4
from flypy.neural_networks.activation_functions import Sigmoid, ReLU from flypy.neural_networks import NeuralNetworkTwoLayers import numpy as np l = ReLU() #l.plot(-10, 10, derivative=False) print("Hello world.") nn_architecture = [ {"input_dim": 2, "output_dim": 4}, #{"input_dim": 4, "output_dim": 6}, #{...
1210ad4c30493aefaa6585472991a79894bdae58
bobbyscharmann/flypy
/flypy/reinforcement_learning/cartpole/random_agent.py
783
3.5
4
"""Implementation of the OpenAI Gym CartPole exercise with a random sampling of the action space. In other words, a vey simplistic (or dumb) agent)""" import gym env = gym.make("CartPole-v0") env.reset() # Couple of variables for knowing when the episode is over done: bool = False # Keeping track of total aware and ...
a899cbea277c1183228ac5f7396dce5347c69279
numbertheory/nanogenmo
/verb.py
991
3.5
4
"""Get a random verb, from a given tense""" import random def get(tense): """ Get a verb in the right tense """ verbs = {'past': ['spoke', 'baked', 'competed', 'smoked', 'switched', 'unlocked'], 'present': ['speaks', 'bakes', 'competes', 'smokes', '...
deb0106dadea39101d8c40357c3f41f9383a9937
GarryK97/Python
/Hashtable/Task5.py
2,715
4.4375
4
from Task3 import HashTable def read_file_removesp(file_name): """ Read a text file and convert it to a list of words without any special characters. :param file_name: File to read :return: the list of words """ f = open(file_name, 'rt', encoding='UTF8') file_list = [] for l...
0d471841786f140724e55f0452db3469f9043be7
GarryK97/Python
/Algorithms/Dijkstra&Bellman-Ford.py
13,153
3.640625
4
import heapq """ Graph implementation for best_trades """ class Trade_Graph: def __init__(self, num_vertices): """ Initialize Graph object :param num_vertices: Total number of vertices :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(V) ...
b0f1454101fcd2aa96d12bc55bfa6aebcd002103
VinceWu-bit/Decision-Chessboard-Puzzle
/env.py
2,181
3.515625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2021/6/12 18:15 # @Author: Vince Wu # @File : env.py import numpy as np class ChessBoardEnv: def __init__(self): self.chessboard = np.array([0, 0, 0, 0]) self.key_dic = {0: 1, 1: 1, 14: 1, 15: 1, # 4维立方体编码规则 6: 2, ...
606de1aa9e681af56f022880698088b3ea58904d
nidakhawar/PracticePythonExcercises
/AverageOfSubjects.py
510
4.1875
4
biology=float(input("Please input your Biology score:")) chemistry=float(input("Please input your Chemistry score:")) physics=float(input("Please input your Physics score:")) if biology<40: print("Fail") if chemistry<40: print("Fail") if physics<40: print("Fail") else: score=((biology+chemistry+physics)/3) ...
2fe1eb2779838cbd559241374b9f94d6b36bc413
KevinSilva11/Python_The_Huxley
/PH.py
145
3.546875
4
ph = float(input()) if ph < 7: print('Acida') else: if ph > 7: print('Basica') else: print('Neutra')
bc5650df61ac37eef9df8a63e2b7d0b147d512da
SuzaneFer/phyton-basico-graficos
/ComparandoGenomas.py
799
3.5
4
#Neste estudo de caso, faremos a comparação entre duas sequências de DNA: # (1) ser humano; vs. (2) bactéria. import matplotlib.pyplot as plt import random entrada = open("bacteria.fasta").read() saida = open("bacteria.html","w") cont = {} # Dicionário for i in ['A', 'T', 'C', 'G']: for j in ['A',...
976cc8ab3327128b679d3d205e8c2dc1b2daae0b
zacharykaczor/Small-Programs
/odd_numbers.py
535
4.1875
4
# Based on https://www.youtube.com/watch?v=LkIK8f4yvOU. # The Difference of Two Squares. number = int(input("Please enter a positive odd number: ")) while number % 2 == 0 or number < 0: number = int(input( "Please enter a positive number: " if number < 0 else "Please enter an odd number: " ))...
c2f1391ee6e1ce4aa1cca4a81314f323495dc655
ProspePrim/PythonGB
/Lesson 5/task_5_2.py
985
3.96875
4
#Создать текстовый файл (не программно), сохранить в нем несколько строк, #выполнить подсчет количества строк, количества слов в каждой строке. with open('test.txt', 'w') as my_f: my_l = [] line = input('Введите текст \n') while line: my_l.append(line + '\n') line = input('Введите...
05da3490735523a90c3b6a6a206a5445ac6e8fa4
ProspePrim/PythonGB
/Lesson 2/task_2_4.py
524
4.03125
4
#Пользователь вводит строку из нескольких слов, разделённых пробелами. #Вывести каждое слово с новой строки. Строки необходимо пронумеровать. #Если в слово длинное, выводить только первые 10 букв в слове. a = input("введите строку ") list_a = [] i = 0 list_a = a.split() for _ in range(len(list_a)): print(f"{list...
cc84abe6637d76e56a7ac2c958ebd7c8a808c1c1
ProspePrim/PythonGB
/Lesson 2/task_2_1.py
628
4.125
4
#Создать список и заполнить его элементами различных типов данных. #Реализовать скрипт проверки типа данных каждого элемента. #Использовать функцию type() для проверки типа. #Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. list_a = [5, "asdv", 15, None, 10, "asdv", False] def type_...
8ff0adfd4e67aa0a69a45ebda1eb30ec290dcd49
ProspePrim/PythonGB
/Lesson 7/task_7_1.py
1,162
3.65625
4
class Cell: cells: int def __init__(self, cells: int): self.cells = cells def __str__(self): return str(self.cells) def __int__(self): return self.cells def __add__(self, cells: 'Cell'): return Cell(self.cells + cells.cells) def __sub__(self, cells: 'Cell'): ...
bce8bf614aca3883f2ac618caa8f00bc32a5dd73
costacoz/python_design_patterns
/behavioral/iterator.py
1,296
4.5
4
# Iterators are built into Python. # It can be engaged, using 'iter(arg*)' function # arg* - can be list, tuple, dic, set and string. # Below is the example of using it. # fruits_tuple = {'apple', 'blueberry', 'cherry', 'pineapple'} # fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') # fruits_tuple = ['appl...
a387b981c804a8e38ba20ce58d2417d82bc4dd89
muhammadyou/PythonTutorial
/ThreadingExample.py
1,758
4.09375
4
import threading import time class Example(threading.Thread): def run(self): for _ in range(10): time.sleep(1) print(threading.current_thread().getName()) def example(): for _ in range(10): time.sleep(1) print("hELlo") def example1(name, x): print("From exa...
717852b99833f1e2f9470bb7e906f0cb29d7874e
bjolley74/myTKfiles
/lesson1.py
255
3.859375
4
"""lesson1.py - message box: creates a tk message box""" from tkinter import * from tkinter import messagebox root = Tk() root.withdraw() messagebox.showinfo('Bobby\' World', 'Hello Y\'all! This is a message from Bobby\nThis is some really cool stuff')
9c47ecc06cd8e6525255f441528d9deae2655c9f
jgu13/Miscellaneous
/Python/ecosys_simulator/ecosystem_simulator.py
13,854
4.125
4
# Jiayao Gu # 260830725 import random import matplotlib.pyplot as plt class Animal: # Initializer method def __init__(self, my_species, row, column): """ Constructor method Args: self (Animal): the object being created my_species (str): species name ("Lion" or "Zebr...
0b602263ce8b46a900c767c974efcce4ca0b2984
JDWree/Practice
/Python/mastermind.py
3,436
4.1875
4
# Simple version of the game 'mastermind' #---------------------------------------- # Version 1.0 Date: 5 April 2020 #---------------------------------------- # Player vs computer # A random code gets initialized. The player has 10 guesses to crack the code. # The game tells the player when it has a right digit i...
059b163345985fdcfee9f3e410de39e001218782
gagaspbahar/prak-pengkom-20
/P02_16520289/P02_16520289_02.py
744
3.5625
4
# NIM/Nama : 16520289/Gagas Praharsa Bahar # Tanggal : 4 November 2020 # Deskripsi: Problem 2 - Konversi basis K ke basis 10 #Kamus #int sm = jumlah bilangan dalam basis 10 #int n = jumlah digit #int k = basis awal #int i = counter #Inisialisasi variabel sm = 0 n = int(input("Masukkan nilai N: ")) k = int(input("Mas...
885e989095d06495061674fe1e2696b815df9463
gagaspbahar/prak-pengkom-20
/H03_16520289/H03_16520289_01.py
436
3.609375
4
# NIM/Nama : 16520289/Gagas Praharsa Bahar # Tanggal : 15 November 2020 # Deskripsi: Problem 1 - Penulisan Terbalik # Kamus # int n = panjang array # int ar[] = array penampung angka #Algoritma #Input n = int(input("Masukkan N: ")) #Inisialisasi array dan memasukkan angka ke array ar = [0 for i in range(n)] for i i...
5966f2409f0998aa515f8f40b56f3339a2d4298a
plaer182/Python3
/test_random_symbol.py
1,575
3.546875
4
#!/usr/bin/env python3 from random_symbols import random_symbol import string def test_length_name(): """ Check length of element in list of results """ try: random_symbol(["Annannannannannannannannannannannannannannanna", "Boris", "Evgenia", "Viktor"]) except: pass...
2724d92157d61f930c089931f2b55042dcfe9f0e
plaer182/Python3
/FizzBuzz(1-100)(hw2).py
354
4.15625
4
number = int(input('Enter the number: ')) if 0 <= number <= 100: if number % 15 == 0: print("Fizz Buzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) elif number < 0: print("Error: unknown symbol") else: ...
df113dafcc1cf93b98304cc6f8f33efbe0a2e296
plaer182/Python3
/fahrenheit_to_celsius(hw1).py
158
4.125
4
celsius = float(input('Enter the temperature in degrees to Сelsius> ')) fahrenheit = celsius * 1.8 + 32 print(str(fahrenheit) + ' degrees to Fahrenheit')
08fe50d6f996a359bd2346667554abde47a94c47
Jamesbwwh/Minesweeper
/Minesweeper/Minefield.py
3,057
3.78125
4
import random def generate(difficulty): mineField = printMineField(difficulty) height = len(mineField) width = len(mineField[0]) ranges = width * height mines = random.randint(ranges // 8, ranges // 7) # mines = 4; # comment or remove this line. for testing only. print "Difficulty: ", diff...
f677307abacfa8b8c1e095bf3eeffaa1f94ffe0f
iman2008/first-repo
/random1.py
187
3.875
4
#defining 10 random number between 10 and 20 import random def random_numer(): i=0 while (i<=10): x = random.random() * 20 if 10 <= x <= 20: print (x) i=i+1 random_numer()
0f23631ef11d79a29889cb820371aa21ffaecde8
iman2008/first-repo
/lab4task1.py
336
3.765625
4
def sum_adder (mlist): """this will add up the content of the list""" total = 0 s_list = mlist for item in s_list: if isinstance(item,int): total = total + item elif isinstance (item,list): total=total+sum_adder (item) else: return "you have not select proper list" return total x = [90,10,11] print...
9b624ac6dee525b0da68baa1196f8b273486d237
Mentos15/Python_2
/paswords.py
691
3.5625
4
#! python3 # paswords.py PASWORDS = { 'email': 'vital2014','vk':'Vital2014','positive':'vital2014'} import sys,pyperclip if len(sys.argv)<2: print('Использование: python paswords.py[Имя учетной записи] - копирование пароля учетной записи') sys.exit() account = sys.argv[1] # первый аргумент командной строки - э...
db6a67f488a152ccc2768d3d24728afb318f10de
CodecoolBP20172/pbwp-3rd-si-code-comprehension-kristofilles
/comprehension.py
2,101
4.3125
4
"""Its a bot what randomly choose a number between 1 and 20, and the user need to guess within 6 round what number was choosen by the bot.""" import random #import the random module guessesTaken = 0 #assign 0 to guessesTaken variable print('Hello! What is your name?') #print out this sentence myName = input() #assig...
19a4a42767f001a14afeb4debed9ef26c6e69afe
rdugh/pythonds9
/pythonds9/trees/binary_tree.py
1,028
3.8125
4
class BinaryTree: def __init__(self, key): self.key = key self.left_child = None self.right_child = None def insert_left(self, key): if self.left_child is None: self.left_child = BinaryTree(key) else: # if there IS a left child t = Binary...
6ced4a96655281b60edd62a77ea9e76b6f79bd55
brentEvans/algorithm_practice
/Python/algo.py
2,264
3.640625
4
class Node: def __init__(self, value): self.val = value self.next = None class SLL: def __init__(self): self.head = None def addBack(self,value): new_node = Node(value) if self.head == None: self.head = new_node else: runner = ...
07bd3a329eafee4c2398a08943aeb985a282b6f2
onionmccabbage/pythonTrainingMar2021
/using_ternary.py
474
4.40625
4
# Python has one ternary operator # i.e. an operator that takes THREE parts # all other operators are binary, i.e. they take TWO parts # e.g. a = 1 or 3+2 # the ternary operator works like this # 'value if true' 'logical condition' 'value if false' x = 6 y = 5 print("x" if x>y else "y") # alternative syn...
8b08218eb70b47bfb0aa02cfacf775dcdb2a3089
onionmccabbage/pythonTrainingMar2021
/py2demo.py
242
3.859375
4
print "hello" # Python 2 print('also hello') # also works in Python 2 # division of ints 7/3 # is 2 in Py2 and 3 and a bit in Py 3 # py 2 has a 'long' data type - change it to 'float' # some py 2 functions were re-defined in py 3
8b888a5341335f8976cfc23b7ede527047886ec3
AnindKiran/N_Queen-s-Problem-Solution-in-Python
/Final N-Queens Project.py
3,087
4.28125
4
a="""This is a program used to display ALL solutions for the famous N-Queens Problem in chess. The N-Queens Problem is a problem where in an N-sized chess board, we have to place N Queens in such a way that no one queen can attack any other queen""" print(a) print() a="""This program will take your input and will ...
04860c836937ba8bc594c64d7c9b752ea564269e
jeremy-robb/KnoxClassRecommender
/tools.py
3,239
4
4
from lists import * takeFrom = [] def chooseMajors(): print("") print("To choose a major, type the first 3 letters of the specialization, followed by the first 2 letters of the degree") print("Examples: CS BA (Computer Science BA) , MATBA (Math BA) , PHYMI (Physics minor)") print("Choose major one") ...
4a16ad732d79913225b5e89bc29acc27bf81937c
Lexical-Lad/Machine-Learning-Python-R-Matlab-codes
/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/PreprocessingPractice.py
1,626
3.609375
4
import numpy as np import pandas as pd import matplotlib.pyplot as mlt import os #os.chdir(...) dataset = pd.read_csv("Data.csv") #splitting the dataset into the feature matrix and the dependent variable vector X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values #conpensating for the missing values, if any ...
3d0d26f588dfeb0d23e179fbdf94a6b35f0388a8
lazyseals/crawler
/products/category_parser.py
18,232
3.671875
4
from products import items as d # Foreach shop a unique parser must be written that executes the following steps: # 1. Category name and product name to lower case # 2. Check if a product in category name needs to be replaced by a mister m category # 3. Determine mister m category based on a pattern in the product nam...
653b56c505745fb2947589692c3a628d149d27ef
robertmplewis/playground
/wordquiz.py
649
3.921875
4
#!/usr/bin/env python import operator def main(): print word_count() def word_count(): word_totals = { } book_contents = f.read() book_contents = book_contents.replace('\n', ' ') book_contents = book_contents.replace(',', '') book_contents = book_contents.replace('.', '') book_contents = book_conten...
375b0579cdbe45e4a66d954f8d5e767f8ef70546
justEhmadSaeed/ai-course-tasks
/Python Assignment 1/Part 2/Task 5.py
261
4.28125
4
# Write a list comprehension which, from a list, generates a lowercased version of each string # that has length greater than five strings = ['Some string', 'Art', 'Music', 'Artifical Intelligence'] for x in strings: if len(x) > 5: print(x.lower())
a54b52aee8ebf3cf44dc050ee68699aa4c6ee011
justEhmadSaeed/ai-course-tasks
/Python Assignment 1/Part 3/Task 3.2.py
306
3.6875
4
# One line function for intersection # Uncomment below code to generate random lists intersection = lambda a, b: list(set(a) & set(b)) # import random # a = [] # b = [] # for i in range(0, 10): # a.append(random.randint(0, 20)) # b.append(random.randint(5, 20)) # print(intersection(a, b))
af2ca98dfba5c5fdf958422f55c0685bef3937e4
JanBednarik/micropython-matrix8x8
/examples/game_of_life.py
1,870
3.5
4
import pyb from matrix8x8 import Matrix8x8 def neighbors(cell): """ Yields neighbours of cell. """ x, y = cell yield x, y + 1 yield x, y - 1 yield x + 1, y yield x + 1, y + 1 yield x + 1, y - 1 yield x - 1, y yield x - 1, y + 1 yield x - 1, y - 1 def advance(board): ...
c6324a495ce9b5cd11784e34e4da56c427482e1f
daniellopes04/uva-py-solutions
/list2/120 - Stacks of Flapjacks.py
1,011
3.5
4
# -*- coding: UTF-8 -*- def main(): while True: try: unsorted = list(map(int, input().split())) current = unsorted.copy() final = sorted(unsorted) N = len(final) steps = [] for i in range(len(current) - 1, -1, -1): ind...
0babe69773bebc354b6da02c83f1fd151b4034dc
daniellopes04/uva-py-solutions
/list3/902 - Password Search.py
943
3.5625
4
# -*- coding: UTF-8 -*- def main(): while True: try: line = input().strip() while line == "": line = input().strip() items = line.split() if len(items) == 2: n = int(items[0]) text = it...
8353125ae9724cfef90b738d8aad6998ca78f8fe
SpCrazy/crazy
/code/SpiderDay03/bs4_learn/hello.py
283
3.5
4
from urllib.request import urlopen from bs4 import BeautifulSoup response = urlopen("http://www.pythonscraping.com/pages/page1.html") bs = BeautifulSoup(response.read(),"html.parser") print(bs.h1) print(bs.h1.get_text()) print(bs.h1.text) print(bs.html.body.h1) print(bs.body.h1)
4788dd580886d9d056d2c5847cacda6b2a95628e
SpCrazy/crazy
/code/SpiderDay1_Thread/condition/concumer.py
821
3.78125
4
import time from threading import Thread, currentThread class ConsumerThread(Thread): def __init__(self, thread_name, bread, condition): super().__init__(name=thread_name) self.bread = bread self.condition = condition def run(self): while True: self.condition.acqu...
8c0d380707fd8ed99cba1e6e44a13b63313bc0c7
whlg0501/2018_PAT
/1004.py
1,663
3.578125
4
""" 1004 成绩排名 (20)(20 分) 读入n名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。 输入格式:每个测试输入包含1个测试用例,格式为 第1行:正整数n 第2行:第1个学生的姓名 学号 成绩 第3行:第2个学生的姓名 学号 成绩 第n+1行:第n个学生的姓名 学号 成绩 其中姓名和学号均为不超过10个字符的字符串,成绩为0到100之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。 输出格式:对每个测试用例输出2行,第1行是成绩最高学生的姓名和学号,第2行是成绩最低学生的姓名和学号,字符串间有1空格。 输入样例: 3 Joe Math990112 ...
c9fd907f7db76ed478ad64875951242b3dcebf0f
whlg0501/2018_PAT
/1049.py
1,239
3.5625
4
""" 1049 数列的片段和(20)(20 分)提问 给定一个正数数列,我们可以从中截取任意的连续的几个数,称为片段。例如,给定数列{0.1, 0.2, 0.3, 0.4},我们有(0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) (0.4) 这10个片段。 给定正整数数列,求出全部片段包含的所有的数之和。如本例中10个片段总和是0.1 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0。 输入格式...
23d0b02ba64c2aca3becf467d88c692109aab9f8
patnaik89/string_python.py
/condition.py
1,696
4.125
4
""" Types of conditional statements:- comparision operators (==,!=,>,<,<=,>=) logical operators (and,or,not) identity operators (is, is not) membership operators (in, not in) """ x, y = 2,9 print("Adition", x + y) print("multiplication", x * y) print("subtraction", x - y) print("division", x/y) pr...
c0bd2b9a856537ea24d75bc6e73ec5396c0a987b
seanjib99/pythonProject14
/python 1.py
954
4
4
#s.n students take k apples and distribute each student evenly #The remaining parts remain in the basket. #How many apples will each single student get? #How many apples will remain in the basket?The programs read the numbers N and k. N=int(input("enter the number of students in class")] K= int(input("enter the numbe...
59eb59d435bb953bdc73df7a5df3d285dbfd6c93
cmillecan/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
460
4.03125
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) last_digit = abs(number) % 10 if number < 0: last_digit = -last_digit if last_digit > 5: print("Last digit of {:d} is {:d} and is greater \ than 5".format(number, last_digit)) elif last_digit == 0: print("Last digit of {:d} is {:d} and ...
65ec659dbb339de8bfbfe81ae2556dcc314c8f0c
cmillecan/holbertonschool-higher_level_programming
/0x0B-python-input_output/13-student.py
816
3.875
4
#!/usr/bin/python3 """ Task 13 """ class Student: """Defines a student""" def __init__(self, first_name, last_name, age): """ Instantiation """ self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """...
bb204dab03699a3aaa32f558c92fd8fc697449ab
arkkhanu/Final-Project-OCR
/Server/hough_rect.py
6,941
3.609375
4
""" Module for finding a rectangle in the image, using Hough Line Transform. """ import itertools from typing import Union import numpy as np import cv2 import matplotlib.pyplot as plt from scipy.spatial import distance import consts def find_hough_rect(img: np.ndarray) -> Union[None, np.ndarray]: """ Find ...
b24585f353af5a15200c7c9ef10d920ed3862fc5
SuryaDeepthiR/competitive-programming
/competitive-programming/Week2/Day-6/InPlaceShuffle.py
449
3.9375
4
import random def random_number(floor,ceiling): return random.randint(floor,ceiling) def shuffle(the_list): # Shuffle the input in place length = len(the_list) for i in range(0,length-1): j = random_number(0,length-1) the_list[i],the_list[j] = the_list[j],the_list[i] sample_l...
834612676d77e7be218b1898422ba94fff11196f
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/minimum-ascii-delete-sum-for-two-strings.py
1,970
3.828125
4
""" Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. Example 1: Input: s1 = "sea", s2 = "eat" Output: 231 Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. Deleting "t" from "eat" adds 116 to the sum. At the end, both strings are equa...
38ca97cf3452797e9460b01dcf61559d53643669
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/number_of_longest_increasing_subsequence.py
1,446
3.984375
4
""" 673. Number of Longest Increasing Subsequence source: https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence/ Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [...
f21b75948484cc34cea7d9d166dc47e72611749d
liadbiz/Leetcode-Solutions
/src/python/degree_of_array.py
1,373
4.15625
4
""" Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explan...
7859a42286274f9710a439def03707787e93641b
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/jump_game_2.py
2,740
3.984375
4
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1,4] Output: 2 Explanation: The minim...
56ea95418a0ec5e08e1b85a87c7cd257e38754d4
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/Palindromic_string.py
1,191
4
4
""" #647 palindromic string https://leetcode.com/problems/palindromic-substrings/ Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Inp...
426bcfbcc836cd23ca4f5e00057781bf180f22e1
liadbiz/Leetcode-Solutions
/src/python/validate_binary_search_tree.py
763
4.0625
4
""" Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left ...
3d6ff3e1c81878b956d537ba48a19df178ee55a5
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/mininum_cost_for_tickets.py
2,204
4.0625
4
""" In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365. Train tickets are sold in 3 different ways: + a 1-day pass is sold for costs[0] dollars; + a 7-day pass is...
498b0478db6e99d4bb321585b4c4fce7f2a9e269
liadbiz/Leetcode-Solutions
/src/python/largest_common_prefix.py
3,031
4.15625
4
""" description: Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix amo...
36afe84aaa377106aa8a4eb6706c015a88fa7a49
liadbiz/Leetcode-Solutions
/src/python/reverse_integer.py
920
3.96875
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example1: Input: 123 output: 321 Example2: Input: -123 Output: -321 Example3: Input: 120 Output: 21 Notes: what if the result overflow? what have learned: 1. in python 2, we can use cmp() function to get sign of the difference of two number a an...
6aac68ffc80dba1f5c76492a7dc37016f632556d
liadbiz/Leetcode-Solutions
/src/python/power_of_four.py
963
4
4
""" Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16 Output: true Example 2: Input: 5 Output: false Follow up: Could you solve it without loops/recursion? """ class Solution: def isPowerOfFour(self, num): """ :type num: int :rt...
8cab006e87d608bdce1899e00044e13f8f09c3f2
liadbiz/Leetcode-Solutions
/src/python/minimum_moves2.py
990
4.03125
4
""" Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. You may assume the array's length is at most 10,000. Example: Input: [1,2,3] Output: 2 Explanation: Only two...
26715c6de77437da8a9084c3aea2db86910a527d
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/split_array_into_consecutive_subsequences.py
2,647
4.09375
4
""" You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split. Example 1: Input: [1,2,3,3,4,5] Output: True Explanation: You can split ...
49ebb1d0c3806b92ab6c158447171ceca908da42
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/course_schedule_3.py
2,124
3.859375
4
""" There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day. Given n online courses represented by pairs (t,d), your tas...
893104e3a4ade89aa31e82a18df0695a040fbd9e
liadbiz/Leetcode-Solutions
/src/python/range_sum_query.py
771
3.71875
4
""" # 303 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function. Acc...
be8da5d6998ab0d7cde8a800612dbabe81830c77
liadbiz/Leetcode-Solutions
/src/python/onebit_twobit.py
2,948
4.03125
4
""" 717. 1-bit and 2-bit Characters We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given stri...
04d56f4cfc176ede74a148b901dad5120b4b1270
Calico888/First-Steps---Quiz
/quiz 2.py
6,549
4.25
4
# Strings for the different difficulties easy_string = """I have a __1__ that one day this __2__ will rise up, and live out the true meaning of its creed: We hold these truths to be self-evident: that all men are created equal. Martin Luther King jr The greatest __3__ in living lies not in never falling, but in __4__...
a060b33270c6c736e397f22f81ebab6f68b1a4e8
arcae/git_lesson-1
/data/portcsv.py
626
3.671875
4
#using csv module import csv def portfolio_cost(filename): ''' Computes total shares*proce for a CSV file with name,shares,price data' ''' total = 0.0 with open(filename,'r') as f: rows = csv.reader(f) headers = next(rows) #skip first row for headers for rowno, row in enumerate(rows,start=1): try: ...
a849d96ef408d998a3ec1b17ce74d6b02f7992ad
saurabhc123/unsupervised
/source/Ops.py
630
4.09375
4
from abc import ABC, abstractmethod class Ops(ABC): def __init__(self, name): self.name = name pass @abstractmethod def perform_op(self): print ("Performing op:" , self.name) pass class Addition(Ops): def __init__(self, name="Addition"): Ops.__init__(self, nam...