blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
000bc463304a917b9db234a0a1d18ef4b5521c2e
mytram/learning-python
/projecteuler.net/problem_043.py
1,381
3.71875
4
# Sub-string divisibility # Problem 43 # The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. # Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the fol...
bcd5a99ff08a480f5738b908e4243816f73ece00
matheuslins/helltriangle
/utils.py
89
3.53125
4
def raw_input_triangle_size(): return input("""What the size of triangle? -->> """)
1968158f65e007b047094afb5b828520a6772726
him-mah10/Mario
/person.py
545
3.640625
4
class People: position=1 shape='' '''def __init__(self): self.position=1 #self.shape''' class Person(People): def __init__(self): #By default the mario is on the ground self.shape='m' #m=>Short Person and M=>Large Person self.position=1 self.height=0 pl...
ba656eb2151452f50d155b8ebb4827aa2f16d388
hcxgit/SwordOffer
/Leetcode/406.根据身高重建队列.py
828
3.53125
4
# # @lc app=leetcode.cn id=406 lang=python3 # # [406] 根据身高重建队列 # class Solution: def reconstructQueue(self, people): # 先对原数组按 h 降序、k 升序排序。然后遍历数组,根据元素的 k 值进行「插队操作」:直接把元素插入数组下标为 k 的位置。 # k 值表示排在这个人前面且身高大于或等于 h 的人数,按 h 降序排序可以方便确定身高更高者的人数 # 按 k 降序排序则先处理排在更前面的数,避免更多的元素交换操作 people = sorte...
04ef69161a22c31b9b2ce49abfabae3df7474134
prernagulati0/Hangman-Game
/hangman.py
4,401
3.6875
4
#main function def hangman(): global picked,right,n,entryy,wrong,x,temp,chances guess = inp.get() entry.delete(0,END) if(n>=1): if guess in picked: for i in range(len(picked)): while picked[i]==guess : right.pop(i) ri...
d846d690a30999d17f6e84c98dfb766439a6ba3c
Aleti-Prabhas/python-practice
/minion_game.py
714
3.515625
4
input_string=input() kevin=0 stuart=0 vowels=['a','e','i','o','u'] def sub_string(string): sub_string_set=[] for i in range(0,len(string)): for j in range(i,len(string)): sub=string[i:j] sub_string_set.append(sub) print(sub_string_set) return sub_string_set ...
df49582c33967cf24ed986057a017f3da3257664
VinayakBagaria/Python-Programming
/New folder/t_server.py
687
3.96875
4
import socket """ socket.socket() creates a socket object """ s=socket.socket() host=socket.gethostname() print(host) port=12345 """ s.bind() - this method binds the address (hostname,port) to socket for knowing where to connect """ s.bind((host,port)) """ s.listen() sets up and starts TCP-IP...
3f106eb715c560fe890f061ed72809fe5f3fbabe
2tom/python_study
/shinyawy/04_hello.py
547
3.65625
4
# coding: UTF-8 # No.1 Python Study 2015/06/11 # 数値 # 整数、少数、複素数 # 演算子 + - * / // % ** # 50 print 10*5 # 3 print 10 // 3 # 1 print 10 % 3 # 8 print 2 ** 3 # 整数と小数の演算 → 小数 # 7.0 print 5 + 2.0 # 整数同士の割り算 → 切り捨ての整数 # 3 print 10 / 3 # 3.333333... print 10 / 3.0 # -4 OS依存で結果が変わる print -10 / 3 # -3.33333... print -10...
536c35801b5318ff79e8f6463fd7aa171ac5e98a
pk2609/Hazard_01
/displaying_graphs.py
2,036
3.515625
4
# -*- coding: utf-8 -*- """ In this module we will be displaying stats about which source is giving more fake news and in what proportion. """ from matplotlib import pyplot as plt a=87 b=90 c=67 d=75 e=91 f=69 g=83 h=71 i=77 labels=["IGN","Independent","Buzzfeed","CNBC","The Washington Post","GoogleNews"...
5fa92113888104be877e04c6103f8fa7ab034823
EugeneZaharchenko/SoftServe
/elementary_tasks/task8fold/task8.py
2,685
4.25
4
""" Elementary Task 8 Fibonacci sequence for a certain range ---------------- The program outputs all Fibonacci numbers, which are in given range. The range is given with 2 arguments during the main class call. Fibonacci numbers are comma separated in output and sorted by asc. """ import sys from functools import lr...
51b6d4cda3beaa2592faacbd8becdfe36cedb6d0
Veridi/EE104Project3
/Hospital ER.py
5,430
3.703125
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 12 10:28:48 2020 @author: Paul Payumo (011344905) and Mike Lin (011001445) """ from random import randint class Global: operatingRooms = 4 beds = 400 nurses = 200 doctors = 50 medicalEquipment = 100 medication = 200 patients =...
24d18536e753b27d331dc7bbcd4428a832855c87
joaoribas35/distance_calculator
/app/services/log_services.py
1,100
3.59375
4
from os.path import exists import os from csv import DictReader, DictWriter FILENAME = 'log.csv' FIELDNAMES = ['id', 'address', 'distance'] def read_logs(): """ Will verify if a file named log.csv exists. If not, will create a log.csv file and write a header with the fieldnames. """ if not exists(FILENAME)...
2e5a33bb1682b5c6c01ab4798916fd929f3400c3
candyer/leetcode
/longestCommonPrefix.py
640
3.796875
4
# https://leetcode.com/problems/longest-common-prefix/description/ # 14. Longest Common Prefix # Write a function to find the longest common prefix string amongst an array of strings. def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' mini, maxi = min(strs), max(st...
b1ff8a58e0750ca520a4474cdb025cc535f892d9
Annabe-ll/scripts_python
/ejemplos_python/diccionario.py
482
3.625
4
peliculas = {"anabel" : "Rapido y furioso", "carli" : "la noche del demonio", "joaquin" : "cars" } print (peliculas["anabel"]) for nombre, peli in peliculas.items(): print("Nombre alumno: %s" % nombre) print("Nombre pelicula: %s" % peli) num = 24 * 10 nombre = "anabel" utiles = ["mochila","libreta","la...
fa190bece1546e35fd97fcf2fc0f5c729d5c681c
jawang35/project-euler
/python/lib/problem45.py
1,059
3.90625
4
''' Problem 45 - Triangular, Pentagonal, Hexagonal Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T_n=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal P_n=n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal H_n=n(2n−1) 1, 6, 15, 28, 45, ... It can b...
63a7f547b5c384a77972a3a1d549eb5ecfb399ad
ziyun-li/Algorithms
/String_Pattern_Finder.py
3,156
3.8125
4
def solution(s): """ This function takes in a string s, and finds the maximum equal splits of s Example, s = abcabcabcab, pattern = abc, max_eqal_split = 3 s = aaaaaaaaaaaaaaabbbbbbaaaaaaaaaaaaaaabbbbbb, pattern = aaaaaaaaaaaaaaabbbbbb, max_equal_split = 2 """ #collect index positions of first ...
4c3d94f81af357492a92938a26b4da13fd4c7bae
RayGonzalez/FormalAnalysis
/KNN/KNN.py
4,638
3.703125
4
__author__ = 'raymundogonzalez' import csv import matplotlib.pyplot as plt import random data_file = open('knn_data.csv') reader = csv.reader(data_file) my_DataList = [] #Create datalist from file for row in reader: my_DataList.append(row) #Create lists for x and y values and the labels (going to need this for ...
8a769a3c52598c3545a8db6f7b4e236275ecffd6
NestY73/Algorythms_Python_Course
/Lesson_2/turnover.py
690
3.515625
4
#------------------------------------------------------------------------------- # Name: turnover # Purpose: Homework_lesson2_Algorythms # # Author: Nesterovich Yury # # Created: 16.03.2019 # Copyright: (c) Nesterovich 2019 # Licence: <your licence> #-------------------------------------------...
346a9f4634f74626323027387540aebf49767cd3
thabbott/prisoners-dilemma
/SchizophrenicRetribution.py
996
3.578125
4
from random import random, choices from Prisoner import Prisoner """ SchizophrenicRetribution: an old Prisoner who usually copies their opponent's last choice, but forgets what to do as time goes on so they usually just cooperate with anyone and everyone. They won't stop telling you the same stories from their glory ...
1c42c564af105d39f03b5d3a96775179d4a39582
yiming1012/MyLeetCode
/LeetCode/栈/单调栈(Monotone Stack)/496. 下一个更大元素 I.py
2,435
4.1875
4
""" 给定两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。 nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。   示例 1: 输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1] 解释: 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。 ...
afda2c426dcca605f9677aca1f872c3f0d9f533e
denzow/practice-design-pattern
/04_factory/pizza_store/lib/ingredient_factory.py
1,669
3.515625
4
# coding: utf-8 from abc import ABC, abstractmethod from .ingredient import * class PizzaIngredientFactory(ABC): @abstractmethod def create_dough(self): pass @abstractmethod def create_sauce(self): pass @abstractmethod def create_cheese(self): pass @abstractm...
f3de785aaf121ecb89bc70272210727208cbd51c
edersoncorbari/hackerrank
/python/dijkstras.py
1,160
3.5625
4
#!/usr/bin/python -tt import sys from heapq import * def read(fn): return tuple(fn(i) for i in sys.stdin.readline().split(' ')) def load_graph(N, M): graph = [dict() for i in range(0, N)] for i in range(0, M): (x, y, r) = read(int) x -= 1 y -= 1 r = r if y not in graph[x] else min(r, graph[x]...
432b80f967e6dda0efc977bb217e1834b9bf0f67
ViniciusEduardoM/Enigma
/Enigmadl.py
7,836
3.625
4
# Importando as bibliotecas necessárioas # Nós precisamos da biblioteca ascii_lowercase para puxar uma lista com alfabeto ingles from string import ascii_lowercase class enigma: def __init__(self, plugboard = {" ":" "}, alpha=None, beta=None, gama=None): ''' Setando as configurações do ...
b6582881a59ad79ae2f96ebd9c02801ac2a120e1
Saeid-Nikbakht/Data_Analysis_UK_Crime
/UK_Crime_Statistics.py
9,435
3.71875
4
#!/usr/bin/env python # coding: utf-8 # # About this dataframe # ## Context # Recorded crime for the Police Force Areas of England and Wales. # The data are rolling 12-month totals, with points at the end of each financial year between year ending March 2003 to March 2007 and at the end of each quarter from June 2007....
6694b60e9a62468e9304591936d2078e613fae73
Jakamarinsek/Backend_python
/Pretvornik.py
264
4.0625
4
mile = 1.852 print("Hi. I can convert km to miles.") odgovor = "yes" while odgovor == "yes": number = int(raw_input("Enter km: ")) km = number / mile print km odgovor = raw_input("another coversion?: ").lower() if odgovor == "no": print ("bye")
e881c0247fd3c4a908d66386947acc5e153c759b
Palash51/Python-Programs
/oop prgm/All-OOP/inheritance/inheritance2.py
463
3.96875
4
## tutorial -- inheritance # -- inheritance is implicite ## -- issubclass(A,B) return boolean ### class Person(object) --> it is explicit but in python3 no need to define it like this (implicit) ### by default class is a subclass of object class class Person: pass class Employee(Person): pass def main(): prin...
356ac29fd2271c864fe24b059dd9a3c82e7d3de1
cuekoo/python-demos
/interview-problem/interview-problem.py
1,315
3.84375
4
#! /usr/bin/python # This program demonstrates the solution to the problem in Quora. # # Suppose you are going to hire one person for a position. There are 100 # candidates. You interview one by one and should make the decision # immediately after the interview. There's no way to get back the candidates # who you a...
407845504f44fc97568ac0bd70aa5eae5205593e
lvsazf/python_test
/variable.py
348
3.828125
4
# -*- coding: utf-8 -*- ''' Created on 2017年6月29日 @author: Administrator list:有序列表,可变 ''' classmates = ["Michael","Boy","Tracy"] print(classmates) #list长度 print(len(classmates)) ''' tuple 元组 一旦初始化完,就不能修改 ''' print("---------------tuple---------------------") t = (1,2) print(t)
148a2433f78ad0f419c3c415bff6f27b8538c48a
3esawe/Python-Linux
/Firecode/unique.py
324
3.6875
4
def unique_chars_in_string(input_string): unique = {} for i in input_string: unique[i] = unique.get(i, 0) + 1 maxval = max(unique.keys(), key=(lambda k: unique[k])) print(unique) if unique[maxval] > 1: return False else: return True print(unique_chars_in_string("Language...
abafada0110b8cba9f6bd2bc7879e44c559c646a
SvetlanaBicanin/MATF-materijali
/3. godina/pp vezbe/cas03 - Funkcionalno programiranje (Python)/3.py
407
3.734375
4
# Marko, Petar i Pavle su polagali ispit iz predmeta # Programske Paradigme. Napisati program koji sa # standardnog ulaza ucitava ocene koji su dobili, # a potom ispisuje listu parova (student, ocena) na # standardni izlaz. imena = ['Marko', 'Petar', 'Pavle'] ocene = [int(input("Ocena za " + ime + ": ")) for ime in i...
a49b79d5e2904914ec815365ccd49ee7dfed10b7
ameet-1997/Course_Assignments
/Machine_Learning/Programming_Assignments/CS15B001_PA1a/Code/q2/run.py
1,818
3.5
4
""" This file has been used to complete assignment parts 1,2,3 of PA1 Includes generation of synthetic data, learning Linear and KNN classifiers and getting the accuracy values Author: Ameet Deshpande RollNo: CS15B001 """ import os import numpy as np import pandas as pd from sklearn.linear_model import Li...
81126c7dbecb3c1d299601de32f6ddb877fc3d24
suman2826/Building_BLocks_of_Competitive
/Array/find_min.py
378
3.5625
4
def find_min(a,low,high): if high<low: return a[0] if high == low: return a[low] mid = (high+low)//2 if mid < high and a[mid+1] < a[mid]: return a[mid+1] if mid > low and a[mid] < a[mid-1]: return a[mid] if a[high]>a[mid]: return find_min(a,low,mid-1) return find_min(a,mid+1,high) a = [10,20,30,4...
c8ed4f0f1024091194fb7a91bbee1d5c1e683725
Mercy021/pythonclass
/dog.py
323
3.609375
4
class Dog: breed="Bulldog" color="grey" def __init__(self,breed,color): self.breed=breed self.color=color def bite(self): return f"Hello chew,my pet bites strangers {self.breed}" def bark(self): return f"Hello,my dog barks every morning {self.breed}" ...
a8ff0c36f7274aff0d820db1d35bc71dda4980ec
windy319/leetcode
/binary-tree-level-order-traversal-ii.py
1,016
3.8125
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrderBottom(self, root): if not root: ...
20bce1c1c43fedeed6448208bc8818507d0a8a29
climatom/BAMS
/Code/Misc/VapourTransport.py
2,309
3.578125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Simple script to estimate moisture flux through the South Col. The principle here is to take the mean spechum and mean wind between South Col and Balcony and estimate the vapour flux in this corridoor. """ import pandas as pd, numpy as np import matplotlib.pyplot...
d9296f0601e1a25b11091028231e1773c56befe5
yeeryan/programming-python
/Lessons/Lesson 5.py
137
3.875
4
# Lists odds = [1,3,5,7] print('odds are:',odds) # Exercise my_list = [] for char in 'hello': my_list.append(char) print(my_list)
cb5ecc6ce57739a80b9e5fa76b883abfbab10eaf
feleck/edX6001x
/lec5_problem6.py
352
3.9375
4
def lenIter(aStr): ''' aStr: a string returns: int, the length of aStr ''' # my solution: RECURSIVE!!!! - should be iterative ''' if aStr == '': return 0 else: return 1 + lenIter(aStr[:-1]) ''' length = 0 while aStr != '': aStr = aStr[:-1] ...
4bf85a2ec403e3f667cf55ab090ac700b3a6cd11
dizethanbradberry/anandh-python
/chapter 2/pgm1-sum.py
289
3.890625
4
# Program to provide an implementation for built in function 'sum' def sum(l): sum=0 for i in l: sum=sum+i return sum n=raw_input("Enter the length of list:") l=[] for i in range(int(n)): l.append(int((raw_input("Enter the element %d:" % i)))) print 'list =',l print 'sum =',sum(l)
c8ab423a0dd38f02dbf42f1a436d52054c3258c2
andersonpablo/Exercicios_Python
/Aula08/avaliando-questao01.py
907
4.21875
4
# -*- coding: utf-8 -*- # 1. Faça um algoritmo que leia n valores e calcule a média aritmética desses valores. # Lê a quantidade de valores a serem digitados quantidade = input("Digite um número: ") # Criando a variável i para contar de 1 até o valor da variável quantidade i = 1 # Criando a variável que será usada p...
7447787a978481feab09108a81c49c01bcf9bbfb
NCRivera/COP1990-Introduction-to-Python-Programming
/Assignments/Weights - Lists.py
840
3.8125
4
# FIXME (1): Prompt for four weights. Add all weights to a list. Output list. weights = [] people = 4 for person in range(people): score = float(input("Enter weight %d:\n" % (person + 1))) weights.append(score) print('Weights:', weights) # FIXME (2): Output average of weights. averageWeight = sum(weights)/peo...
c79e597d19e8dc91b674c2e63a048029297f43f6
khela123/exercises
/journalbirthdays.py
2,656
3.765625
4
import csv # import sys class Birthdays: # xRead from an input file # xAdd entry to journal # xView entries # xSearch entries # Edit entries # Delete entries # xExport def __init__(self): self.birthday_id = 1 self.entries = [] def read_input(self): with ...
7d8a0270e5a2e56d239bbbb499dfbdec7bce235e
gewl/Exercisms
/python/pangram/pangram.py
358
3.890625
4
from string import ascii_lowercase def is_pangram(phrase): alphabet_dictionary = {letter:False for letter in ascii_lowercase} for letter in phrase: letter = letter.lower() if letter in alphabet_dictionary: alphabet_dictionary[letter] = True return all(letter == True for letter ...
faba3c76462321ba453f49646fde34404cc836e2
donsergioq/learn-homework-1
/4_while1.py
840
4.15625
4
""" Домашнее задание №1 Цикл while: hello_user * Напишите функцию hello_user(), которая с помощью функции input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” """ def hello_user(): answer = '' while answer != 'Хорошо': answer = input('Как дела? ') print('Рад за Вас') ...
d91fa9fa82e5c5db73bc708f18cdadcbeeceaf13
reichlj/PythonBsp
/Schulung/py01_einführung/f060_input.py
214
4.25
4
name = input("Dog's name? ") if name == "Blanchefleur" or name == "Camille": print("Bonjour " + name) elif name == "Dolce" or name == "Valentino": print("Buongiorno " + name) else: print('Hi ' + name)
f70037f414c4d495354a92f88427b0a5c86e4dbf
todaybow/python_basic
/python_basic_jm_22.py
2,052
3.953125
4
''' 파이썬 데이터베이스 연동 (SQlite) 테이블 조회 ''' import sqlite3 # DB파일 조회(없으면 새로 생성) conn = sqlite3.connect('D:/Python/python_basic/resource/database.db') # 커서 바인딩 cursor = conn.cursor() # 데이터 조회 cursor.execute("SELECT * FROM users") # 커서 위치가 변경 # 1개 로우 선택 # print('One-> \n', cursor.fetchone()) # 지정 로우 선택 # print('Three-> ...
c742ae188533ee2a08faca9347dbae2869144ff4
Caio-Batista/coding-marathon-problems
/hackerrank/min_max_sum.py
466
3.53125
4
def miniMaxSum(arr): ordered = count_sort(arr) min_sum = sum(ordered[0:4]) max_sum = sum(ordered[1:]) print(f'{min_sum} {max_sum}') def count_sort(arr): temp = [0] * 100000 ordered = [] for e in arr: temp[e] += 1 for i in range(len(temp)): for _ in range(temp[i]): ...
8d11169a869dbdbab4db192659e43f0f8b03489a
Remyaaadwik171017/mypythonprograms
/collections/list/nestedlist/list4.py
136
3.96875
4
t1=(1,2,4,6,3,6,8,12,34,22)#tuple t2=sorted(t1) #after sorting will return list not tuple print(t2) t3=sorted(t1,reverse=True) print(t3)
a02e2ae96b764d6a94b02fd5be8b6d1ceaef9413
mebinjohnson/Basic-Python-Programs
/Journal Testing/Q18 Mebz(Create data.txt).py
642
3.921875
4
read_file=open('data.txt','rb') string='' string=read_file.read() read_file.close() upper='' lower='' other='' print string for letter in string: #if letter.isalpha(): if letter.isupper(): upper+=letter elif letter.islower(): lower+=letter else: other+=letter print...
17544229d9f5c1a697ec95b67c0e9410f50d2b46
psukhomlyn/HillelEducation-Python
/Lesson2/HW-2-password_validator.py
985
4.5
4
""" password validation rules: 1. password should be 8 characters or more 2. password cannot contain spaces 3. password should include at least 1 digit and 1 special symbol (Shift+digit on keyboard) """ import string password: str = input('Enter password: ') is_digit_found = False is_symbol_found = False if len(pass...
0a55cd4dac118fd9d72b1a9348c8433eeee13957
harshavachhani/python_intermediate_project
/q03_create_3d_array/build.py
186
3.84375
4
# Default Imports import numpy as np # Enter solution here def create_3d_array(): n=3*3*3 array_a = np.array(range(n)) array_a = array_a.reshape((3,3,3)) return array_a
3badd4865b7411d18df907d258f6ccf6a29cb0b8
luisalcantaralo/Tarea-02
/porcentajes.py
575
3.96875
4
#encoding: UTF-8 # Autor: tuNombreCompleto, tuMatricula # Descripcion: Texto que describe en pocas palabras el problema que estás resolviendo. # A partir de aquí escribe tu programa mujeres = int(input("Mujeres inscritas: ")) hombres = int(input("Hombres inscritos: ")) total = mujeres + hombres porcentajeMujeres = r...
3d9e57b9640d52849b8be5622bbc4a178658b9d1
snaveen1856/Test_project
/emp_open.py
968
3.671875
4
# Writing a file(Bonus.txt) with only one file (name) as input name=input('Enter file name bonus: ') b=open(name,'w') # first it will create file with user give name then take input as filename fname=input('Enter file name:') with open(fname) as f: data=f.readlines() # Here it will read data line by lin...
577f5aed445c5bf4e790d0174183f7481ebee6a8
SeanLeCornu/Coding-Notes
/4. Python - DataCamp/1. Intro to Python/1.4 NumPy Stats.py
436
3.65625
4
import numpy as np # numpy has lots of inbuilt mathematical functions such as mean and median np_2d = np.array([[1.7, 1.6, 1.8, 2], [65, 59, 88, 93]]) print("Mean:", np.mean(np_2d[1])) print("Median:", np.median(np_2d[0])) # other common functions include correlation coefficient, np.corrcoef and standard deviation np...
f7e13e224c49e4d71fb286ee3b6aaf2efb42027a
daniel-reich/ubiquitous-fiesta
/Pjffmm9TTr7CxGDRn_3.py
784
3.78125
4
def is_ascending(s): def group_by_size(string, size): if len(string) == size: return [string] elif len(string) < size: return ['XX'] else: return [string[:size]] + group_by_size(string[size:], size) def ascending(group, index = 0, previous = None): if previous == None: previ...
c15ba12a1fe7b9f756395a3468008a8cbac8fa4e
navarrjl/scientific_computing_python_projects
/time_calculator/time.py
3,224
3.984375
4
import math def add_time(cur_time, time_add, day_of_week=" "): current_time, period = cur_time.split(' ') current_hour, current_minute = current_time.split(':') hour_to_add, minutes_to_add = time_add.split(':') day_of_week = day_of_week.lower() days_of_the_week = ["saturday", "sunday", 'monday', "t...
ae5aa91b9e74acea9a642444324a6f07f263f5a1
Usernam-kimyoonha/python
/12.py
338
3.9375
4
x = 3 y = 1 if x > y : # 3이 1보다 크면 print("x(3)는 y(1)보다 크다.") #출력이 된다. print("x가 y보다 크기(True)때문에 출력 된다.","\n") if x < y : # y가 x보다 크지 않다. print("x보다 y가 크다") # 출력이 안된다. print("y가 x보다 크지 않기(False)때문에 출력 안된다.","\n")
374c5ee25d60f2c91470f5e58e8f96b26b4dfdce
sounmind/problem-solving-programmers
/level_1/Pg_12825.py
367
3.75
4
# https://programmers.co.kr/learn/courses/30/lessons/12925 def solution(s): answer = 0 if s[0].isalpha(): if s[0] == "+": answer = int(s[1:]) else: answer = -int(s[1:]) else: answer = int(s) return answer print(solution("1234")) print(solution("-134"))...
5af1a8a0d5c5184c9a95ee3cd12ac22332db81f4
buwenzheng/Study
/python-study/python-basics/6-OdjectOrientedProgramming/5_getObjectMsg.py
5,531
3.78125
4
# !/user/bin/env python3 # -*- conding: utf-8 -*- # 获取对象信息 # type()获取对象的类型,基本类型都可以用type(),来判断 type(123) # 输出 <class 'init'> type(abs) # <class 'builtin_function_or_method'> # 但是type()函数返回的是什么类型?它返回对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同 type(123)==type(456) # True type(123)==int # True type(...
9649c5ed3408179b73b222d0a691598dfaf1699d
wasymshykh/ai-ml-course-practice
/artificial-intelligence-work/final-term-practice/csp/Variable.py
222
3.53125
4
class Variable: def __init__(self, name): self._name = name def get_name(self): return self._name def __eq__(self, other): other: Variable return self._name == other.get_name()
11d95f94377f889dae7675eaa47d55b7178c8b3c
fatima-a-khan/ITM200-IntroToProgramming
/poly1.py
581
3.578125
4
#poly.py #Author: Fatima Khan #Input s = input("Enter input such as a=10, b=5, c=1, x=1: \n"); s = s.lower(); #Parse operands i1 = s.find('a'); i2 = s.find(','); ai = s[i1+2:i2].strip(); a = float(ai); o1 = s.find('b'); o2 = s.find(',', i2+1); bo = s[o1+2:o2].strip(); b = float(bo); p1 = s.find('c'); p2 = s.find(',...
6d31371a7564e22fa29c69cebe8896b117c8f073
zhuwhr/interview
/snippets/prim.py
1,779
3.890625
4
""" quite similar to dijkstra find shortest path from start node to all nodes prim vs dijkstra: 都是通过贪心的算法用BFS dijkstra找的是最短路径,在发现环的时候,要对比最短路径是不是有变化,然后更新 prim是发现环的时候就不管它,找的是从根开始到每个点的最小总和,并不一定是到每个点的最短路径 """ import heapq def prim(graph, costs, start): items = {} pq = [] for i in graph.keys(): if i ...
9ee96b1a3baec5dbfd3e4d0a020a26667353dc8a
dandubovoy/DPV
/chap1/modulo_expo.py
519
3.6875
4
from readint import readinput def modular_exp(x, y, N): """ given two n-bit integers x and N, an integer exponent y output: x^y mod N """ if y == 0: return 1 z = modular_exp(x, y//2, N) if y % 2 == 0: return (z*z) % N else: return (x*z*z) % N def main(): print ("X...
6a230e0e26e8b1992c6d2652b55a8860b75154b5
nivleM-ed/WIA2005_Algorithm_Assignment
/main.py
4,325
3.609375
4
import copy from time import sleep from Map import airports, dijkstra, getAirports, plotMap, getPossibleRoutes from Words import Analysis, plotAllWords, plotNegVPos, plotStopwords def compare(p, n): if p > n: print("The country have positive political situation.") elif p == n: print("The count...
34e1943fb795e8889cc1a61e50ad6cdfc219dcef
karchi/codewars_kata
/已完成/Find Maximum and Minimum Values of a List.py
1,570
4.03125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' # Find Maximum and Minimum Values of a List题目地址:http://www.codewars.com/kata/577a98a6ae28071780000989/train/python ''' import unittest class TestCases(unittest.TestCase): def test1(self):self.assertEqual(min([-52, 56, 30, 29, -54, 0, -110]), -110) def test2(self)...
a731325eb1221231ccdd918e2fa620f7a07b2d1b
bikashkrgupta/Blockchain
/complete_blockchain.py
2,479
3.984375
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 26 13:12:15 2020 @author: Kiit1705576 """ blockchain=[] def get_last_value(): return(blockchain[-1]) def add_value(transaction_amount,last_transaction=blockchain[-1]): blockchain.append([[last_transaction],transaction_amount]) def get_transaction_v...
7bc8926e6c79bc24e3fd752e27323bb4fa517caa
radkovskaya/Algorithms
/les2/1.py
1,945
3.953125
4
# 1.Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции вводятся пользователем. После выполнения вычисления программа не должна завершаться, а должна запрашивать новые данные для вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве...
5453db4b25bd8232c31f364493709cff4dbbec8a
nnayrb/--Python--
/CeV - Exercises/Python/jogo advinhar v1.0.py
626
3.671875
4
from random import randint from time import sleep from termcolor import colored computador = randint(0, 3) print('\033[34;40m-=-\033[m' * 20) print('Vou pensar em um número entre 0 e 8. Tente advinhar...') print('\033[34;40m-=-\033[m' * 20) jogador = int(input('Em que número eu pensei??')) #Jogador tentar advinh...
22f284e9a6b764263af8656e12dc81b37a263450
JnKesh/Hillel_HW_Python
/HW15/Peter's height.py
711
3.671875
4
while True: s = list(map(int, input('Enter pupils heights: ').split())) if max(s) > 200: # Проверка списка на максимальное значение print('Only numbers between 1 and 200 are accepted, try again.') if min(s) < 1: print('Only numbers between 1 and 200 are accepted, try again.') else: ...
f558b9da2bc8ce26578899af4e15349b63c82e78
Sly143/Criptografia
/1 Unidade/transp_linhas.py
1,844
3.765625
4
# encoding: utf-8 def railfence_id(tam, key): ''' Retorna um lista de inteiros com a posicao da linha que o caracter do texto ira ocupar, variando de 0 ate key - 1. ''' j = int(0) inc = int(0) idx = [] for i in range(tam): if j == key - 1: inc = -1 elif j...
d2d3394728f06090dfc37375d2312652d9f32710
mtariquekhan11/PycharmProjects
/welcome Projects/factor_factorial.py
1,072
4.21875
4
# Author: Mohd Tarique Khan # Date: 14/10/2019 # Purpose: To find the factors and factorials condition = "True" def factor(n): print("The factors of ", n, "are: ") for i in range(1, n + 1): if n % i == 0: print(i) i = i + 1 def factorial(n): factorial = 1 if n == 0:...
522afa119c64845ae6e1e09af595ef88635dcfe8
JanZahalka/ii20
/ii20/data/ImageFinder.py
3,064
3.546875
4
""" ImageFinder.py Author: Jan Zahalka (jan@zahalka.net) Finds all images in specified directory (recursively) and establishes image ordering. """ import os import PIL class ImageFinder: @classmethod def find_all_images(cls, traversed_dir, image_list=[], relative_dir_path=""): ...
3bffd95baafb7581cae575744256028bb4971142
salahlotfi/Python-Scripts
/CDC - Overall DeathCount.py
1,499
3.875
4
# This script is created to count the number of deaths # given diseases in a given year reported by CDC database. # The disease codes are obtained from ICDO dictionary, so you need to put # the icd_nodot script as well as database file in the same folder. The final file is a .CSV file. import icd_nodot def main() : ...
a8883f4ca635181e7d52ef488473d3808d46be23
Schnei1811/PythonScripts
/CLRS Algorithms/Class2/tkinterHeuristicTSP.py
5,480
4.09375
4
from tkinter import * from random import * from math import sqrt points = [] size = 550 def click(event): draw_point(event.x, event.y) points.append((event.x, event.y)) def draw_point(x, y): c.create_oval(x, y, x+1, y+1, fill="black", tags = "point") def draw_points(): c.delete("point", "line"); map(lamb...
97c41771bfc591b6ec7af42a2e3fce0e6473de32
jhirniak/pizza-for-students
/data_engine/geometry.py
1,909
3.84375
4
class Point: def __init__(self, x, y): self.x, self.y = float(x), float(y) def distance(self, other): return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5 def add(self, other): return Point(self.x + other.x, self.y + other.y) def midpoint(self, other): ret...
20cda797e60043083dbff471c9bbdb3e8cdbdb86
prateekvishnu/Numpy_practice
/Basic Operations.py
1,288
3.875
4
import numpy as np a = np.array([20, 50, 70, 40]) b = np.arange(10, 50, 10) c = a-b print c # power of each element print c**2 #sin fuction print 10*np.sin(c) #Returns a bool type array - returns True if value less tha n25 else returns False print c<25 # Element-wise and Matrix Multiplication A = np.array( [[1,1], [...
22d35a0bc6494d700c653d17caf9d087c83a73f7
shu6h4m/Python_Assignments
/A3_Control Constructs.py
2,946
4.21875
4
''' Assignment_3 Program to perform following tasks: 1) Takes input from user and save it to n 2) Print Prime Numbers and their count between 1 and n. 3) Print Even And Odd Numbers between 1 to n. Submitted by Subham Sharma IDE Used:- https://www.onlinegdb.com/ :) ''' def printp(n): #Defining function to print prime ...
40e8b918ea19f3b7e7c82eb6ddaaef59c5aa8a78
Pa1245/Coding_Practice
/Python/ProjectEuler/PrimeNumbers/sum_of_primes.py
894
3.796875
4
import math import timeit def isPrime(number): if number == 1: return False elif number<4: return True elif number%2 == 0: return False elif number < 9: return True elif number%3 == 0: return False else: limit = math.sqrt(number) i = 5 ...
32dc69bc9381b24568227fb5b08ad8a01d35c098
jonborg/IASD
/uninformed.py
878
3.9375
4
from uninformed2 import * # trying to implement uniform cost, this way we can garantee optimality with # a resonable complexity def choose_next_node(open_list, closed_list): """Apply Uniform cost algorithm to choose next node/step in tree""" selected_node = open_list[0] minimum_cost = selected_node.g...
1d0b78af74837cb98625fc3c3f0370a97bb33958
danieka/grupdat
/3/longest.py
269
4.09375
4
def longest(s): words = s.split() longest_word = "" for word in words: if len(word) > len(longest_word): longest_word = word return longest_word with open("/home/daniel/Code/grupdat/3/dikt.txt") as f: s = f.read() print(longest(s)) print("Nu filer stängd")
7de5999f1a7faa2fd0d869266bb88a69c17da302
Rookiee/Python
/Python2.7/mile_trans_kilomettet.py
317
3.671875
4
def MileTransKilo(): input_str = raw_input("Input mile or kilo: ") if input_str[-1] in ['K','k']: m = eval(input_str[0:-1]) / 0.62 print ("The result is %f miles." %m) elif input_str[-1] in['M','m']: k = eval(input_str[0:-1]) * 0.62 print (" %f kilo ." %k) else: print "Input error" MileTransKilo()
d06b425e784066c68ff4f82bcafdf5603c24c576
9hafidz6/self-projects
/hacker rank/newyearchaos.py
1,730
3.84375
4
#!/bin/python3 # did not manage to pass all test cases import math import os import random import re import sys # # Complete the 'minimumBribes' function below. # # The function accepts INTEGER_ARRAY q as parameter. # def swap(index1,index2,elem,res): # check if can swap ie, 2 positions max # use remove and i...
8467c79b2da6ec9b0381450db8caf0e4f78e3502
SMMend/PythonLab
/slicing.py
1,400
4.0625
4
text = "My GitHub handle is @shannonturner and my Twitter handle is @svt827" # Let's extract the GitHub handle using str.find() and slicing. snail_index = text.find('@') print text[snail_index:snail_index + 14] # So the first slicing index is given by the variable, but we're still relying on knowing the exact number...
97e551318a5d4175393e2ae253fccb9935adbdf5
AP-MI-2021/lab-3-AlexandruGirlea01
/main.py
7,339
4.0625
4
def tipareste_meniu(): print("1. Citire date") print("2. Cea mai lunga secventa in care toate elementele sunt patrate perfecte") print("3. Cea mai lunga secventa in care toate elementele au acelasi numar de biti de 1 in reprezentarea binara") print("4. Cea mai lunga secventa in care toate elementele sun...
39c82b00fa2f9d1a053859052be9e0c573540dc3
kaitoukito/PythonADT
/7. LinkedListADT/PositionList.py
889
3.59375
4
import DoublyLinkedBase class PositionList(DoublyLinkedBase._DoublyLinkedBase): # -------------------- nested Position class -------------------- class Position: """An abstract representing the location of a single element.""" def __init__(self, container, node): """Constructor sh...
57de694b14db9a8b2ed7ec3f61c4759f4348c61c
sunho-park/Notebook
/textbook/14.dataframe/list14_27.py
270
3.875
4
import pandas as pd from pandas import DataFrame dupli_data = DataFrame({"col1":[1, 1, 2, 3, 4, 4, 6, 6], "col2":["a", "b", "b", "b", "c", "c", "b", "b"]}) print(dupli_data) print(dupli_data.duplicated()) print(dupli_data.drop_duplicates())
5ce4aeab8b28262f9ca3e8b60952be27200d9db4
svenenri/python-csv-transform
/handler.py
6,190
3.734375
4
""" Module used for performing transformations to a csv file that are needed to prepare the csv file for ETL process """ from collections import defaultdict import re import csv import boto3 import botocore def extract_nums(code_list): """ Method to remove numbers from the Project Code and Project Series. ...
e88fa6b8801496e80b69b89c08b5129d91c2cd6d
L273/Cryptology-
/古典密码/古典密码项目文件/hill加密(弹性)/hill.py
11,546
3.765625
4
def menu(): li = { 1:en_file, 2:de_file } choose=True while(choose): try: print("1、加密文件") print("2、解密文件") choose = eval(input("请输入选择:")) if(choose==2 or choose ==1): break choose=True except: ...
2cd8c34beaa70ec4a8b9076fb85187839c82297d
chphuynh/CMPM146
/P3/mcts_vanill.py
3,598
3.578125
4
from mcts_node import MCTSNode from random import choice from math import sqrt, log num_nodes = 1000 explore_faction = 2. def traverse_nodes(node, state, identity): """ Traverses the tree until the end criterion are met. Args: node: A tree node from which the search is traversing. stat...
eea8a43a6c18386e98a34dd44e6fc385cd6fc338
kathleentully/process_haz_waste
/find_clusters.py
805
3.53125
4
#import simplejson as json import json, urllib, csv key = json.loads(open('key.json').read())['key'] VAR_LIMIT = 50 def find_points(year,num): data = json.loads(open('20'+year+'-hazwaste.json').read()) point_list = [] for point in data: if len(point['areaAroundPoint']['points']) >= num: point_list.append(poin...
a10cf95e53cfac5f7f34b305b70c79f2b90a299d
Voronit/Python
/Основы Python/6.Работа с файлами/Задача 1.py
1,889
3.5625
4
def main (_file): file = open(_file) cook_book = {} i = True for lines in file: dish = "" if i == True: for line in lines: if line != "\n": dish += line else: cook_book.update({dish: support1(_file, lines...
56b31a245e622cad125c8f4fcc9a434cb9b7e1b3
lidongdongbuaa/leetcode2.0
/链表/链表排序与划分/148. Sort List (linked list).py
10,842
4.1875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019/11/13 9:14 # @Author : LI Dongdong # @FileName: 148. Sort List (linked list).py '''''' ''' 题目分析 1.要求:Sort a linked list in O(n log n) time using constant space complexity. Input: 4->2->1->3 Output: 1->2->3->4 Input: -1->5->3->4->0 Output: -1->0->3->4...
d6a303fb8a6bde2a8e0d8cbf06111b2d8b8b4d43
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4029/codes/1749_3089.py
212
4.03125
4
n = int(input("Digite um numero: ")) s = 0 while ( n != 0): s = s + n n = n + 1 if (n > 1): msg = "Direita" else: msg = "Esquerda" else: n = int(input("Digite um numero: ")) print(n) print(msg)
9062b9544dba86ffcb31d6d19bb435022107aa41
cloudenjr/Calvert-Loudens-GitHub
/Self_Study/Python_MC/Py_Prog/Using_DB_inPython/createDB/contacts2.py
1,969
4.3125
4
# ********************************************************************************************************************* # Notes: # - in Python, when you want to just iterate over the resulting dataset, Python allows you to execute queries using the # connection w/o having to create a cursor # - you really should commit...
85b6513ca460043e6d02a8b7a3a9774d7128a7ab
tashakim/code-catalog-python
/catalog/suggested/graphs/topological_sort.py
824
3.671875
4
def topological_sort(self): """ Determines the priority of vertices to be visited. """ STATUS_STARTED = 1 STATUS_FINISHED = 2 order = [] statuses = {} assert (not self.contains_cycle()) for vertex in self.get_vertex(): to_visit = [vertex] while to_visit: ...
47b090e88a2e00fe69fa6039c1b715433ab1e2fd
raissaazaria/pythonexcercise-1and2
/python exercise 2 no 4.py
1,059
3.71875
4
qty = eval(input("Enter the number of packages purchased:")) retails_price = qty * 99 if qty >= 10 and qty <=19: result1 = (10*retails_price/100) result_1 = retails_price - result1 print("Discount amount @10:$", format(result1)) print("Total amount: $", format(result_1, ".2f")) elif qty >= 20 a...
549556d660759df46ffa9387402059552d0bd4ba
CodingDojoDallas/python_oct_2017
/staci_rodriquez/OOP/callcenter.py
2,306
3.71875
4
class CallCenter(object): def __init__(self): self.calls = [] self.queue_size = 0 #adds a call to the end of the queue def add(self, call): self.calls.append(call) self.queue_size+=1 return self #removes a call by phone number def remove_by_number(self, number): for call in self.calls: if call.n...
27d2f39716e8a6c8d69cb9448584ebd539a2843f
Faturrahman025/faturrahman
/kelasDemo.py
947
3.984375
4
class Demo(object): def __init__(self, m,p,a): self.mahasiswa = m self.pelajar = p self.aparat = a def hitungJumlah(self): return self.mahasiswa + self.pelajar + self.aparat def cetakData(self): print("mahasiswa\t: ",self.mahasiswa) print("pelajar\t: ",self...
7f64ec931e7823f036f286b23c272551309c5afb
DCHuTJU/blockchain2021
/graduation/2018级/hudengcheng/code/code/storage_allocation_code/normalization/normalization.py
488
3.53125
4
import numpy as np # 使用 sigmod 归一化函数 def normalization(number_set): for i in range(len(number_set)): number_set[i] = 1.0 / (1 + np.exp(-float(number_set[i]))) return number_set def normalization_with_number(num): return 1.0 / (1 + np.exp(-float(num))) def mapminmax(data, MIN, MAX): d_min =...
3b197763dd054afef7e3a4aafb5f2c5b07cef08d
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
/students/RoyC/lesson01/comprehensions.py
321
3.96875
4
#!/usr/bin/env python3 # Lesson 01, Comprehensions import pandas as pd music = pd.read_csv("featuresdf.csv") toptracks = sorted([x for x in zip(music.danceability, music.loudness, music.artists, music.name) if x[0] > 0.8 and x[1] < -5], reverse=True) for track in toptracks[:5]: print(track[3] + " by " + track[2]...
3b0fa1960d6b5281a087b45d0f50f5fbc8978bc8
darkraven92/CodeAbbey
/Python/Problem #4 Minimum of Two/problem4.py
196
3.53125
4
c = [] data = int(input("data:\n")) for i in range(data): x,y = input().split() if int(x) < int(y): c.append(x) else: c.append(y) for u in c: print(u, end =" ")