blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
237b2110af02b94b19b78f0e6536d30cc07d7008
sweetpo1son/coding
/pe/94.py
760
3.59375
4
#x^2-3*y^2=1 #x^2-3y^2=-2 #2d+1=y^2 #p=12d+2=6*(y**2)-4 #x=2,y=1 #p=12y**2+4<1000**3 #y<9129 ''' import math def isSqr(n): a = int((math.sqrt(n))) return a * a == n li2=[] for n in range(1,300): #print(n) sq=3*n**2-2 if isSqr(sq): li2.append((int(math.sqrt(sq)),n)) print(li2) ''' x=2 y=...
89a104bf2e1cedfeea5db117d355522663cd234c
josd/josd.github.io
/temp/python/lee.py
2,356
3.6875
4
# See https://en.wikipedia.org/wiki/Lee_algorithm # Original code from https://stackoverflow.com/questions/45969687/python-maze-route-finding def gen_lee(start, size, traversable): neighbor_offsets = [(0, 1), (1, 0), (0, -1), (-1, 0)] score = 0 lee_map = [[None for _ in range(size)] for _ in range(size)] ...
12c0391d2fe3f701c8d21b5994e10ed64c15ad63
josd/josd.github.io
/temp/python/fibonacci.py
361
3.578125
4
# See https://en.wikipedia.org/wiki/Fibonacci_number from sympy import fibonacci if __name__ == "__main__": cases = [ "fibonacci(0)", "fibonacci(1)", "fibonacci(6)", "fibonacci(91)", "fibonacci(283)", "fibonacci(3674)" ] for c in cases: print('[] :p...
1159724dcf6a6d298bffea2b3f367eaa9c5a1455
dsouzadyn/ud036_StarterCode
/media.py
2,248
4.34375
4
class Video: """Base class for videos. """ def __init__(self, video_title, video_trailer): """The Video class constructor takes 2 arguments. Args: movie_title (str): The title of the video movie_trailer (str): Link of the video """ self.title = video_...
74d669744e82796114da6ec79824468b1557508f
pankaj-cloud/Python_Essentials
/Simple input and output.py
580
4.3125
4
# input a float value for variable a here # input a float value for variable b here # output the result of addition here # output the result of subtraction here # output the result of multiplication here # output the result of division here print("\nThat's all, folks!") value_a = float(input("Type a value fo...
033b947e69687f0f3cc7cda7651b462e89747c0d
nguyenductinh1998py/PythonLab
/Python_Lab_02/3.py
99
3.609375
4
lst = [] n = int(input()) for i in range(n): lst.append(int(input())) lst.sort() print(lst)
b98885c07db72e195108e20a240a2fc18810a831
nguyenductinh1998py/PythonLab
/Python_Lab_01/7.py
292
3.625
4
n = int(input("Nhập n đề liệt kê các sos nguyên tố trước nó : ")) def soNT(i): count = 0 for s in range(1, i + 1): if (n % s == 0): count += 1 if count == 2: print(s) for n in range(2, n + 1): if n == 1: print(1) soNT(n)
07da6105c19129f459ab9d799844f80376cd4da0
cindyyklai/Python-code-experiments
/median.py
413
4.125
4
# Write a function called median that takes a list as an input and returns the median value of the list. def median(numbers): numbers = sorted(numbers) length = len(numbers) if len(numbers) % 2 == 0: mid = length / 2 first = numbers[mid - 1] second = numbers[mid] return (fi...
7c988ebe600199e16eb55d661aca40de7116d7ab
martadelac/python_syntax
/convert.py
1,630
4.5625
5
def convert_temp(unit_in, unit_out, temp): """Convert farenheit <-> celsius and return results. - unit_in: either "f" or "c" - unit_out: either "f" or "c" - temp: temperature (in f or c, depending on unit_in) Return results of conversion, if any. If unit_in or unit_out are invalid, return "I...
bd6a774f2d487aa2832cb105f406daa162a5ac99
perkam/cracking_the_code_interview
/cracking_the_coding_interview/chapter_4.py
4,191
3.875
4
from typing import List, Tuple from cracking_the_coding_interview.Graph import Node from cracking_the_coding_interview.linked_list import LinkedList from cracking_the_coding_interview.Tree import BinaryTree, TreeNode def search_path(source: Node, target: Node): source_queue = [] target_queue = [] source....
193c30b8345cac84a555389ae84a3cd84b891148
jombooth/jodb
/jo_db.py
16,430
4.03125
4
""" Auxiliary functions """ def identity_map(n): """ Return a dictionary initialized to be the identity mapping, defined on all integers 0 <= i < n """ return {i:i for i in range(0,n)} def inv_map(map): """ Return the inverse of a 1:1 correspondence. DO NOT INVERT A DICTIONARY THAT IS ...
d7a9fedb9697c35d08b148429e95949fb926eaa0
hidekin/mangareader
/mangareader/tree/node.py
1,517
3.765625
4
""" Author: Hasen "hasenj" il Judy License: GPL v2 The Directory tree has two kinds of nodes: files and directories. When walking the tree, we are usually more interested in files than directories: we're only interested in directories because they (potentially) contain files. File nodes are s...
37d15fa2c4903de8571c5e65b8cef0f845f6ee7b
GregNetolsOpex/FunPuzzles
/Factorials/Factorials.py
693
3.9375
4
def factorial(a, b): if a > b: return a * factorial(a-b, b) else: return a def binary_search(low, high, b, target, function): y_low = function(low, b) mid = (high+low)/2 y_mid = function(mid, b) y_high = function(high, b) if abs(y_mid - target) < (10**-12): return ...
b92295a49a100815b606abe62fb31d77c9c51b31
zjzoloo/my-hackerrank-solutions
/Python/Strings/find_a_string.py
340
4.03125
4
def count_substring(string, sub_string): ans = 0 for i in range(0,len(string)): if (string[i:i+len(sub_string)] == sub_string): ans += 1 return ans if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_strin...
05ef61697206a6f220476dc1634c3f50a0e1df57
edsu/inst126
/modules/04/examples/dollar.py
271
4
4
# jaylin hours = float(input("Enter hours worked: ")) rate = float(input("Enter hourly rate: ")) if (rate >= 15): pay=(hours* rate) print("Pay: $", pay) else: print("I'm sorry " + str(rate) + " is lower than the minimum wage!")
f43aa3c250af631ca2e15190b65841b1a854ca37
edsu/inst126
/modules/08/exercise.py
334
3.59375
4
# read mail file and average the X-DSPAM-Confidence filename = input("Enter the file name: ") fh = open(filename) spam_values = [] for line in fh: if line.startswith('X-DSPAM-Confidence:'): parts = line.split(':') num = float(parts[1]) spam_values.append(num) print(sum(spam_values) / len...
9ec847c3efbf844a32b74341587bf34558bbf9b5
edsu/inst126
/modules/04/examples/nested.py
400
4.125
4
# Edward Hours_Worked = float (input ('Enter hours worked: ')) if Hours_Worked == 0: print ("Go to work!") elif Hours_Worked > 6000: print ("take a break!") else: Hourly_Rate = float (input ('Enter hourly rate: ')) if Hourly_Rate < 15: print ("I'm sorry",Hourly_Rate, "is lower than th...
75424a46fa848ccb8b99f4a525192cb5f1dbfbb1
PedroBiel/Mein_Kram
/The_Platters/datos/pandasdfxlsx.py
1,513
3.859375
4
# -*- coding: utf-8 -*- """ Transfiere datos de pandas DataFrame a Excel Created on Fri Dec 20 11:47:08 2019 __author__ = Pedro Biel __version__ = 0.0 __email__ = pbiel@taimweser.com """ import pandas as pd class PandasDFXLSX: """Transfiere los datos a una hoja de cálculo Excel.""" def ...
322933110023eee65a646314a1a68ad442d6e338
PedroBiel/Mein_Kram
/The_Platters/pruebas/SQLite/abresqulites/datos/os.py
1,437
3.546875
4
# -*- coding: utf-8 -*- """ DESCRIPCIÓN Created on Tue Nov 26 09:08:27 2019 __author__ = Pedro Biel __version__ = 0.0 __email__ = pbiel@taimweser.com """ import os class Os: def __init__(self, pfad, extension=''): self.pfad = pfad self.extension = extension def list_...
a9b4cc8b15d347462e2c5793b3317c49ad597f6e
amit-lab/python-projects
/snake-water-gun.py
1,444
3.890625
4
import random str_ch = ("s", "w", "g") print("#"*5, " Welcome to Snake Water Gun Game ", "#"*5) print("Game discription :: ") print("1. You will got 10 chances") print("2. You will have to enter : \n\ts for Snake\n\tw for Water\n\tg for Gun") print("\nSo let's begin the game\n") count = 0 syscount = 10 i=0 while i<...
957e816893ba60e401ebb60297ade5153ccfcc94
Codeless10010/Sort
/Heap_Sort/heap_sort.py
910
4.0625
4
# Name: Intro Sort # Original Author: J. W. J. Williams # Time Comlexity: # Best Case:O(n) # Average Case: O(nlogn) # Worst Case: O(nlogn) # Space Complexity: O(n) # Logic: Create a max heap (tree with root as the largest element). Then swap the root with last element and consider it sorted. Repeat these steps un...
5be6d5653236b17a825f8dd6cc5a70822953d015
mariacamila0712/Taller_exercism_python
/word-count/word_count.py
481
4.3125
4
import string import re def count_words(sentence): """Counts all the words in a string and returns a dictionary in the format {word: count, word: count}""" # Split on spaces, _, \n, \t and anything in string.punction words = re.split(r"[ _\n\t" + string.punctuation + "]+", sentence.lower()) c...
2fb07480ab54944631ca02a502043d7d7d9fe98e
mariacamila0712/Taller_exercism_python
/palindrome-products/palindrome_products.py
663
3.828125
4
def largest(min_factor, max_factor): return find_palindrome(min_factor, max_factor, (max_factor**2, (min_factor**2)-1, -1)) def smallest(min_factor, max_factor): return find_palindrome(min_factor, max_factor, [min_factor**2, max_factor**2+1]) def find_palindrome(lower, upper, candidates): if upper < low...
7aed3bb665756eb9a05f398f829a135f2b4b17ae
alessandrovendrame/IIoT-anno2
/Python-Mungherli/CalcolaFattoriale/CalcolaFattoriali.py
1,647
3.625
4
##############################Programma svolto da################################ #####Vendrame Alessandro, Collarini Marco, Maraspin Lorenzo, Apostu Gabriel###### ###Dopo una ricerca abbiamo deciso di utilizzare l'algoritmo di Trial Division### ##########################################################################...
19618bfed573e066dd797294262b4a7e34acaf3e
Xgz20/test
/datastructure/树/小根堆.py
3,727
3.859375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Xgz @Date: 2020/3/24 """ class BinHeap: """二叉堆(此处构造小根堆)""" def __init__(self): self.heap_list = [0] self.current_size = 0 def insert(self, ele): """ 往小根堆中插入一个数据项ele :param ele: 待插入数据项 ...
8dbeb51955365b09ea9c218fec89c1afdfd96243
Xgz20/test
/datastructure/排序/shellsort.py
1,073
4.03125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- def group_sort(alist, start_positon, gap): """ 对每个分组排序 :param alist: :param start_positon: :param gap: :return: """ for i in range(start_positon + gap, len(alist), gap): current_value = alist[i] position = i ...
4e19884829c890d7dcc68ac42d96bd8df1fec4bb
ArshdeepSingh22101988/Fizzbuzz1
/Task2.py
1,071
4.0625
4
os.dictdir(path="target directory") def get_dict_of_files(target): #creates a dictionary of folders and files dictoffiles=os.dictdir(targetdirectory) totalfiles= dict() #iterate through all the entries for entry in dictoffiles: #a full path is created full path= os.path.join(target diectory,entry) if os.pa...
e9563452c698f850fd0cf89d5d7bd6fb3dcebb1a
aishanisingh/cpsols
/codeforces/translation.py
464
3.703125
4
#https://codeforces.com/problemset/problem/41/A #TODO: check array from the back to reduce memory straight = input() backwards = input() straightarr = [] backwardsarr = [] straightarr[:0] = straight backwardsarr[:0] = backwards straightarr.reverse() straightlen = len(straightarr) backwardslen = len(backwardsarr) for...
305846d1df23eb68113e2b75fd1df5a019fd0f38
taehoon95/PandasStudy
/판다스자료구조 데이터프레임/change_df_idx_col.py
657
3.5625
4
from list_to_dataframe import df df.index = ['학생','학생2'] df.columns = ['연령','남녀','소속'] print('행 인덱스, 열 이름 변경하기', df, df.index, df.columns, sep='\n', end='\n\n') df.rename(columns={'연령':'나이', '남녀':'성별', '소속':'학교'}, inplace=True) print('열 이름 중, 연령을 나이로, 남녀를 성별로, 소속을 학교로 바꾸기') print( df, df.index, df.columns, sep='\n',...
15c298c3175f95cbeeea86ffdec4ff854c86ac43
amherst97/python
/my-calculate-pi/permutation.py
1,007
3.828125
4
## calculate how many unique 4-digit numbers, using each following number only once ## 0 1 2 3 4 ## Expected counts: 4 x 4 x 3 X 2 from collections import Counter def contain_others(array): if '5' in array: return True if '6' in array: return True if '7' in array: return True i...
c58532b34311af826e2a725c5e64dac4f36e0955
dm-stulov/e-olimp
/Спичечная_модель.py
683
4.09375
4
'''Профессор Самоделкин решил изготовить объемную модель кубиков из спичек, используя спички для рёбер кубиков. Длина ребра каждого кубика равна одной спичке. Для построения модели трех кубиков он использовал 28 спичек. Какое наименьшее количество спичек нужно Самоделкину для построения модели из n кубиков? Все числ...
0ccfc9d5ce9ffdfc0fc2192d119b9a986060f609
akshitone/Data-Science-in-Python
/pandas/04.py
1,541
3.546875
4
import pandas as pd import numpy as np from numpy.random import randn numbers_2D = randn(5, 4) X_labels = ['A', 'B', 'C', 'D', 'E'] Y_labels = ['W', 'X', 'Y', 'Z'] data_frame = pd.DataFrame(numbers_2D, X_labels, Y_labels) print("Data frame".center(50, '-')) print(data_frame) print("Boolean data frame".center(50, '-'...
78c6faca1c435c8f3817d95a527c53dd4c585716
akshitone/Data-Science-in-Python
/pandas/03.py
1,376
3.703125
4
import numpy as np import pandas as pd from numpy.random import randint, randn numbers_2D = randn(5, 4) # numbers_2D = randint(1, 100, 20).reshape(5, 4) X_labels = ['A', 'B', 'C', 'D', 'E'] Y_labels = ['W', 'X', 'Y', 'Z'] data_frame = pd.DataFrame(numbers_2D, X_labels, Y_labels) print(data_frame) # Display column d...
e8d0ce5345d5bc281b8562e31e6e8ba01e2ce76c
ChongzhengChen/Reinforcement-Learning
/Assignments/Assignment3 Monte Carlo Agent/programming1.py
1,510
3.703125
4
import numpy as np import matplotlib.pyplot as plt #probility of Headup pHead = 0.55 delta = 0 theta = 0.00000001 stateValue = np.zeros(101) #set the optimal policy Policy = np.zeros(101) Reward = np.zeros(101) #the winning state which means the reward is 1 Reward[100] = 1.0 sweep = 0 forever = True ##Value iteratio...
021d54c04c4894d537682f7892160e5e2700cdd0
hypatia733/ch8
/rainfall.py
682
3.953125
4
import math rainfalls = [] months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def get_rainfall(): while len(rainfalls) < 11: rain = int(input('Enter rainfall:')) rainfalls.append(rain) prin...
eaef55a91425cc667b115d27cca2eeff98cdf779
ashraf-kabir/CSE422-Artificial-Intelligence-Lab-Codes
/CSE422-Lab01-Basic-Python/task05.py
661
3.96875
4
# -*- coding: utf-8 -*- """ Created on Thu May 16 21:12:28 2019 @author: ASUS """ #5. A calendar year divisible by four is a leap year, with the exception of the years ending in 00 (that is, those divisible by 100) and not divisible by 400. For instance the years 1600 and 2000 are leap years, but 1700, 1800, and 1900...
38e696a3f7fdfcb48cdc8580d62dd4f3ce424bad
parkerjgit/algorithms
/python/bit_manipulation/insert_m_into_n.py
1,009
3.875
4
""" question: You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits betwe...
96bfb738e85b30fdf7569d2870c33a8ab105f750
parkerjgit/algorithms
/python/linked_lists/linked_list.py
1,047
4.0625
4
""" A simple linked list. """ class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def push(self, item): new_node = Node(item) new_node.next = self.head self.head = new_node @...
49cff67f275b30d3734cdaeed6c14328d4a2d1fb
parkerjgit/algorithms
/python/bit_manipulation/longest_sequence_after_bit_flip.py
1,566
3.9375
4
""" question: You have an integer and you can flip exactly one bit from a O to a 1. Write code to find the length of the longest sequence of 1 s you could create. source: McDowell, Gayle Laakmann., Cracking the Coding Interview: 189 Programming Questions and Solutions 6th Edition (2015) 194. """ def get_binary_sequen...
2f49dea03adea50439878f358038dbfa320dd319
parkerjgit/algorithms
/python/recursion_and_dynamic/navigate_grid.py
2,559
4.46875
4
""" question: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right....
a7d2a8d0301aa0603b33e5c9b20db8290f3b4393
parkerjgit/algorithms
/python/linked_lists/partition.py
1,915
3.96875
4
""" question: Write code to partition a linked list around a value x, such that al nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x. The partition element x can appear anywhere in the "right partiti...
533eef9995f9848f0025cb3ed81866d1d846a422
parkerjgit/algorithms
/python/arrays_and_strings/palindrome_permutation.py
2,507
4
4
""" question: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. source: McDowell, Gayle Laakmann.,...
e42257341ea92cd466d454c1295c052b4ef9975b
ramirovazq/algorithmexamples
/example_algorithms/count_triplets.py
1,674
3.921875
4
''' Sample Input 4 2 1 2 2 4 Sample Output 2 https://www.hackerrank.com/challenges/count-triplets-1/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps ''' # Complete the countTriplets function below. def counting_frequency(dict_frequency, x): if x ...
9fa3b3508ab736047e38799a0dbf9173e6cc7b2a
ramirovazq/algorithmexamples
/example_algorithms/binary_search.py
1,218
4.0625
4
def binary_search(lista, value): ''' lista, must be ordered value, is the number we are searching ''' found = False indice = -1 # means not founded low = 0 high = len(lista) - 1 while low <= high and not found: mid = (low + high) // 2 #print("low {} ... mid {} ... high {}".format(low, mid, high)) if...
423b7922a1fdea84d0288a359fc52339b2f9f37d
ramirovazq/algorithmexamples
/example_algorithms/sorting_bubble_sort.py
1,958
4
4
''' https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting ''' def swap(a, y, y_next): new_a = a.copy() value_y = a[y] value_y_next = a[y_next] new_a[y] = value_y_next new_a[y_next] = value_y retu...
90e785a5f956fc51729640a0bd9e0ecccac48df8
ramirovazq/algorithmexamples
/example_algorithms/pairs.py
324
3.640625
4
def pairs(k, arr): d = {} for y in arr: d[y] = y count = 0 for x in arr: number_to_find = x - k if number_to_find in d: count += 1 # now we start return count if __name__ == '__main__': counter = pairs(2, [1,5,3,4,2]) assert counter == 3, "check c...
d083d424d3da7c65d0e94acca82b6ac39b1aee43
ramirovazq/algorithmexamples
/example_algorithms/making_anagrams.py
1,603
4.09375
4
''' Sample Input cde abc Sample Output 4 https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings ''' def letters_frequency(word=""): ''' retun a dict, key letter and value, frequency appears in w...
63377371e619b81d094b8d505024539751239720
bpetov/Multidimensional-list
/Bombs.py
2,649
3.609375
4
# I. Make a matrix with input # II. Make the steps with a function # III. When bomb explode check every direction and every diagonal for if it is bomb, if it is <= 0, # IV. Make output current_r = int(input()) current_c = current_r def matrix_creator(r): matrix = [] for _ in range(r): row = lis...
21a8916a2275c0de2640e8be1504a7724dde9f8f
adrianflatner/ITGK
/7AdrianFlatner/øving7/Strenghåndtering.py
871
4.0625
4
def check_equal(str1, str2): for n in str1 and str2: if str1 == str2: return True else: return False str1 = "Hei" str2 = "Hei" str3 = "abba" ans = check_equal(str1, str2) print(ans) #[::-1] def reversed_word(str): new_string = "" index = len(...
40a50ca13ca7d6d57236c1a67229da3c32d08ddf
adrianflatner/ITGK
/5AdrianFlatner/øving 5/kollektivapp.py
800
3.65625
4
def sykkel_funksjon(a): if a == ("JA"): sykkelpris = 50 else: sykkelpris = 0 return sykkelpris def billettpris(): ans = str.upper("ja") while ans == str.upper("ja"): alder = int(input("Hva er din alder? ")) sykkel = str.upper(input("Har du sykkel? ")) ...
0837982acc59916f0b55061e0bb8647f0affa93d
Hrushabhs/My-Pycode
/palindrome.py
202
3.9375
4
n=int(input("Enetr number: ")) t=n rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 if(t==rev): print"The Given number is palidrome" else: print"The given number is not palidrome"
e714d5202cba07ab13a0c943d9f750667145b73d
Hrushabhs/My-Pycode
/table.py
203
3.984375
4
#/* n=int(input("Enter the number to print the tables for:")) #for i in range(1,11): # print(n,"x",i,"=",n*i) n=int(input("Enter the number")) for i in range(1,11): print (n ,"x", i, "=", n * i)
3c0b8d61c228e00a225182c5b1403231da6be09a
LeNam223/Try-for-fun
/ReadFile_Python3/Save&Play-listmusic.py
6,223
3.59375
4
import webbrowser class Video: def __init__(self, title, link): self.title = title self.link = link def open(self): webbrowser.open(self.link) class Playlist: def __init__(self, name, description, rating, videos): self.name = name self.description = description self.rating = rating self.videos = vid...
3c8c18be03f721a9ed8345ff72cf80ff5aa63754
s-touchstone/College
/Advanced Computer Languages - Python/output_example.py
822
3.90625
4
#Steven Touchstone #Dr. Vladimir Ufimtsev #Advanced Computer Language (Python) #Basic output styles and formats a=5 b=9 c=6 d=a+b+c e=7.5 f=2.5 g="output text" h="output continued" i="20" print(a,b,c) #print list of integers print(a+b+c) #integer math inside a print print(d) #integer math outside a print print(e,...
aec88279172b7a726e3a11eabfd0cf750d4a8fe7
s-touchstone/College
/Advanced Computer Languages - Python/elif.py
643
4.125
4
#Steven Touchstone #Dr. Vladimir Ufimptsev #Advanced Computer Language (Python) #if, elif, and else examples from math import * print('Please make a selection:\n1, 2, or c') sel=input() #Remember: The input is a string even if sel=="1": #with numbers entered print('You made the first selection') area=7 elif...
e368f491e2debdebdd72a346f1871dc7f881bcbb
s-touchstone/College
/Advanced Computer Languages - Python/Div.py
1,098
4.15625
4
#Steven Touchstone #Professor Vladimir Ufimtsev #CMPSC 3313 (Python) #Division algorithm no '//' or '%' allowed #Output: The quotient and remainder of the two entered numbers. a=int(input("Enter an integer->")) b=int(input("Enter a divisor->")) def func(a,b): r=a q=0 if a>=0: #Used python shell for...
ac4ef06f83f570ccdbb2981bb26645ecca3803c0
rulitka/basic
/2.py
660
3.609375
4
def odometer(N): long = len(N) if long >= 2: num = 0 sum_distance = 0 distance_all = 0 for index, number in enumerate(N): if index%2 == 0: speed = N[index] else: if num == 0: time = N[index] ...
3496824b74aa7f03a4a8eff837200a54936dd3f7
rulitka/basic
/22.py
1,066
3.546875
4
def create_dict(s): count = {} for elem in s: if elem in count: count[elem] += 1 else: count[elem] = 1 return count def SherlockValidString(s): number = 0 Flag = True count_dict = create_dict(s) new_values = [] for i in count_dict.values(): ...
e9c4dd62c985237c0c685769ce5911a1c1dcfefd
vivekchaubey/Python
/Algorithmic Toolbox/wk2/gcd.py
363
3.65625
4
# Uses python3 import sys def gcd_naive(aa, bb): if aa == 0: return bb elif bb == 0: return aa elif aa == bb: return aa elif aa > bb: return gcd_naive(aa % bb, bb) elif bb > aa: return gcd_naive(aa, bb % aa) if __name__ == "__main__": a, b = map(int, i...
5b1f9832846d80bf8525b5242ec4d93f1bc0d074
queid7/hma
/modules/ys_motion/test1.py
344
3.609375
4
def ssn_parser(ssn): front, back = ssn.split('-') sex = back[0] if sex == '1' or sex == '2': year = '19' + front[:2] else: year = '20' + front[:2] if (int(sex) % 2) == 0: sex = '여성' else: sex = '남성' month = front[2:4] day = front[4:6] return year, ...
3c5c49429e606eafccf77d4df5e04ffacead6275
hwaseonchoi/adventofcode2020
/03_TobogganTrajectory/03.py
758
3.765625
4
#!/usr/bin/env python3 ## Day 3: Toboggan Trajectory def toboggan(right = 3, down =1): # Initialize variables matrix = [] trees = 0 i = 0 x = y = 0 # Create the matrix with open('input.txt') as file: for line in file: matrix.append([]) for c in line.strip()...
0971873f07495797ad1733cd5c8e2244cc9ec9fb
luckywind/magic_box
/data_manning/scikit_learn/overview/iris_classify.py
2,406
4.125
4
#encoding=utf-8 ''' 参考:http://www.jianshu.com/p/e2c7d692fe2c 数据的可视化(visualization) scikit-learn自带有一些经典的数据集,比如用于分类的iris和digits数据集,还有用于回归分析的boston house prices数据集。 可以通过下面的方式载入数据: ''' from sklearn import datasets iris = datasets.load_iris() digits = datasets.load_digits() ''' 该数据集是一种字典结构,数据存储在.data成员中,输出标签存储在.target成员中。 ...
b024cad14805d3e416497bab294f431ef1b605e5
luckywind/magic_box
/basic_class/mytest.py
2,303
3.9375
4
#coding=utf-8 # 1. 已知字符串 a = "aAsmr3idd4bgs7Dlsf9eAF",要求如下 a = "aAsmr3idd4bgs7Dlsf9eAF" # 1.1 请将a字符串的大写改为小写,小写改为大写。 print a.swapcase() # 1.2 请将a字符串的数字取出,并输出成一个新的字符串。 num_in_a = [x for x in a if x.isdigit()] print ''.join(num_in_a) # 1.3 请统计a字符串出现的每个字母的出现次数(忽略大小写,a与A是同一个字母),并输出成一个字典。 例 {'a':4,'b':2} a_lower = a.lower() ...
b703e400ea77850bcbaa6ca54d229fdc46fa2dd9
evgeniy879/python.lesson
/lesson1/task2.py
158
3.8125
4
time = int(input()) time = time % (24 * 3600) hour = time // 3600 min = (time % 3600) // 60 sec = (time % 3600) % 60 print(f'{hour:02d}:{min:02d}:{sec:02d}')
d03bd2cd8df613f93129d464cb7c6019d594b86c
evgeniy879/python.lesson
/lesson1/task5.py
633
4.0625
4
cost = int(input('введите сумму издержек ')) revenues = int(input('введите сумму выручки ')) profit = revenues - cost if profit > 0: print(f'прибыль фирмы составила {profit}') profitability = profit / revenues count_workers = int(input('введите число сотрудников ')) profit_per_count_workers = profit / c...
b2394917806944d72251a4b7716814a8feb3fb01
evgeniy879/python.lesson
/lesson1/task3.py
82
3.640625
4
n = input() nn = n * 2 nnn = n * 3 suma = int(n) + int(nn) + int(nnn) print(suma)
3352f46377b048a6189d2601c855b6ce18f7c4d3
duguzanzan/LearnToPython3
/Lesson16.py
1,902
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2019-05-29 14:24 # @Author : zan # @File : Lesson16.py # @Title : 常用的内建模块 'itertools' '提供了非常有用的用于操作迭代对象的函数' import itertools ''' natuals = itertools.count(1) for n in natuals: print(n)#打印自然数序列 ''' ''' cs = itertools.cycle('ABC') for c in cs: ...
1edeb3974846d3a8397a9792973bcb25c89f2c2d
duguzanzan/LearnToPython3
/Lesson8.py
5,096
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'DeRozan' '错误、调试和测试' 'Bug fix' '高级语言通用的try...except...finally' try: print('trying...') r = 10 / 0 print('result:', r) except ZeroDivisionError as e: print('except:', e) finally: print('finally...') print('END') 'Python的错误其实也是class,所有的错...
cbc306236459e449ba94af1aa1ed600af2d65dfc
duguzanzan/LearnToPython3
/Lesson3.py
7,105
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #高级特性 #切片 L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] #取list的前三个元素 print(L[:3]) #这里的3是索引3,但是不包含索引3的元素 #从索引1开始取到索引3的元素 print(L[1:3]) #取倒数两个元素 print(L[-2:]) L = list(range(100)) #前10个 print(L[:10]) #后10个 print(L[-10:]) #前10个数,每两个取一个 print(L[:10:2]) #所有的数,每5个取一个 print...
e62d0fafbc24cf9c1a2112bdcb8f8592c1f621da
sirius-william/Data_structure_and_algorithm_python
/linkList/SingleCircleLinkedList.py
3,613
3.609375
4
""" 单向环形链表 """ # 节点类 class Member(object): def __init__(self, no, val, Next, start: bool = False): self.no = no self.val = val if start: # 如果定义为起始节点,则连接到自己 self.next: Member = self else: self.next: Member = Next def __str__(self): ne...
dd92d56a4ac7f2c3a3cf8baa1fb62bb1faf9f639
sirius-william/Data_structure_and_algorithm_python
/tree/二叉搜索树.py
7,035
3.703125
4
""" 二叉搜索树满足: 左子树小于根,右子树大于根 包括:查询、插入、删除 效率:o(logn) 最坏情况:每个节点的子节点都最多只有一个(变成了链表),从树形结构退化为线性结构。o(n) 解决: 随机化插入 AVL树 """ from tree.二叉树 import * class SelectTree(BinaryTree): def __init__(self, rootNode, baseList: list = None): self.__sort_list = [] super().__init__(rootNode) if baseL...
de8b721d4a46463d5b5233dade683a299414af68
sirius-william/Data_structure_and_algorithm_python
/sort/其他/桶排序.py
920
3.796875
4
""" 桶排序 对计数排序的改进 将列表按照区间(分段函数)分为很多部分,建立很多小列表,分别计数排序 效率:取决于数据的分布 """ def count_sort(li, minNum, maxNum): count = {} for i in range(minNum, maxNum + 1): count[i] = 0 for i in li: count[i] += 1 li.clear() print(count) for i, j in count.items(): li += [i] * j def bucket_...
13721c6141ea34972fe3d3b3b55f43c871be737b
5TDg9/trader
/scraper.py
1,887
3.59375
4
# This is a template for a Python scraper on morph.io (https://morph.io) # including some code snippets below that you should find helpful # import scraperwiki # import lxml.html # # # Read in a page # html = scraperwiki.scrape("http://foo.com") # # # Find something on the page using css selectors # root = lxml.html.f...
826cae261f595645f2b5ef3a730a1fdc52267506
ricwtk/result-ai-a1-202104
/players/Group23Player2/player.py
5,654
3.6875
4
import itertools class Player: name = "Uninformed Agent: Breadth First Search" group = "1M" members = [ ["Phyllis Chong Yee Teng", "18011551"], ["Khirrtini Muraleetharan", "18032052"], ["Khairul Akmal bin Khairulanwar", "18045872"] ] informed = False def __init__(self, ...
b245c2c949a68429414e7039a842ba4b320c9898
ricwtk/result-ai-a1-202104
/players/Group27Player1/player.py
5,094
3.53125
4
# - INFORMED AGENT # - Used Best First Search import heapq as heap # NODE class # for using inside the MIN-HEAP class Node: def __init__(self, head, dir, info, distance): self.head = head self.dir = dir self.info = info self.distance = distance # - class comparator # - smaller distance will come earlier...
ef570c3eccd13c46ca02bdcf416649da8fd7b578
ricwtk/result-ai-a1-202104
/players/Group26Player2/player.py
6,592
4
4
import itertools class Player(): name = "Breadth-First Search player" group = "Fancy" members = [ ["Tan Wyyee", "17013673"], ["Kok Ming Ho", "19024272"], ["Sin Jun", "18087619"], ["Leong Yen Loong", "18076083"] ] informed = False def __init__(self, setup): # setup = { # maze_size...
b6b7047bfac4f4a90700a5330798c82d6ee0a9ad
dylan-hanna/ICS3U-Unit-3-08-Python
/leap_year.py
770
4.0625
4
#!/usr/bin/env python3 # Created by: Dylan Hanna # Created on: October 2019 # This tells you if you can date the ladies grandchild def main(): year_as_string = input("Enter a year: ") print("") # process & output try: year = int(year_as_string) if year % 4 == 0 and year % 100 != 0: ...
3fb7e2a07102d7f0d8fe9f54af9a68ac848e69fe
ErofeevAA/taskPython
/5/D.py
861
3.671875
4
class Polynomial: def __init__(self, coefficients: list): self._coefficients = coefficients @property def coefficients(self): return self._coefficients def __call__(self, x): res = 0 for i in range(len(self._coefficients)): res += (self._coefficients[i] * x...
8ff54ba39a8921c461dc90e9fd0bfb13c9a212f1
ErofeevAA/taskPython
/4/A.py
325
3.546875
4
def get_num_from_console(n: int): for j in range(n): tmp = input().split() yield int(tmp[1]) > 1 all_sum = int(input()) flag_list = [] for i in range(all_sum): group_sum = int(input()) flag_list.append(any(list(get_num_from_console(group_sum)))) print('ДА' if all(flag_list) else 'НЕТ')
a4c21d614d831792c037539e951ad49576c3d1b8
chrisdivitto/the-generatinator
/gen.py
4,254
3.875
4
#!/usr/bin/python3 # Hello! Welcome to this program! # If you are a seasoned programmer that has somehow found your way to this project, # it'd probably take you 2 seconds to realize I have no idea what I am doing. # This is correct. My code is awful, but as of now, it works. # This tool is made specifically for my us...
40ec30be5ba8d348829168e0695a26ab520c6790
linhaidong/linux_program
/container_ssl/python_test/pytool-master/date_time/date_loop.py
1,010
3.921875
4
# coding=utf-8 """ desc.. :copyright: (c) 2015 by fangpeng. :license: MIT, see LICENSE for more details. """ __date__ = '1/8/16' from datetime import datetime, date, timedelta import calendar def get_month_range(start_date=None): if start_date is None: # 巧妙之处:计算出一个对应月份第一天的日期 # 使用 date 或 d...
50fba38196e2dc46eaf4bd91b1b8989a8a314263
linhaidong/linux_program
/container_ssl/python_test/pytool-master/multithread/V2-queue-implement.py
1,685
3.765625
4
# coding=utf-8 """ 在V1-condition_to_implement_queue.py中通过Condition实现Queue. 接下来通过Queue实现上述代码 Queue封装了Condition的行为,如wait(),notify(),acquire()。 :copyright: (c) 2015 by fangpeng. :license: MIT, see LICENSE for more details. """ __date__ = '12/2/15' from threading import Thread import time import random from Queue...
fb05b3747192a9401b4c2eef768efd86774989e7
linhaidong/linux_program
/container_ssl/python_test/pytool-master/strings-and-text/splitting-strings.py
588
3.90625
4
# coding=utf-8 """ 使用多个界定符分割字符串 string.split Vs re.split :copyright: (c) 2015 by fangpeng. :license: MIT, see LICENSE for more details. """ __date__ = '1/5/16' line = 'asdf fjdk; afed, fjek,asdf, foo' def string_split(): return line.split(',') # string.split()只能分隔简单的字符串,不能有多个分隔符 def re_split(): ...
49fffd66e3da01408028c28639ab39115551bd06
linhaidong/linux_program
/container_ssl/python_test/pytool-master/datastruct/mapping-keys-to-multiple-values-in-a-dictionary.py
1,009
3.671875
4
# coding=utf-8 """ 一个键对应多个值的字典的三种实现方法 :copyright: (c) 2015 by fangpeng. :license: MIT, see LICENSE for more details. """ __date__ = '1/4/16' # method 1:一个键映射多个值,将这多个值放到另外的容器中,比如列表或者集合里面 dic1 = { 'key_1': [1, 3, 4, 5], # 保持元素的插入顺序就应该使用列表 'key_2': {1, 3, 5} # 去掉重复元素就使用集合 } # method 2:col...
8a4416973172dfb9a31165f047b997d76f38430f
JaeguKim/PSAssistant
/test/Codeforces/wordCapitalization.py
108
3.8125
4
#3m word = [ch for ch in input()] if word[0].islower(): word[0] = word[0].upper() print(''.join(word))
bbcadcad8263e412c748f5d3010ee9e8dda56ed3
JaeguKim/PSAssistant
/test/Codeforces/VasilyTheBearAndTriangle.py
425
3.59375
4
#25m x,y = [int(num) for num in input().split(' ')] yCoord = (abs(x)+abs(y)) * int(y/abs(y)) coord1 = (0,yCoord) xCoord = (abs(x)+abs(y)) * int(x/abs(x)) coord2 = (xCoord,0) if coord1[0] < coord2[0]: print(coord1[0],end=' ') print(coord1[1],end=' ') print(coord2[0],end=' ') print(coord2[1]) else: pr...
0fef8751eb3ae7127147f96f17a9c4fc995e326a
JaeguKim/PSAssistant
/test/Codeforces/A2OJ Ladder 13/Dubstep.py
109
3.546875
4
#5min str=input() ary=str.split('WUB') for s in ary: if s != 'WUB' and len(s)>0: print(s,end=' ')
e4ad905fb0d3df349d0b941a9c87afcf2dc78fa3
JaeguKim/PSAssistant
/test/Codeforces/A2OJ Ladder 13/luckySumOfDigits.py
547
3.625
4
#알고리즘은 거의 맞았으나, 사소한 함수들을 최적화해야 accept되는 문제 import sys def printMin(a,b): for i in range(b): print('4',end='') for i in range(a): print('7',end='') n = int(input()) a = 0 find = False aCnt = -1 bCnt = -1 m=sys.maxsize prev = sys.maxsize while 7*a <= n: if (n-7*a)%4 == 0: b = int((n-7...
496d7285ff6cea97f3e2167134ef338321e3e850
JaeguKim/PSAssistant
/test/Codeforces/PetyaAndStrings.py
198
3.515625
4
#7min 26s str1 = input().lower() str2 = input().lower() list = [str1,str2] list.sort() if str1 == str2: print('0') else: if list[0] == str1: print('-1') else: print('1')
689745370a06a5a61e37cf8888bd33ad09720263
JaeguKim/PSAssistant
/test/KAKAO/2020KAKAO_REQRUIT/parenthesis.py
803
3.5625
4
def isBalanced(str): num = 0 for idx,value in enumerate(str): if value == '(': num+=1 elif value == ')': num-=1 if num == 0: return idx def isRight(str): stack = [] for ch in str: if len(stack)>0 and ch == ')' and stack[-1] == '(': ...
da0b224e655febd46eaa8acdb88054e4764f1f98
xiaooodd/CS362-in-class-w7
/wordcount.py
257
3.71875
4
def w_count(string): str1 = str.strip(string) n = 1 i = 0 while i < len(str1): while str1[i] == ' ': n += 1 i += 1 break while str1[i] == ' ': i += 1 i += 1 return n
78fb146369b25a0890904e8722c4f697271e01d9
anagrzesiak/metody-numeryczne
/metody rozniczkowania.py
1,649
3.828125
4
def f(x, y): return x * x + y def print_f(): output = "y'(x) = x^2 + y" return output def euler(x, y, end, step): stop = (end - x) / step x_temp = x y_temp = y for i in range(int(stop + 1)): y_temp = y_temp + step * f(x_temp, y_temp) x_temp = x_temp + step ...
a48b4594271ec6843bea58d4f1d94516bccd5e8c
SagarKumar1310/array
/array .py
2,074
4.40625
4
#!/usr/bin/env python # coding: utf-8 # # Array # # 1.array is an object that provide a mechaanism for storing several data in one identifier.array is used to store group of data in same data type # 2.In python size of array is not fixed array can increase or decrease their size dynamically # 3.array is not same as...
71e5b6399bcd6cd8493007f296ee250b7f70e6e5
CDSUDHAKAR/Test-Repository
/EvenOddtest.py
145
4.21875
4
Number = int(input('Enter the number: \n')) print(Number) if (Number % 2) == 0: print('Its Even number') else: print('Its Odd Number')
1304061d479d82945393610044e277894f3aa2a7
hamburgcodingschool/L2C-Python-1804
/Lesson 1/05_decisions.py
330
4.03125
4
print("What is the first number?") value1 = input() number1 = int(value1) print("What is the second number?") number2 = int(input()) if number1 == number2: print("THEY ARE THE SAME!!!!") else: if number1 > number2: print("The biggest is " + str(number1)) else: print("The biggest is " + str(...
081ce5d392c5fe4d2220171e3eb287e82a208081
hamburgcodingschool/L2C-Python-1804
/Homework_Solutions/5_basic.py
350
4.1875
4
year = 2104 #ask the user for input instead isLeap = False if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: isLeap = True else: isLeap = False else: isLeap = True else: isLeap = False if isLeap: print("YAY it's a leap year!!!") else: print(...
73a57fedbc73cd8bedad226859d795960331755b
hamburgcodingschool/L2C-Python-1804
/Lesson 5/05_prime_fun.py
497
3.796875
4
def isPrime(number): for test in range(2, number): if number % test == 0: return False return True # prime numbers between 1 and 100 # # for i in range(1, 101): # if isPrime(i): # print(i) # first 100 prime numbers # primesFound = 0 numberToCheck = 1 while primesFound < 100...
171d761f0fa247973ce40671a421147a96121696
Demons-wx/leetcode_py
/leetcode/q7_reverse_integer.py
1,052
3.890625
4
# -*- coding: utf-8 -*- __author__ = "wangxuan" # Reverse digits of an integer # # Example1: x = 123 return 321 # Example2: x = -123 return -321 # Example3: x = 1230 return 321 # # 注意整数越界 class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x...
ad19a21a8ff994895792da421390888b34e81c29
Demons-wx/leetcode_py
/leetcode/q14_longest_common_prefix.py
1,140
3.640625
4
# -*- coding: utf-8 -*- __author__ = "wangxuan" # find the longest common prefix string amongst an array of strings # 最长公共前缀 # # Time: O(n*k) k是公共前缀的长度 class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: ...
e12dacbc1a5e6abd48c8e65838265542f27809ec
sandipan898/interact-with-os-using-python
/week-2-assignment-2/pr-4.py
610
4.21875
4
""" 5. Question 5 The parent_directory function returns the name of the directory that's located just above the current working directory. Remember that '..' is a relative path alias that means "go up to the parent directory". Fill in the gaps to complete this function """ import os def parent_directory(): # Cre...