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
b4496e825119631d6983be6f93a06365fafe52ad
ferranespigares/adventofcode2017
/day3/day3p1.py
1,591
3.578125
4
import math def Step(): global posX global posY global incX global incY posX+=incX posY+=incY def CanTurnLeft(): global Grid global posX global posY global Dir if Dir=="Right": if Grid[posX][posY-1]!=0: return False else: return True ...
bc6fe0fb3c7810780858f188775751f70263845c
local-motion/playground-importer
/src/localmotion/domain/address.py
348
3.71875
4
class Address: def __init__(self, street: str, number: int, zipcode: str, city: str) -> None: self.street = street self.number = number self.zipcode = zipcode self.city = city def to_readable_address(self): return "{} {}, {}, {}, Nederland".format(self.street, self.numbe...
0c9a8321a58531e04e5018abb5b7a9d3753c8276
YaohuiZeng/Leetcode
/217_contain_duplicates.py
661
3.9375
4
""" Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. """ # Space O(n); time O(n) # if O(1) space required, can first do heap-sort, then compare adjacent e...
9b86db9b20f79d980c719c572bc9d64906e39a5d
YaohuiZeng/Leetcode
/475_heaters.py
2,835
4.0625
4
""" Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses. Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters. So, your input will b...
dc61558dcef21d8e7a28c11b0ddf357453abd0c2
YaohuiZeng/Leetcode
/311_sparse_matrix_multiplication.py
2,275
3.796875
4
""" Given two sparse matrices A and B, return the result of AB. You may assume that A's column number is equal to B's row number. Example: A = [ [ 1, 0, 0], [-1, 0, 3] ] B = [ [ 7, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ] ] | 1 0 0 | | 7 0 0 | | 7 0 0 | AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | ...
86a9f9654568017337b9f306ebd4a8eea326b535
YaohuiZeng/Leetcode
/152_maximum_product_subarray.py
1,446
4.28125
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. """ """ Q: (1) could have 0, and negative (2) input contains at least one number (3) all in...
d5ac5a0d89985b6525988e21ed9fe17a44fb4caa
YaohuiZeng/Leetcode
/280_wiggly_sort.py
1,227
4.21875
4
""" Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. """ """ 1. use python in-place sort() 2. one pass: compare current and next, if not the right order, swap. This wo...
d01f8acd33d21474046882619f2346d1531f3d0a
YaohuiZeng/Leetcode
/441_arrange_coins.py
1,420
4.0625
4
""" You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: n = 5 The coins can for...
f1d5b2e77b6b6dcef16cbba4ea4226c0b201d930
lionel-k/python-challenge
/level3.py
192
3.8125
4
#!/usr/bin/env python import re with open("mess-level3.txt","r") as f: mess = f.read() regex = "[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]" matches = re.findall(regex,mess) print "".join(matches)
1dfce5a987d040ca4c116e25cfcca7ef6039cbc4
trevorlangston/aoc2018
/1/b-sol.py
911
3.765625
4
class Node: def __init__(self, data, next): self.data = data self.next = next class CircularLinkedList: def __init__(self): self.head = None self.tail = None def add(self, data): node = Node(data, self.head) if self.head is None: self.head = nod...
6aea488ab45998317d8a8d5e180d539e5721873e
ariModlin/IdTech-Summer
/MAC.py
518
4.125
4
# finds the MAC of a message using two different keys and a prime number message = "blah blahs" key1 = 15 key2 = 20 prime_num = 19 def find_mac(): message_num = 0 for i in range(len(message)): # takes each letter of the message and finds its ASCII counterpart num = ord(message[i]) # adds each ASCII nu...
6fe51f731f777d02022852d1428ce069f0594cf4
ariModlin/IdTech-Summer
/one time pad.py
1,867
4.21875
4
alphabet = "abcdefghijklmnopqrstuvwxyz" message = input("input message you want to encrypt: ") key = input("input key you want to encrypt the message with: ") message_array = [] key_array = [] encrypted_numbers = [] decrypted_message = "" def convert_message(): for i in range(len(message)): # takes...
ada99ffe37296e78bbaa7d804092a495be47c1ba
dineshj20/pythonBasicCode
/palindrome.py
890
4.25
4
#this program is about Palindrome #Palindrom is something who have the same result if reversed for e.g. " MOM " #how do we know whether the given string or number is palindrome number = 0 reverse = 0 temp = 0 number = int(input("Please Enter the number to Check whether it is a palidrome : ")) print(number) temp = numbe...
06660bc2ab53b5196e3ab8d5eb282a07f09dd510
juniorjrml/CursoDePythonComDalessandro
/aula06.py
5,162
3.953125
4
import json import csv exercicio = ["6_1", "6_2", "6_3", "6_4"] # _______________inicio do exercicio 1 _______________ # definindo a solucao: def mulheres_idade_superior_a_x(base, x): with open(base, 'r') as arquivo_csv: leitor = csv.reader(arquivo_csv, delimiter=';') # primeira linha tem os t...
b09d264252fa25d5ec3ec90714beeac5ac1799d3
gowthamthaman6/quvi
/largest.py
326
3.921875
4
n1=int(input()) n2=int(input()) n3=int(input()) if(n1,n2,n3 > 0): if(n1>n2 and n2>n3): print(n1) elif(n2>n1 and n2>n3): print(n2) else: print(n3) elif(n1,n2,n3<0): if(n1<n2 and n2<n3): print(n1) elif(n2<n1 and n2<n3): print(n2) else: print(n3)...
6c5ee3e9cb85a24940a9238981b7f6fbf9ec1696
MichealPro/sudoku
/create_sudoku.py
2,158
4.375
4
import random import itertools from copy import deepcopy # This function is used to make a board def make_board(m=3): numbers = list(range(1, m ** 2 + 1)) board = None while board is None: board = attempt_board(m, numbers) return board # This function is used to generate a full board def at...
30028435f715210577d399fba75cd3b51021136d
trimcao/principles-computing-rice
/week-3/tictactoe_online.py
4,315
3.75
4
""" Monte Carlo Tic-Tac-Toe Player Tri Minh Cao trimcao@gmail.com September 2015 """ import random import poc_ttt_gui import poc_ttt_provided as provided # Constants for Monte Carlo simulator # You may change the values of these constants as desired, but # do not change their names. NTRIALS = 1 # Number of ...
526984cfd6c01ee1a4160a0b95edc6c804703f3b
ThatGuy00000/LPTHW
/ex13.py
288
4.03125
4
from sys import argv script, first, second=argv cats= raw_input("How many cats do you have?") print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second #print "Your third variable is:", third print "So you have %s cats?" % cats
72d14b487cde24a313d025ab55249c461dba1e56
orez-/MazeAgents
/board/__init__.py
1,411
3.53125
4
import constants class Maze(object): def __init__(self, width, height): self.left = 0 self.top = 0 self.right = width self.bottom = height self.walls = {} @staticmethod def _translate_coords(x, y, direction): dir_map = { constants.UP: (x, y - 1)...
f605c356950e7e609d3e57c92169775cf4ed497a
sssvip/LeetCode
/python/num003.py
1,303
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-09-28 22:25:36 # @Author : David:admin@dxscx.com) # @Link : http://blog.dxscx.com # @Version : 1.0 """ Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the ...
09615ae4f2e7bb641f96fe2d4f35ff6ee3489d16
sssvip/LeetCode
/python/num027.py
1,325
4.0625
4
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: David @contact: tangwei@newrank.cn @file: num027.py @time: 2017/10/7 15:42 @description: Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must...
89db6d170e6eb265a1db962fead41646aaed6f9f
sssvip/LeetCode
/python/num581.py
1,606
4.21875
4
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: David @contact: tangwei@newrank.cn @file: num581.py @time: 2017/11/7 20:29 @description: Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be s...
81fd6c69f950118c4bf20f56093b6a588b02d2fa
sssvip/LeetCode
/python/num069.py
766
4.09375
4
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: David @contact: tangwei@newrank.cn @file: num069.py @time: 2017/10/9 15:00 @description: Implement int sqrt(int x). Compute and return the square root of x. """ class Solution(object): def mySqrt(self, x): """ :type x: ...
6900760be8e37a79c4b6873655f933368bbbab1b
sssvip/LeetCode
/python/num013.py
1,016
3.796875
4
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: David @contact: tangwei@newrank.cn @file: num013.py @time: 2017/10/6 16:57 @description: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. """ class Solution(object): def romanTo...
4bcdef1f0a719af7fe0cd118c74c11b844f1208b
aoadamson/codeReview
/withStatements.py
255
3.53125
4
import json dictionary = {"a": "1", "b": "2"} with open('example.json', 'w') as file: file.write(json.dumps(dictionary)) with open('example.json', 'r') as file: read_file = file.read() output_file = json.loads(read_file) print(output_file)
4ffb814e30b81b1d18889c2c57a8ec276b4b0d0c
junjongwook/programmers
/Skill Check/Level3/s12978.py
1,343
3.828125
4
# -*- coding: utf-8 -*- """ 배달 : https://programmers.co.kr/learn/courses/30/lessons/12978?language=python3 """ def solution(N, road, K): answer = 0 result = set() graph = dict() for v1, v2, d in road: graph.setdefault(v1, dict()) graph.setdefault(v2, dict()) if v1 in graph and ...
10372b8fa5d8a3f354467ceea1254c5d2e473a84
junjongwook/programmers
/Skill Check/Level4/s68938.py
1,978
3.546875
4
# -*- coding: utf-8 -*- """ 문자열의 아름다움 : https://programmers.co.kr/learn/courses/30/lessons/68938?language=python3 """ def solution(s): answer = 0 d = dict() N = len(s) stack = [(0, N-1)] # 0, N-1 일때의 최대값 구하기 while stack: # print(f'd = {d}') # print(f'stack = {stack}') top...
5c7db07d6b86375c7d917f61f542e683534804ac
junjongwook/programmers
/Skill Check/Level3/s67258.py
1,723
3.828125
4
# -*- coding: utf-8 -*- """ 보석 쇼핑 : https://programmers.co.kr/learn/courses/30/lessons/67258?language=python3 """ def solution(gems): width = len(gems) d = dict() for g in gems: # 개별 보석의 개수 초기화 d[g] = 0 totalKinds = len(d) answer = [0, width - 1] left, right = 0, 0 d[gems[0]] = 1...
4ec23c73ee6c2eacf6091cdaae5a30473b5b1183
junjongwook/programmers
/Skill Check/Level3/s12900.py
538
3.828125
4
# -*- coding: utf-8 -*- """ 2 x n 타일링 : https://programmers.co.kr/learn/courses/30/lessons/12900 """ def solution(n): if n == 1: return 1 elif n == 2: return 2 answer = 0 from collections import deque queue = deque([1, 2]) for _n in range(3, n+1): answer = queue[0] + queue[1] ...
0d2041614806d597b4b3e3583b5496f8adc8857b
junjongwook/programmers
/Skill Check/Level2/s42888.py
1,002
3.671875
4
# -*- coding: utf-8 -*- """ 오픈채팅방 : https://programmers.co.kr/learn/courses/30/lessons/42888?language=python3 """ def solution(records): answer = [] nameDict = dict() actions = [] for record in records: action, *user = record.split() actions.append((action, user[0])) if len(use...
2191e63d2697b3b9a76b37402f7f54e7c64c7bae
junjongwook/programmers
/Skill Check/Level2/s62048.py
512
3.625
4
# -*- coding: utf-8 -*- ''' 멀쩡한 사각형 : https://programmers.co.kr/learn/courses/30/lessons/62048?language=python3 풀이 : https://leedakyeong.tistory.com/entry/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%A9%80%EC%A9%A1%ED%95%9C-%EC%82%AC%EA%B0%81%ED%98%95-in-python ''' def solution(w,h): from math impor...
0d8412c539cb20f4559f4ae4e3b1537120f03ad8
junjongwook/programmers
/Skill Check/Level3/s60059.py
1,691
3.53125
4
# -*- coding: utf-8 -*- """ 자물쇠와 열쇠 : https://programmers.co.kr/learn/courses/30/lessons/60059?language=python3 """ def solution(key, lock): lock_width = len(lock) key_width = len(key) def key_value(start_h, start_w, h, w): _h = h - start_h _w = w - start_w if 0 <= _h < key_width ...
27724f1be9478f91c54338d078d7365b299d1c42
junjongwook/programmers
/Skill Check/Level2/s12985.py
499
3.796875
4
# -*- coding: utf-8 -*- """ 예상 대진표 : https://programmers.co.kr/learn/courses/30/lessons/12985?language=python """ def solution(n, a, b): answer = 1 a, b = min(a, b), max(a, b) while True: if a % 2 == 1 and a + 1 == b: break else: a = (a + 1) // 2 b = (b ...
ff200de5d85a8c2e801f2eff4585ae087ea8bd6b
junjongwook/programmers
/Skill Check/Level4/s64063.py
980
3.515625
4
# -*- coding: utf-8 -*- """ 호텔 방 배정 : https://programmers.co.kr/learn/courses/30/lessons/64063?language=python3 """ def solution(k, room_number): answer = [] N = len(room_number) reserved = dict() for room in room_number: if room not in reserved: answer.append(room) res...
e80d7e50cf0e36d750f62a1c0cb3f42e8708c112
junjongwook/programmers
/Skill Check/Level2/s17683.py
1,958
3.734375
4
# -*- coding: utf-8 -*- """ [3차]방금그곡 : https://programmers.co.kr/learn/courses/30/lessons/17683?language=python3 """ def change(m): m = m.replace('C#', 'c').replace('D#', 'd').replace('F#', 'f').replace('G#', 'g').replace('A#', 'a') return m def solution(m, musicinfos): answer = '(None)' m = change(m...
dc6022ad2e4820e959d39bf5431bed099c247c5a
fxh-coder/python_sgrammer
/fileDeal/TraverFiles.py
1,169
3.65625
4
import os import time ''' 功能描述:遍历目录处理子文件 参数描述: 1 rootDir 目标文件的根目录 ''' class TraversalFun(): # 1 初始化 def __init__(self, rootDir): self.rootDir = rootDir # 2 遍历目录文件 def TraversalDir(self): TraversalFun.AllFiles(self, self.rootDir) # 3 递归遍历所有文件,并提供具体文件操作功能 def AllFiles(self, roo...
63706cde238c954bdeb64fcfeabd309e48858491
priyaresilient/PythonBeginner
/main.py
536
3.90625
4
import random if __name__ == '__main__': def game(): user = input(f'r for Rock s for Scissors p for paper') computer = random.choice(['r', 's', 'p']) if user == computer: return 'Tie' if is_win(user, computer): return 'You WON!' ...
616b6e64282b508ff1f18fd43934da28ca620e5b
harshitaagrwl/SocketProgramming
/task1(TCP calculator)/client.py
793
3.609375
4
print("\tClient Server Calculator") print("############################################################") print("If you want to stop calculation,enter x while giving input") print("############################################################") import socket print("\t\t\t Client side communication ") host = socket.geth...
8b1da6f03ed53cf4962736b1ff909a48f4ab0afc
martincli/coms4701-assignments
/decision_tree_learning/learner.py
6,301
3.5
4
import math import csv import sys #================================== # Decision tree learning algorithm # (textbook pg. 658, 2nd edition) #================================== def decisionTreeLearning(examples, attributes, default): if not examples: return default elif allSameClassification(examples): ...
52fa1dc2a81fc3c74972662255c74957d0fb9429
GeginV/Iterations-Python
/practice (9).py
141
4.03125
4
A = int(input('Enter A\n')) if not((-10 <= A <= -1) or (2 <= A <= 15)): print('It does not belong') else: print("It belongs")
93d555666abe7d69cb5ff710ccf599009da762ed
GeginV/Iterations-Python
/practice (3).py
199
3.828125
4
try: number_input = int(input(" Type a number ")) except ValueError as e: print("You didn't type a number") else: print('You typed ', number_input) finally: print("I'm done")
bee25d157f354404981db25e5912e87f21e1bb10
GeginV/Iterations-Python
/practice (17).py
769
4.1875
4
list_ = [-5, 2, 4, 8, 12, -7, 5] # Объявим переменную, в которой будем хранить индекс отрицательного элемента index_negative = None for i, value in enumerate(list_): if value < 0: print("Отрицательное число: ", value) index_negative = i # перезаписываем значение индекса print("Новы...
e873b638d6a66673c7e3666619df0950fe84a96c
whendonkiesfly/CrawlingRobotsEA
/controllers/ennlib.py
12,969
3.75
4
""" This library defines classes that implement neural networks as well as a generic EA algorithm. """ import json import pickle import random import numpy as np def interpolate(val, min, max): """ Interpolates values between 0 and 1 to values between the specified min and max. Used primarily map...
96baa75d216fb45ec5e00a24da990a02c8b7ee61
RadhikaK14/Python_Libraries
/sl_numpy.py
389
4.09375
4
import math as m # import numpy as np # # array = np.array([5,8,4,3]) # print(array.mean()) ''' x = [5,8,4,3] array = 0 sum = 0 for num in x: array = array + num * (x.index(num)) sum = sum + num mean = array/sum # mean = sum(x)/len(x) print(f'mean : {mean}') diff = 0 for num in x: diff = diff + ((num-mean)...
270662b5c2fe90053ccdb64d1c0412ff1e638a3a
sas342/hackerRank
/datastructures/Heap.py
10,669
3.8125
4
from math import floor, log import abc class Heap(): __metaclass__ = abc.ABCMeta def __init__(self): self.heap = [] def size(self): return len(self.heap) def height(self): return floor(log(self.size())) def printRoot(self): print self.heap...
a76f4184dce657ce05f02b7fa5ea2719e609080a
sas342/hackerRank
/strings/GameOfThrones.py
608
3.953125
4
''' Created on Apr 9, 2016 Check if given string is anagram of palindrome @author: sstimmel ''' def isPalindrome(string): charArray = [0 for x in range(26)] for x in string: val = ord(x)-97 charArray[val] = charArray[val] + 1 numOfUneven = 0 for x in range(0,26,1): ...
3a20f5938a1a24548eddc1af7a8d5eff35cedbd8
sas342/hackerRank
/greedy/Florist.py
575
3.53125
4
''' n flowers, k friends A is cost of flowers sorted ''' def findCost(A, n, k): cost = 0 timesThru = 1 bought = 0 while bought < n: for i in xrange(k): #print "i=",i cost += (timesThru * A[n-bought-1]) # print "cost=",cost," ",timesThru," ",A[n-bought-1] ...
c5c2bd0b0ba37393ce9ceeaba22fde3097283d82
sinan-ozel/network-analysis-sample-snippets
/count-ap.py
1,263
3.5
4
""" This utility counts the access points that a given MAC address has roamed on. Usage Example: python ./count-ap.py XCC_StationEventsLog.csv 5C:A8:6A:8E:66:7A --start "May 5, 2021 7:00:00 PM" --end "May 5, 2021 7:05:00 PM" """ from argparse import ArgumentParser, RawTextHelpFormatter import pandas as pd parser =...
38f1887dfd69cc05ac8fa0a0c050f458d09d9a5f
tomperrine/ip-renumber-analysis
/filter-my-ranges.py
1,326
3.5625
4
#!/usr/local/bin/python3 # given two files - a list of "my" IP ranges and a list of candidate IP addresses: # filter out all IPs that are in one of "my" ranges # Usage: $0 range-file candidate-ip-file import sys import ipaddress # the list of "my" ranges # this is a list of IPv4Network objects my_ranges = [] # a...
4ab4c3056fd4eef1bb596232ebf098b9882c82e2
avikejriwal/Project_Euler
/p12.py
559
3.671875
4
#nth triangle number can be computed by n(n+1)/2 import math n = 1 k = 1 def isSquare(n): root = int(math.sqrt(n)) if root**2 == n: return True else: return False while k < 500: k = 0 N = n*(n+1)/2 for j in range(1,int(math.sqrt(N))): if N % j == 0: k += 1...
9565a51e8ffdc7faf54af9c702eb4d2261d724c0
thoratomkar/Python
/BinarySearchTree.py
4,783
3.875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 1 10:41:06 2018 @author: omkar """ class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None self.parent=None class BinarySearchTree(): def __init__(self): self.root ...
2095edd41bdf8036ba5ad3aab3a75cb7492b1f2e
YoungsoonLee/review_algorithms_data_structure
/quickSort.py
986
3.875
4
import unittest # return pivot index def partition(array, left, right, pivotIndex): pivot = array[pivotIndex] # right is pivot while left <= right: while array[left] < pivot: left += 1 while array[right] > pivot: right -= 1 if left <= right: temp = array[left] array[left] = array[right] array[...
18504ba6b54cd9a97e75999a3734ac3d361a9cb7
YoungsoonLee/review_algorithms_data_structure
/hanoi.py
765
3.984375
4
class Hanoi(): def __init__(self): self.count = 0 def hanoi(self, n, source, helper, target): print("hanoi( ", n, source, helper, target, " called") self.count += 1 if n > 0: # move tower of size n - 1 to helper: self.hanoi(n - 1, source, target, helper) ...
c540abc39164e185419ee8d9e29ebca03832a345
4rachelgreen/Dart_EnvGIS
/Week1-2_Lecture.py
5,274
3.828125
4
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # Name: Week1-2_Lecture.py # Purpose: Example and Notes for Week 1 Lecture # # Compatibility: Python 3.5 # # Author: James Dietrich, Dartmouth College # james.t.dietrich@dartmouth.edu...
8d2d834deb28a65efbf4211c4485ace8dad340ac
wind86/learning
/python3-basics-tutorial/src/lesson7.py
214
3.984375
4
''' Created on Jan 21, 2017 @author: ubuntu ''' x = 5 y = 8 if x > y: print('x > y') else: print ('x <= y') if x > y: print('x > y') if x > 55: print ('x > 55') else: print ('x <= y')
8e87d81950a88b0cf9c1b7db0163e624b874bbae
wind86/learning
/python3-intermediate-tutorial/src/lesson4.py
578
3.890625
4
''' Created on Apr 08, 2017 More on list comp and generators - Intermediate Python Programming p.5 https://www.youtube.com/watch?v=MJUbUDa-YCA&index=5&list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_ @author: ubuntu ''' # input_list = [5,6,2,1,6,7,10,12] # # def div_by_five(num): # if num % 5 == 0: # return True...
37b5b63621bd57d967013b7d9d2c1a67fd41ccc4
wind86/learning
/python3-intermediate-tutorial/src/lesson20.py
1,266
3.765625
4
''' Created on Apr 08, 2017 Special Methods, OOP, and Iteration Python Tutorial https://www.youtube.com/watch?v=jucLTJCM5jA&list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_&index=21 @author: ubuntu ''' # x = range(5) # # x = (i for i in range(5)) # # for i in x: # print(i) # # x = (i for i in range(5)) # nex...
16858c6ef1445b0692da633215586257ee3dcb2d
lukasz-f/hf-python
/03 files and exceptions/string_operations.py
2,667
3.921875
4
str = ' asdf:fdsa:asdf ' # s = '!!!!!'' s = "!" * 5 # s = 'hellothere' s = 'hello' + 'There' # s = 'helloThere!' s += '!' # Get s length len(s) # Sliceing str[2] # Return third letter from str str[2:4] # Return third and fourth letter from str str[1:] # Return string without first letter str[-1] # Return l...
132916133e06d31875f9a8e131f69a7d550ef5d1
francescomantegna/tf_pos_tagging
/FRA/ExampleBayesClassifier2.py
7,174
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 19 18:26:25 2017 @author: patrizio """ ''' A Multilayer Perceptron implementation example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/) Author: Aymeric Damien Project: h...
b2df25d12178483143cbb6fcceaba3e2220b2b4b
eludom/snippits
/python/exercises/python/QuickSort.py
2,607
4.125
4
# -*- coding: utf-8 -*- """ This class implements qucksort on arrays. See https://en.wikipedia.org/wiki/Quicksort # algorithm quicksort(A, lo, hi) is# # if lo < hi then # p := partition(A, lo, hi) # quicksort(A, lo, p – 1) # quicksort(A, p + 1, hi) # # algorithm parti...
18efb01e3eafcc67f2f4e873fa901bd974e2bd5e
eludom/snippits
/python/dicts.py
205
3.890625
4
#! /usr/bin/env python """ Simple tests of dictionaries in python """ foo = {} foo["foo"]="fooo" foo["bar"]="baaar" foo["baz"]="baaaz" for k in foo.keys(): print "key", k, "value", foo[k]
8a7069d475e28c9eed02902b0aaa459b5ddf0213
hackaholic/StartUs
/verifypass.py
1,431
4.0625
4
"""There is a restriction in the authorization system: the password must begin with a Latin letter, consist of Latin letters, numbers, dot and minuses, but end only with a Latin letter or number; the minimum password length is one character, the maximum is 20. Write a code that checks whether the input string matches t...
700ef659d1f87be1cb960ca2ecb5e12553ae8ce2
Jenny520235/Practice-Project
/8-4:列表_查找和修改元素.py
1,066
3.9375
4
my_list=[16,25,78,96,31] print(my_list) # 知识点1:查找其中一个元素 # 引入index方法。讲解:如果能查找到该值,即会打印出它所在位置。若不存在则会报错 result=my_list.index(31) # 傻不傻:当你不晓得怎么打印出它的时候,就说明你改重新定义一个变量来接收这个结果了 print(result) # 拓展:值经常在变,需要修改的这种情况就可以直接将它定义成一个变量 # 知识点2:修改列表中元素的值 old=25 new=8000 # 思路:先找到要修改的值的位置,然后将其修改 # 查找位置,需进行校验。因为该值不在列表中则会报错 if old in my_lis...
632cfc88d528bc36bf9ce581efcbff0f2c27a62f
Jenny520235/Practice-Project
/5-3:while循环-continue.py
1,169
3.6875
4
# 练习-计算1-100的累加和,但50不进行累加。 """ 方法1: 思路:排除50,其他数字相加即可。 附注:index — <数>指数,索引 """ index =1 total =0 while index<=100: if index != 50: total=total+index index+=1 print("结果是:",total) """ 方法2:当累加遇到数字50的时候,跳过它 如何跳过? —while循环中的continue关键字 continue关键字的作用:跳过本次循环。不是退出循环! """ a =1 my_sum =0 while a<=100: if...
d857692a88d5ed6428d6075759bea76c1a5726cc
Jenny520235/Practice-Project
/7-3:容器_字符串切片.py
3,113
4.09375
4
# 知识点1:查找字符串 # 案例:将邮箱中的一部分字符串单独截取出来储存,需要如何操作? user_email="liulihong@163.com" # 案列思路分析:首先要了解邮箱的组成:@前面部分是用户名,@后面部分是邮箱域名 # (1)查找字符串中@的位置 # (2)获得字符串中的子串(子串就是字符串中的一部分的意思) # 第一步查找@的位置需要引入一种方法:find # find函数的特点: # a.如果能查找到,则返回子串第一次出现的位置 # b.如果不能查找到,则返回-1 position=user_email.find("@") # 是字符串的相关操作,字符串在代码中要用"" if positio...
a735ed7dcaf2fa67a3426e9e67edb26018b8bdf7
Jenny520235/Practice-Project
/11-2:文本拷贝.py
1,631
3.71875
4
# coding:utf-8 # 原封不动的拷贝一个文件,不能涉及格式转换——因此要用二进制 # 思路分析: # 1.获取要拷贝的原文件名(老文件) old_name=input("请输入要复制的文件名:") # 2.拼写复制后的文件的名字(新文件) # 2-1.将截取老文件.txt前面部分的文件名,加入[副本]这种格式。因此需要用切片 position=old_name.rfind(".") # print(position) # 拼接复制后的文本名儿 # new_name=old_name[:position]+"副本"+".txt" # 此处考虑的不够全面,文本后缀不一定都是TXT啊,还有可能是PDF等等 # 最好是对...
a85e26d5ceacfe1b669762e06e6311d061b53afa
CUCEI20B/zodiaco-omar2959
/main.py
1,636
4.0625
4
Mes = { 'ENERO' : 1, 'FEBRERO' : 2, 'MARZO' : 3, 'ABRIL' : 4, 'MAYO' : 5, 'JUNIO' : 6, 'JULIO' : 7, 'AGOSTO' : 8, 'SEPTIEMBRE' : 9, 'OCTUBRE' : 10, 'NOVIEMBRE' : 11, 'DICIEMBRE' : 12 } dia = int(input('Ingresa unicamente el numero del dia de tu nacimiento (entero): '))...
9b960b1e462429103d155428b9efac967529c7a3
NghiepQuangLy/FIT3077_FHIR_Patient_Monitor
/src/DataModel/Observation.py
1,045
3.875
4
from abc import ABC, abstractmethod class Observation(ABC): _name: str _value: float _unit: str def __init__(self, value: float, unit: str, name: str): assert type(value) is float, "Observation value should be a float but is of type " + str(type(value)) assert type(unit) is str, "Obs...
073fc2f6fa2351d7017e8c56e29c442c4e9e6b6b
SeungHune/hakerrank
/hakerrank_Jumping_on_the_Clouds.py
267
3.515625
4
def jumpingOnClouds(c): check = 0 answer = 0 for cloud in c: if cloud == 0: check += 1 else: check = 0 answer += 1 if check == 2: answer += 1 check = 0 return answer
7b0474975d01b10c21590ebde63e8b354754bce2
adsarode/artificial-intelligence
/Projects/3_Adversarial Search/scratchpad.py
278
3.515625
4
class A: def __init__(self, val1, val2): self.a1 = val1 self.a2 = val2 A1 = A (10,20) A2 = A (1,200) A3 = A (5,500) testDict = {A1: 'A1', A2: 'A2', A3: 'A3'} best = max(testDict.keys(), key = lambda item: item.a2) print(testDict[best]) #for a in testDict: # print(a.a1)
1a12eee67a186c99a8d6e1aa922b79308d2d331e
farhod-rahimov/python-django-pool
/day-01/ex06/my_sort.py
1,065
3.703125
4
def sort_func(): d = { 'Hendrix' : '1942', 'Allman' : '1946', 'King' : '1925', 'Clapton' : '1945', 'Johnson' : '1911', 'Berry' : '1926', 'Vaughan' : '1954', 'Cooder' : '1947', 'Page' : '1944', 'Richards' : '1943', 'Hammett' : '1...
c8df86dfbe9e8bf14411562c03c844b126c67d8d
farhod-rahimov/python-django-pool
/day-01/ex05/all_in.py
2,986
3.671875
4
import sys def get_capital_from_state(capital): def get_state(key): states = { "Oregon" : "OR", "Alabama" : "AL", "New Jersey": "NJ", "Colorado" : "CO" } try: val = states[key] return val except KeyError: ...
1663b6673555defcd141973816e8b5e1364fcb53
fabianomobono/interview_prep
/duplicates.py
251
3.9375
4
d = [1, 2, 3, 6, 3, 6, 1, 1] # find all duplicates def find_duplicates(arr): di = set() duplicates = set() for x in arr: if x in di: duplicates.add(x) else: di.add(x) return duplicates print(find_duplicates(d))
35c3600cf44522a3aa1e151c875fb388ec3b474b
sarincr/Semester-Long-Program-on-App-Development
/23.Add/07.Counter/main.py
600
3.703125
4
import tkinter as tk def increase(): value = int(X["text"]) X["text"] = f"{value + 1}" def decrease(): value = int(X["text"]) X["text"] = f"{value - 1}" root = tk.Tk() root.rowconfigure(0, minsize=50, weight=1) root.columnconfigure([0, 1, 2], minsize=50, weight=1) btn_decrease = tk.Button(master...
cfb596a774c3cf155c7c648cb0c5ee5d67ef61f5
sarincr/Semester-Long-Program-on-App-Development
/20.Grids and Frames/01.Grid1.py
339
3.703125
4
from tkinter import * root = Tk() btn_column = Button(root, text="I'm in column 3") btn_column.grid(column=3) btn_columnspan = Button(root, text="I have a columnspan of 3") btn_columnspan.grid(columnspan=3) btn_sticky = Button(root, text="I'm stuck to north-east corner of frame") btn_sticky.grid(sticky=NE)...
28b44cbf023b4b08922ab4ed76cd549977b640e2
Atomiccloud/Astar
/Main.py
1,731
3.578125
4
import random import sys from AStar import astar from DisplayGUI import GUI def make_grid(size, percent): grid = [] grid = [[0 for x in range(size)] for y in range(size)] if percent != 0: percent = percent/100 grid = fill_grid(grid, size, percent) return grid def fill_grid(grid, siz...
0a8dcc7920f533d158afb026ca2eb4c557d87cc1
tchataigner/Artificial_Neural_Network
/ann.py
5,695
3.5
4
import math import random import numpy as np np.seterr(all = 'ignore') array_error=[] # sigmoid transfer function def sigmoid(x): return 1 / (1 + np.exp(-x)) # derivative of sigmoid def dsigmoid(y): return y * (1.0 - y) # using tanh over logistic sigmoid is recommended def tanh(x): return math.tanh(x...
a0357a37f8d8fa57aba007fb38caf46b6109f667
pythonbrad/social_network
/maintenance_mode/io.py
674
3.84375
4
# -*- coding: utf-8 -*- import os def read_file(file_path, default_content=''): """ Read file at the specified path. If file doesn't exist, it will be created with default-content. Returns the file content. """ if not os.path.exists(file_path): write_file(file_path, default_content) ...
3994654b46ae8b7b623f088bb17b9bd71c78c0f1
poo250696/python_training
/dict/example.py
582
3.765625
4
a_list = [1, 2, 3, 4, 5] b_list = ["a", "b", "c"] # b[1] a_dict = { 'a': 'rahul', 'v': 'sandeep' } print(a_dict['v']) b_dict = { 1: 'rahul', 2: 'sandeep' } print(b_dict[1]) c_dict = { 'a': 'rahul', 2: 'sandeep', 'b': 'red' } print(c_dict[2]) d_dict = { 'name': 'shelke', 'firs...
8010c44e4156bca1df75a2542762306dfea6b305
codingnoye/eachday-algo
/2693.py
96
3.59375
4
for i in range(int(input())): li = list(map(int, input().split())) print(sorted(li)[-3])
b903455b43ec3d5745b4884be8495fcb303f333f
codingnoye/eachday-algo
/11557.py
256
3.609375
4
for i in range(int(input())): high = 0 highschool = 0 #lol for j in range(int(input())): school, amount = input().split() if int(amount)>high: highschool = school high = int(amount) print(highschool)
ef502f9a1338f2b5625d8ba9125373de0b28768d
codingnoye/eachday-algo
/2948.py
237
3.6875
4
day = ['Wednesday','Thursday','Friday','Saturday','Sunday','Monday','Tuesday'] monthday = [31,28,31,30,31,30,31,31,30,31,30,31] date = 0 d, m = map(int, input().split()) for i in range(m-1): date += monthday[i] print(day[(date+d)%7])
6b858790b38bd6689e236613304084c00d69de30
wcedmisten/ingredient-phrase-tagger
/ingredient_phrase_tagger/training/partitioner.py
1,804
3.78125
4
def split_labels(label_reader, training_label_writer, testing_label_writer, training_fraction, max_labels=0): """Splits a full label set into a training and testing set. Given a full set of labels and associated inputs, splits up the labels ...
6d0ad8f431b1d437f365d76737b097af67e5175a
TigerTTTT/AID_2010
/project_month02/FTP_sys/ftp_client.py
2,825
3.5625
4
from socket import * import sys, os class FTPHandle: server_address = ("127.0.0.1", 4321) def __init__(self): self.socket = self.connect_server() def connect_server(self): tcp_socket = socket() tcp_socket.connect(FTPHandle.server_address) return tcp_socket def do_lis...
973cb899da9bc274acf4fe8ddf3bdf9a844357e3
RaulVS14/adventofcode2019
/Day 3: Crossed Wires/manhattan_distance.py
1,619
3.609375
4
import re class ManhattanDistance: @staticmethod def calculate_distance(wire1, wire2): path_wire1 = ManhattanDistance.trace_path(wire1) path_wire2 = ManhattanDistance.trace_path(wire2) intersections = set(path_wire1.keys()) & set(path_wire2.keys()) distance = min([abs(x) + abs...
f7cc05e2f6c0f960397d8e59f413ffa266da842d
u98106/Python-learning-notebooks
/Untitled.py
1,820
3.78125
4
# coding: utf-8 # In[1]: a = 10 print a*a f(a) # In[ ]: def f(a): pass f(10) # In[ ]: class Shape(object): def __init__(self): pass def area(self): pass def peri(self): pass # In[26]: class Rectangle(object): def __init__(self, length, width=None): self.l...
dbf16de19d2a7b0cc78f044ca460dbce36955bd8
u98106/Python-learning-notebooks
/sop.py
420
3.515625
4
# Calculate som-of-prods of two lists #import pdb #pdb.set_trace() def sop(l1, l2): sum_ = 0 c = [] for i in range(len(l1)): c.append(l1[i]*l2[i]) return sum(c) def sop(l1, l2): sum_ = 0 for n1, n2 in zip(l1, l2): sum_ += n1*n2 return sum_ a = [1,2,3,4] b = [0,-1,2,...
724a0578dc27aed922d97a4d217cf707578bb491
EmmaYorHa/secao5
/Exercicio7.py
278
4.0625
4
print('Insira abaixo um número inteiro:') num = int(input()) print('Insira abaixo outro número inteiro:') num1 = int(input()) if num > num1: print(f'{num} é maior que {num1}') elif num == num1: print('Números iguais') else: print(f'{num1} é maior que {num}')
f13f5e7386d850e2b1caa729db4a98e543b086f6
adrian/udacity-cs387-applied-cryptography
/final/crypto.py
1,951
3.5
4
from Crypto.Cipher import AES from Crypto.Util import Counter import binascii class AESCounterMode: def decrypt(self, key, nonce, ctr_iv, ciphertext): """ key: (byte string) - The secret key to use in the symmetric cipher nonce: (hex string) - MUST be 4 bytes ctr_iv: (hex string)...
cec45cedd76fc6bf74d4c417ca9f308d56333a17
efraim224/competitive-programming
/problem solving/dynamic programmi/pc.py
1,506
3.609375
4
# a simple parser for python. use get_number() and get_word() to read def parser(): while 1: data = list(input().split(' ')) for number in data: if len(number) > 0: yield(number) input_parser = parser() def get_word(): global input_parser return next(input_pa...
eafded0302cce8ca09236e4857bcfe66b4d6d6c5
efraim224/competitive-programming
/problem solving/dynamic programmi/testofGFG.py
533
3.84375
4
# Python3 program for # the above approach # Function to calculate the total # number of ways to have sum N def findWays(N): # Initialize dp array dp = [0] * (N + 1); dp[0] = 1; # Iterate over all the # possible intermediate # values to reach N for i in range(1, N + 1): dp[i] = 0; # Calculate the sum for...
fea487f79d30c9836bbb95cb97b503a06a5b6480
allysonbueno/DIOCarrefourDataEngineer
/Python/arquivos.py
818
4.03125
4
""" r = read w = write a = both r+ = r+w w+ = apaga arquivo anterior a+ = r+w atualiza arquivo atual """ # -*- coding: utf-8 -*- #arquivo = open("arquivo.txt") #w = open("C:/Estudos/Python/arquivo2.txt", "w") #argumento w - write #w = open("C:/Estudos/Python/arquivo.txt", "w") #w - write e sobrepoe o arquivo.txt cri...
bf0510bb115bd7b514b280b178403da6e22acf81
allysonbueno/DIOCarrefourDataEngineer
/PythonDIO/2 InteracaoUsuario.py
573
4
4
a = int(input('Digite um valor: ')) b = int(input('Digite outro valor: ')) soma = a + b subtracao = a - b multiplicacao = a * b divisao = a / b resto = a % b 5 2 resultado = ('Soma: {sum}' '\nSubtracao: {sub}' '\nMultiplicação: {mult}' '\nDivisão: {div}' '\nResto: {rest}...
3dce6bc1c00a2858c41e931d43e2b4f6a0129e3d
allysonbueno/DIOCarrefourDataEngineer
/Python/avancadoListComprehension.py
339
3.84375
4
x = [1,2,3,4,5,6,7,8,9] y = [] # for i in x: # y.append(i**2) # lista de x foi pra i e resulta no quadrado de cada 1 # print(x) # print(y) #list comprehension: x = [1,2,3,4,5,6,7,8,9] y = [i**2 for i in x] #y = [valorAAdicionar laço condição] z = [i for i in x if i%2==1] #para imprimir numeros impares print(x) p...
8e0bec6a74bb4a037652999418e015ca2da5f15e
jmcastagnetto/2013-IntroDataScience-Coursera
/assignment03/problem04/assymmetric_friendships.py
732
3.640625
4
import MapReduce import sys """ Assymetric friendships using the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() def mapper(record): person = record[0].encode('utf8') friend = record[1].encode('utf8') mr.emit_intermediate(person, friend) def reducer(key, values): person = key fo...
9ccf0e412d035754b362837e88c2bdcd8adfd68a
sananta/Python
/prog2partb.py
1,432
4.0625
4
## prog2partb.py ## Srivarshini Ananta ## January 26, 2016 def inchesToMeters(inches): """ compute meters given inches """ exchangerate = 0.0254 result = inches * exchangerate return result def poundsToKgs(pounds): """ compute kilograms given pounds """ exchangerate2 = 0.453592 result = p...
60918ca66c51c0662482de444832e1edb4dee976
Selsen/RockSoup
/myapp.py
1,119
3.90625
4
# This program will help the user determine, which type of rock the person has found. # The user types properties of the rock, like color, porosity etc. The program combines the user input with properties of know rocks and suggests these # I.e. User types 'Pink', Computer outputs 'It could be/contain Rosenkvarts'. 'It...
d91f1a2a92614ce18fa55741ec76a3278ad31431
tatanmejia/taller1_inteligencia_artificial
/Taller 1 inteligencia artificial.py
942
3.84375
4
# coding: utf-8 # In[1]: #calculo de moda y media import statistics as stats print ("VALORES ALMACENADOS ESTATICAMENTE") valor = [ 3 , 11, 6, 3, 2, 5 , 24, 9, 12, 20 ] print (valor) print (" ") totaldata= len(valor) print ("Total valores almacenados : ", totaldata) print (" ") #calculo de moda numdata = 0 for i ...
dcff5772d21ce234c5d187d1abaa219ae382b0ea
Yared01/ABC-Algorithm
/quick_fsort2.py
946
3.515625
4
import random as rand import source as flower class Quick(flower.Nectar): def __init__(self, data): self.src = data def fsort2(self, start, end): pivot_value = self.src[int(round(start + end)/2)].get_fitness() left_mark = start right_mark = end while left_mark <= right_...
9b79913f33afb24d35352da0dde9614588cc4928
riyasoy/Sudoko-python
/sudokoplay.py
2,177
3.5625
4
board = [ [1,0,0,4,8,9,0,0,6], [7,3,0,0,0,0,0,4,0], [0,0,0,0,0,1,2,9,5], [0,0,7,1,2,0,6,0,0], [5,0,0,7,0,3,0,0,8], [0,0,6,0,9,5,7,0,0], [9,1,4,6,0,0,0,0,0], [0,2,0,0,0,0,0,3,7], [8,0,0,5,1,2,0,0,4] ] def solve(bo): #using recurssion print(bo) find = find_empty(b...