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
bbfe897c1626af2c6ed3e518f2b4b78c0373e1c9
piaoliangkb/python-socket
/socket_client.py
2,820
3.5
4
from socket import * import time def set_keepalive_linux(sock, after_idle_sec=1, interval_sec=3, max_fails=5): """Set TCP keepalive on an open socket. It activates after 1 second (after_idle_sec) of idleness, then sends a keepalive ping once every 3 seconds (interval_sec), and closes the c...
9a731795319bcfc246c20b309c32fee3eaa75132
AugustineAykara/Competitive-Coding
/TCS CodeVita/Swayamvar/solution.py
316
3.5
4
n = int(input()) bride = input() groom = input() result = n m = groom.count('m') r = groom.count('r') for brideDrink in bride: if (brideDrink == 'm'): drink = m m -= 1 else: drink = r r -= 1 if (drink == 0): break; else: result -= 1 print(result)
5070da9f68ef68438fbaf701c5c958eba2243118
AugustineAykara/Competitive-Coding
/HackWithinfy/Paper Sheets/solution1.py
510
3.546875
4
h, w = map(int, input("Enter initial dimension : ").strip().split(" ")) h1, w1 = map(int, input("Enter new dimension : ").strip().split(" ")) count = 0 while(h > h1): if(h&1 == 1): #if h is odd h = h >> 1 #divides h by 2 h += 1 else: #if h is even h = h >> 1 count += 1 ...
21315e1418477adef07e13e67435d3e2550982ca
AugustineAykara/Competitive-Coding
/String/Sample1/solution.py
850
3.6875
4
t = int(input()) for _ in range(t): string = input() wordList = [] resultantList = [] dif = 1 i = 0 j = 1 # to break the string into words for k in range(1, len(string) + 1): word = string[i : j] if(word == ''): break wordList.append(word) ...
8b517e809f826243cf5cec06fe0af978dc37901f
AugustineAykara/Competitive-Coding
/Coding Interview Problems/Sample16/solution.py
277
4
4
n = int(input()) odd = 1 even = 2 for i in range(1, n+1): count = 1 while(count <= i): if (i % 2 == 0): print(even, end = " ") even += 2 else: print(odd, end = " ") odd += 2 count += 1 print()
a2021c337ebefca4044c15fa0771909aa3910f67
AugustineAykara/Competitive-Coding
/Others/Sample03/solution.py
356
3.84375
4
t = int(input()) for _ in range(t): shape = input() a = int(input()) b = int(input()) if(shape == 'rectangle'): area = a * b print(area) elif(shape == 'square'): area = (a * b)//2 print(area) elif(shape == 'triangle'): area = a * b print(area...
f109446921f1ff318bbba69316fc5d9ec5f39047
alanblevins/anybase32
/anybase32/__init__.py
2,937
4.0625
4
"""Encode and decode base32 data using arbitrary alphabets""" import base64 import string # Define known alphabets for convenience RFC_3548 = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" RFC_4648 = RFC_3548 RFC_2938 = b"0123456789ABCDEFGHIJKLMNOPQRSTVW" CROCKFORD = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ" CROCKFORD_MODIFIED = b"01...
ac233558523fd4d10a3f327417816cf9aafcfa9c
kchaoui/me
/week2/exercise1.py
1,958
4.65625
5
""" Commenting skills: TODO: above every line of code comment what you THINK the line below does. TODO: execute that line and write what actually happened next to it. See example for first print statement """ import platform # I think this will print "hello! Let's get started" by calling the print function. print("h...
ad434b6dc5c8cb5bf441469b5015ffc421612449
DhiaulAmar/Dhiaul-Amar-Naufal_I0320027_Tiffany-Bella_Tugas-7
/I0320027_Soal 1_ Tugas 7.py
342
3.65625
4
teks = "Panik ga? Panik ga? Panik lah masa engga" #membuat string berada di tengah a = teks.center(70,"*") print(a) #mengubah string menggunakan upper dan lower print(teks.upper()) print(teks.lower()) #mengganti kata panik b = teks.replace("Panik", "Kaget") print(b) #mengitung panjang kalimat print("Panjang string ...
526c8fed005bf2092f3aacd1e0bc3d08d87445cd
DoubleHok/Data-Structure-Algorithms
/Code by myself/13快速排序.py
1,292
3.859375
4
# encoding: utf-8 """ @version: 3.7 @E-mail: DoubleHok@163.com @file: @time: 2020/4/22 10:54 """ def quick_sort(alist, start, end): """快速排序""" # 递归的退出条件 if start >= end: return # 设定起始元素为要寻找位置的基准元素 midpoint = alist[start] # low为序列左边的由左向右移动的游标 low = start # hig...
57323a8a33eb22ccc3f4fc6073cc86080fdb24a5
DoubleHok/Data-Structure-Algorithms
/Code by myself/11选择排序.py
669
3.75
4
# encoding: utf-8 """ @version: 3.7 @E-mail: DoubleHok@163.com @file: @time: 2020/4/22 9:09 """ def selection_sort(alist): n = len(alist) # 需要进行n-1此选择操作 for i in range(n-1): # 记录最小位置 min_index = i # 从i+1位置到末尾位置选出最小数据 for j in range(i+1, n): if ...
cf92a0932911b5126e14d2a7eb413680b8b57272
MichalMatija/B4M36KBE
/lab3/lab3.py
2,471
3.515625
4
import itertools import hashlib def tupleToString(tuple): str = ''.join(tuple) return str salt = '1e09d' my_sha1 = "2655a13f039e9966d590ca8e260cc1a48bf494a6" password_possible_letters = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', ...
813e8d695353a248f0d24f7247c759d57e496270
vahev/python-ninja
/modules/iterators-generators.py
351
4
4
# Creates a generator for numbers to the third power def gencubes(n): for num in range(n): yield num**3 for x in gencubes(10): print(x) # When: [a, b = b, a+b] statement is executed, the outcome will # execute like:[ a = b; b = a + b] but simultaneously, neither the value of 'b' # nor 'a' will change ...
fa056713abc31b82ca49e370fd027d0b234bfcc2
Usefmuq/AI-project
/AStar.py
4,339
3.765625
4
N = 10 G = [[False for x in range(N)] for y in range(N)] estCost = [0] * 10 toCityCost = [[0 for x in range(N)] for y in range(N)] funcGCost = [0] * 10 funcFCost = [0] * 10 calc = [0] * 10 list_ = [] def hFunc(i): global estCost return estCost[i] def retFCost(city): global funcFCost return funcFCost...
4e9cb8455cb90b2e8ac87a279ebec79d7392da96
Umakanth-mishra/gitam-june-2019
/28 June 2019.py
3,449
3.921875
4
#!/usr/bin/env python # coding: utf-8 # In[7]: class demo: def test(self): print("test() for the class and method") return obj=demo() obj.test() # In[3]: def test(): print("test() for function") return test() # In[10]: class demo1: def fact(self,n): #return the factori...
0919ad6c53022ddabaa7a109f7052f0c151032af
dylanmann/blog_parsing
/get_insights.py
1,106
3.5625
4
#!/usr/bin/python3 import json from pprint import pprint import operator def dedup(x): return { 'Julian': 'Julian Mazaira', 'Steven': 'Steven Jacobson', 'JLiu' : 'Jasper Liu', 'Alan' : 'Alan Delaney', 'alan delaney': 'Alan Delaney', 'Roman' : 'Roman Schuster', ...
ea54a9607e1c97179a1b686b78bd5dc809c250a2
sghosh1991/InterviewPrepPython
/LeetCodeProblemsEasy/680_valid_palindrome2.py
720
3.84375
4
""" """ class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ left = 0 right = len(s)-1 while left < right: if s[left] != s[right]: return self.isPalindrome(s[left:right]) or self.isPalindrome(s[l...
167f110957ddd56954d89e211007901673ce2ca5
sghosh1991/InterviewPrepPython
/Strings/AnagramSubstring.py
1,763
3.765625
4
import collections def create_freq_table(src): freq_table = collections.defaultdict(int) #Do processig here for ch in src: freq_table[ch] += 1 return (freq_table, set(src)) def isMatchFound(freq_table): if len(freq_table) == 0: return True return False ...
94101d0179b9826da4e12ed61fbb1f08cf93e7e5
sghosh1991/InterviewPrepPython
/LeetCodeProblemsEasy/543_Diameter_of_binary_tree.py
2,650
4.40625
4
''' Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree 1 / \ 2 3 / \ 4 ...
63ce707a748bbece3e2ece80e264fdebce16b631
sghosh1991/InterviewPrepPython
/HackerRank/MaxSumSubsequence.py
318
3.5
4
import sys def maxSumSubsequence(arr): # Simply sum up all +ve numbers. If no positive numbers simply output the least -ve number max_sum = 0 for i in range(len(arr)): if arr[i] > 0: max_sum += arr[i] if max_sum <= 0: max_sum = max(arr) return max_sum
0f4dffef4df1aee09724c670618ab5689d1e4333
sghosh1991/InterviewPrepPython
/DynamicProgramming/LongestPalindromicSubsequence.py
2,474
4.03125
4
''' Creation Date: Jul 4, 2016 @author : Santosh Ghosh Problem Statement: Find the longest palindromic subsequence in a string. Similar kind of question: Minimum number of chars to be deleted to make a string palindromic Input: String S Output: Length of LPS as well as the LPS itself Logic Applied: This solution u...
8654e16483faf714b7feafd42690c87429c247f6
sghosh1991/InterviewPrepPython
/Strings/Trie.py
1,339
3.609375
4
class TrieNode(): def __init__(self): self.children = {} self.endofword = False def buildTrie(words): root = head = TrieNode() for word in words: #print "Adding " + word + " to trie" head = root for ch in word: #print "Inspecting " + ch if ch...
da21be7cbcebc6b6163d9f41c0e8b575941a7548
sghosh1991/InterviewPrepPython
/Recursion/AllStringPermutationWithDup.py
1,556
3.84375
4
''' Creation Date: Jul 2, 2016 @author : Santosh Ghosh Problem Statement: Given a input string s which may contain duplicate characters find the number of anagrams Input: String s with duplicate chars Output: All anagrams Logic Applied: Look at Page 359 of Cracking the coding interview 6th ed. TC <--- O(n!) ''' imp...
3b0db36653b5e9381a261d687b950d0f78abecdb
sghosh1991/InterviewPrepPython
/DynamicProgramming/WildcardMatch.py
2,549
4.0625
4
''' Creation Date: Jul 4, 2016 @author : Santosh Ghosh Problem Statement: Given a text and a pattern test whether the text matches the pattern. The pattern contains wildcards. Only two wild cards are there: 1) * <--- 0 or more occurance of a character 2) ? <--- 1 occurance of any character. Input: A string called te...
5002927273458dd9a7c040081147302aaf549917
sghosh1991/InterviewPrepPython
/LeetCodeProblemsEasy/463_IslandPerimeter.py
2,333
4.03125
4
''' You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't h...
cdb6a38a20336efe8615cf200359ee7242f741dd
sghosh1991/InterviewPrepPython
/Recursion/WordChain.py
350
3.765625
4
''' Creation Date: 2016-06-24 @author : Santosh Ghosh Problem Statement: Given an array of strings, find if the given strings can be chained to form a circle. A string X can be put before another string Y in circle if the last character of X is same as first character of Y. Input: Output: Logic Applied: ''' ...
800976fcad42de0fb85ccf8ff4c2aa5d751d2c12
sghosh1991/InterviewPrepPython
/LinkedLists/CloneLinkListWithRandomPointers.py
1,177
3.765625
4
class Node(): def __init__(self, val): self.val = val self.next_node = None self.random = None def clone(ll): mapping = {} runner = ll while runner is not None: mapping[runner] = Node(runner.val) runner = runner.next_node runner = ll while runner.n...
2f9907ec41c94565a282c7e323dd14c04c28eda4
sghosh1991/InterviewPrepPython
/LeetCodeProblemsMedium/17_letter_combination_phone_number.py
1,121
3.71875
4
""" https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ """ class Solution(object): def __init__(self): self.results = [] self.mappings = { 2: "abc", 3: "def", 4: "ghi", 5: "jkl", 6: "mno", 7: "pqrs...
1b085ba4d6f4b8f0014e0daa1a7c12cbcc4ae677
sghosh1991/InterviewPrepPython
/Arrays/AddOneToANumberReprAsArray.py
582
3.671875
4
""" Given a number represented as an array add one to it and resturn another array that represents the incremented number """ def incr(num): numLength = len(num) carry = 1 i = numLength-1 while i >= 0: if num[i] + carry == 10: num[i] = 0 i -= 1 else: ...
d61517621e713beb2c88b1379e15c3a6c23ce61c
sghosh1991/InterviewPrepPython
/LeetCodeProblemsEasy/682_BaseballGame.py
1,828
3.6875
4
''' You're now a baseball game point recorder. Given a list of strings, each string can be one of the 4 following types: Integer (one round's score): Directly represents the number of points you get in this round. "+" (one round's score): Represents that the points you get in this round are the sum of the last two va...
5ac54dd56d88f98d8a0877706ef05f53f0bcbec1
sghosh1991/InterviewPrepPython
/LeetCodeProblemsEasy/461_HammingDistance.py
1,254
4.15625
4
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Hints: XOR followed by count set bits. Counting set bits can be done in many ways. Lookup table in O(1). Brutoforce O(n) Brian- Kerningha...
ee985251eced81849d0faa4f722b20fd9a219d36
sghosh1991/InterviewPrepPython
/BinarySearch/MinInRotatedSortedArray.py
513
3.859375
4
''' Creation Date: 2016-06-24 @author : Santosh Ghosh Problem Statement: Input: Output: Logic Applied: ''' def find_min_rotated_sorted_array(arr): lo = 0 hi = len(arr) - 1 while ( arr[lo] > arr[hi]): mid = lo + (hi-lo)/2 if arr[mid] > arr[hi]: ...
6615f76bb10634d06bbf725ecc7f0464cdb80bf0
sghosh1991/InterviewPrepPython
/LeetCodeProblemsHard/42_trapping_rain_water.py
1,662
3.625
4
""" https://leetcode.com/problems/trapping-rain-water/description/ Idea: For each bar find how much water can there be on top of the bar Find the greatest height bar on the right side of each bar GR s.t it is greater than or equal to its own height Find the greatest height bar on the left side of each bar GL s.t it i...
b111d3923918fb68818ac3fef827982984a11810
Klariss/PyCharm
/main.py
1,200
3.71875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # import geometry # import sys # from PyQt4 import QtGui # def main(): # # app = QtGui.QApplication(sys.argv) # # w = QtGui.QWidget() # w.resize(250, 150) # w.move(300, 300) # w.setWindowTitle('Simple') # w.show() # # sys.exit(app.exec_()) # # # i...
142f4737b713400368ed1a41f5b6d0424b8c2ddc
dimazap/lesson2
/ask2.py
431
3.625
4
def main(): try: talk = {"Как дела?": "Хорошо!", "Что делаешь?": "Программирую", "Что будешь делать?": "Программировать"} while True: keyinput = input("Каков твой вопрос? ") if keyinput in talk.keys(): print(talk[keyinput]) else: print("Тогда до свиданья") except(KeyboardInterrupt): print(" Пок...
011c0aa49e2684a509281c743b7efc0aaa833736
JohnConnor94/BlackJackPy
/lib/Deck.py
2,112
3.6875
4
import random from lib.Card import Card class Deck: _seeds = ("Hearts", "Diamonds", "Clubs", "Spades") _values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K") def __init__(self, jolly = False): self._cards = [Card(v, s) for s in Deck._seeds for v in Deck._values] if ...
859c36dace953d7029755af480946e77b15ea631
forum2k9/Python-Programming-for-GIS-Data-Processing
/python_scripts/Script_04.py
8,876
4.34375
4
# Script_04.py # Author: UmarYusuf.com # Date: 25/05/2022 # Topic: Conditional (Control flow) Statements if/for/while # ------------------------------ # Python supports the usual logical conditions from mathematics: # Equals: a == b # Not Equals: a != b # Less than: a < b # Less than or equal to: a <= b # Greater th...
99e5876e31defedfb6860d88cc0c3dd7c523114b
mcfaraz/CSAssignments
/CS917/Assignment1/part2.py
9,087
3.984375
4
""" This module contains classes that form the basis for part 2 of the assignment Refer the the coursework assignment for instructions on how to complete this part. """ import math import statistics class Point: """""" def __init__(self, x, y): self.x = x self.y = y def get_x(self):...
3ff9c15625f19059eaa337b5513a315ad74e6a95
FoFabien/Compiler-wip-
/prototype.py
21,203
3.75
4
# -*- coding: utf-8 -*- import time import re def is_number(str): if str == "true" or str == "false": return True try: float(str) return True except: return False def is_name(str): return re.match("\w+", str) def peek(stack): return stack[-1] if stack else None d...
f98948f98cb32bff142c1f03bb19c57229107d56
castrolimoeiro/Uri-exercise
/1048 AUMENTO SALARIO.py
1,127
3.6875
4
# -*- coding: utf-8 -*- salario = float(input()) if 0 < salario <= 400: aumento = salario * 0.15 novo_salario = salario + aumento print(f'Novo salario: {novo_salario:.2f}\n' f'Reajuste ganho: {aumento:.2f}\n' f'Em percentual: 15 %') elif 400 < salario <= 800: aumento = salario * 0....
512c05a96ba8fa08afedd507efae5b2615358bd1
chenyk1990/useful-utilities
/projects/mdb/rsf/school/pydemo.py
1,693
3.71875
4
# ------------------------------------------------------------ # strings a='StPetersburg' len(a) a[0] a[4:7] b=a+' '+'workshop' print b c=b+2014 c=b+' '+str(2014) print c # ------------------------------------------------------------ # lists d = ['StPetersburg', 'workshop'] len(d) print d[0] print d[1] d.append('...
301ac424e3bd924088d24ce87e459c5433d5d02f
dugweb/pythonCourse
/week5/unittests.py
346
3.578125
4
""" Implement one unit tests for "add(a, b)" function, that validates the resulting value of its execution. """ def add(a, b): return a + b import unittest class AssignmentTestCase(unittest.TestCase): def test_add(self): self.assertEqual(add(3,4), 7) self.assertEqual(add(9383, -38...
a971bf170042b76f83d0d555d12b91a26afef5d1
dugweb/pythonCourse
/week5/lineamount.py
263
3.625
4
""" Write a function, that receives a path to a text file as parameter, and returns the amount of lines that text file has. Example: count_lines('test-file.txt') # 10 """ def count_lines(filepath): f = open(filepath, 'r') return len(f.readlines())
0f518fdc83fa31c118f769a0cd2d5435d6cb8121
dugweb/pythonCourse
/week3/linkedlist.py
6,007
4.03125
4
""" A Linked List (https://en.wikipedia.org/wiki/Linked_list) is a linear data structure. You can think of it as an implementation of a regular Python List. Using Object Oriented programming, build a simple Linked List that shares the same interface with Python Lists: l = LinkedList() l.append(2) l.count...
0f374e6a5fcd19ef127d77714c091c691ade3376
lingxiaomeng/capstone
/src/cal.py
543
3.515625
4
from math import cos, sin ps2_radians = 0.559347 x2 = -0.03884 + 0.5 * cos(ps2_radians) + 0.5 * sin(ps2_radians) y2 = 4.08117 + 0.5 * sin(ps2_radians) - 0.5 * cos(ps2_radians) ps3_radians = 0.5759972 x3 = 2.5153 + 0.5 * cos(ps3_radians) - 0.5 * sin(ps3_radians) y3 = -0.448662 + 0.5 * sin(ps3_radians) + 0.5 * cos(ps3_ra...
fe8beb0411d757f9a4ed0737f75838ed51de4e84
Noahigh/cicitest
/select_words.py
685
3.625
4
""" 敏感词汇筛选 找出敏感词汇,并反馈 """ file_url = r'text_test\filtered.txt' st_string = [] rs = '' with open(file_url) as file_object: lines = file_object.readlines() for line in lines: rs += line if('\n' in rs): st_string.append(rs.rstrip()) rs = '' print(st_string) '''单个词的判断''' abc = input('P...
47c4914dec8ec981ab011fe76749da942879e8db
RenanLeviathan-zz/AlgoritmoPrim
/src/plot.py
1,052
3.609375
4
''' Created on 12 de nov de 2017 @author: Israël & Renan ''' from tkinter import * class Plot: def __init__(self,edges,pos): self.pos=[] self.pos=pos self.edges=[] self.edges=edges def plot(self,title): master=Tk() widget1 = Frame(master,width=600,height=500) widget1.pack() canvas=C...
bb2b3696c94c4dc772fd43e3bd99168ce0f05762
oriel975/orielwork
/equtaions.py
1,791
3.578125
4
# -*- coding: utf-8 -*- def XtimesY(x,y): if x <= 0: return 0.0 return exponent(y*Ln(x)) def myfactorial(x): fac = 1 i = 1 while i <= x: fac = fac * i i = i + 1 return fac def mypow(x,y): ans = 1 for n in range(y): ans=ans*x # print ("mypow",ans)...
8a5ef825cde9711d61e0385faaa44742e7987eb8
Annhakobyan/Classes
/Homework7))/main.py
1,100
4
4
# list1 = ["M", "na", "i", "Ke"] # list2 = ["y", "me", "s", "lly"] # print(list1[0]+list2[0] + " " + list1[1]+list2[1]+ " " + list1[2]+list2[2]+ " " +list1[3]+list2[3]) #Given a Python list of numbers. Turn every item of a list into its square # lucky_numbers = [1, 7, 34, 8, 45] # for i in range...
99a22199e4a4fc502f1227e239e6d552c4880b91
hamzaca/Chess_ReinforcementLearning
/chess/Game.py
1,560
3.59375
4
from chess.Grid_Pieces import Grid from chess.Player import Player import numpy as np class Game(): def __init__(self, color_choice): """ color_choice contain three possible outcomes, either black, white or random """ self.color_choice = color_choice.replace(" ", "") # if method is random...
150ea09c90f114ffe9916a68ba389d44ff22c5d1
quarkgluant/exercism
/python/hangman/hangman.py
1,111
3.53125
4
# Game status categories # Change the values as you see fit STATUS_WIN = "win" STATUS_LOSE = "lose" STATUS_ONGOING = "ongoing" class Hangman(object): def __init__(self, word): self.remaining_guesses = 9 self.status = STATUS_ONGOING self.word = word self.mask = list('_' * len(word))...
4a5e0a460a243d04917209bfa0533971bd8573dd
quarkgluant/exercism
/python/robot-name/robot_name.py
536
3.515625
4
from random import choices, seed from string import ascii_uppercase, digits class Robot(object): already_used_names = [] def __init__(self): seed() self.name = self._rename() def _rename(self): self.name = ''.join(choices(ascii_uppercase, k=2) + choices(digits, k=3)) if se...
5dff5131b0fe2d91ee73e049ec6aeeea454167b0
okayu1015/ci-program
/2014-1.py
188
3.546875
4
x = 10 y = 10 def A(d): ans = (x / d + 1) * (y / d + 1) return int(ans) print(A(1)) ans = 0 d = 1 for x in range(0,11): for y in range(0,11): ans += 1 / d print(ans)
6e5d63596c7d370b7ca2f5840ea6f25ce4ad8f50
okayu1015/ci-program
/2016-2.py
389
3.6875
4
data = {"a":0, "b":1, "c":2, "d":3, "e":4, "f":5, "g":6, "h":7} #10進数をn進数へ def change(i, n): if (int(i / n)): return change(int(i/n), n)+str(i%n) return str(i%n) #n進数を10進数へ def change_to_10(i, n): x = 0 for j in range(1, len(i)+1): x += int(data[str(i[-j])]) * (n ** (j-1)) return x...
69c002b9ab81cd43fb0ec2830f7e15a16ca556ab
ava11235/machineLearning
/nlp/test.py
811
3.765625
4
import pickle class Bar(object): def __init__(self, var1=1, var2='x'): self.var1 = var1 self.var2 = var2 def __repr__(self): return f'Bar {self.var1} - {self.var2}' class Foo(object): def __init__(self, var3=3): self.var3 = var3 self.bar = Bar(2,'y') def prin...
1c2e009c89ec7ba0933fcf3e10b129f8b8f7b213
neuralmax/parametric-animation
/class2/2miniDrawClr.py
1,156
3.671875
4
# load modules import pygame, sys from random import randint from pygame.locals import * # start game engine pygame.init() # open window screen=pygame.display.set_mode((500, 400), 0, 32) # rename window pygame.display.set_caption('Hello world!') # paint window black color=(red,green,blue) values:0-255 screen.fill((0,0,...
dc5582429feceb574971638993a62de94562738f
attaebra/Project-Euler
/Euler2.py
311
3.671875
4
def getFibonnaci(): yield 0 a, b = 0, 1 while True: yield b print("The value is: %d" % b) b = a + b a = b - a values = [] for num in getFibonnaci(): if num > 4000000: break values.append(num) sum = 0 for value in values: if (value%2 == 0): sum += value print(sum)
f772e658fb9d5957854ac12050e31ed0552b3e32
jedahan/study
/balanced-tree.py
444
3.609375
4
import math class unbalanced: tree = list() def add(self,data): self.tree.append(data) def __str__(self): s = "" max_depth = math.log(len(self.tree),2) i = 0 while i < max_depth: for j in math.log(i,2): s = s + " "*2*(max_depth - j) ...
8bfdc70ad52e4ed6f47694a3a897ba90d93fe040
jedahan/study
/red-black-tree.py
1,050
3.8125
4
class node: data = None left = None right = None color = "Black" def __init__(self, data): self.data = data def __str__(self): return "{} {} {}".format(self.left or "", self.data, self.right or "") class rbtree: root = node(None) def __str__(self): return str(...
e55c52f0e7ad35282834f9ceb926eb4273c32683
Aurales/DataStructuresHomework
/Data Structures/Lab 01/Lab01ReadingFiles_KyleMunoz.py
452
3.875
4
#Kyle Munoz #Create a program that ask for input of a text files and produces a text file but now with lines numbers. def main(): file = input("Please enter the name of a text file: ") modfile = open(file, "r") filelines = modfile.readlines() linenumber = 1 modfile.close() modfile = open(file, "...
41df50dd1f20e926992b910468b7c44859377dfe
Aurales/DataStructuresHomework
/Data Structures/Lab 04/Lab04A_KyleMunoz.py
367
4.1875
4
#Kyle Munoz #Collatz Conjecture Recursively def CollatzConjecture(n, c = 0): if n == 1: print("Steps Taken: ",c) elif n % 2==0: return CollatzConjecture(n/2, c + 1) else: return CollatzConjecture(((n * 3) + 1), c + 1) def main(): x = int(input("What number would you like t...
736b387e21f6927a74aedffd1580eb89d92a4f06
feyfey27/python
/age_calculator.py
669
4.25
4
from datetime import datetime, date def check_birthdate(year, month, day): today = datetime.now() birthdate = datetime(year, month, day) if birthdate > today: return False else: return True def calculate_age(year,month,day): today = datetime.now() birthdate = datetime(year, month, day) age = today - birt...
ccd8a8ee40b3fd69ab77c0b22f51f1526939e4ae
LordBao666/MITLecture6.0001_Introduction_To_CS_Programing_In_Python
/finger_exercise/4functions_scoping_and_abstraction/string_occur_in_the_other(chapter4.1.1).py
442
4.09375
4
""" @Author : Lord_Bao @Date : 2021/3/5 """ """ Finger exercise: Write a function isIn that accepts two strings as arguments and returns True if either string occurs anywhere in the other, and False otherwise. Hint: you might want to use the built-in str operation in. """ def isIn(s1, s2): return s1 in s2 o...
c3b219f1fbd6299291f5772de19be8cef695c4de
LordBao666/MITLecture6.0001_Introduction_To_CS_Programing_In_Python
/practice/5structured_types_mutabillity_and_higher_order_functions/map_and_lambda_expression(chapter5,4).py
145
3.59375
4
""" @Author : Lord_Bao @Date : 2021/3/6 """ L = [] for i in map(lambda x, y: x ** y, [1, 2, 3, 4], [3, 2, 1, 0]): L.append(i) print(L)
f8954917858e5d48f8cfb29590b69cfee91c922a
aindrila2412/DSA-1
/Booking.com/atoi_string_to_integer.py
2,316
3.640625
4
""" mplement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this...
1049a329ecc51e9c7eb3c3edf05c2a0a13caa19d
aindrila2412/DSA-1
/BFS/words_search.py
1,667
3.90625
4
# After catching your classroom students cheating before, you realize # your students are getting craftier and hiding words in 2D grids of letters. # The word may start anywhere in the grid, and consecutive letters can be # either immediately below or immediately to the right of the previous letter. # Given a grid and...
427579387587762c67f2ceca56b3055d86c8e752
aindrila2412/DSA-1
/designPattern/abstract_factory.py
3,675
4.375
4
from abc import ABCMeta, abstractmethod, abstractstaticmethod """ Imagine that you’re creating a furniture shop simulator. Your code consists of classes that represent: A family of related products, say: Chair + Sofa + CoffeeTable. Several variants of this family. For example, products Chair + Sofa + CoffeeTable are...
0d56b4a82a65402cfdc5b366935ab07d615203f2
aindrila2412/DSA-1
/Booking.com/tree_right_child.py
1,282
4.03125
4
""" public class Node { public Node[] Children; public Node Right; }  Each node represents an element of a tree and specifies a list of immediate children.  The 'Children' property lists all children (in order) but the 'Right' property is set to null. Suppose you are given the root of a fully populated tree (i.e. a N...
84f9b09013e04222ed26dfc6af70fcc91dcf2324
aindrila2412/DSA-1
/Booking.com/power_set.py
1,609
4.1875
4
""" Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] Example 2: Input: nums = [0] Output: [[],[0]] ...
c1650540ee3e62d46d75fccf326c9d64215f8702
aindrila2412/DSA-1
/Stack/nearest_greater_to_left.py
1,555
3.9375
4
class Stack: def __init__(self): self.stack = [] def is_empty(self): return len(self.stack) == 0 def push(self, elm): self.stack.append(elm) def top(self): if self.is_empty(): return None return self.stack[len(self.stack) - 1] def pop(self): ...
04ae665f3abdc0aa9a909d1a1dc01f0b5df0c8b1
aindrila2412/DSA-1
/Recursion/print_height_of_binary_tree.py
630
4.09375
4
# print height of binary tree """ 1 | | 2 3 | | 4 5 | 6 | 7 """ class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None def compute_height(bt: BinaryTree): if bt is None: return 0 return 1 + max(compute_height(bt.left), comp...
13d4d03d5c948c50f6e48ee10760f77af45f3ec5
aindrila2412/DSA-1
/Stack/nearest_smaller_to_left.py
1,247
3.90625
4
class Stack: def __init__(self): self.stack = [] def push(self, elm): self.stack.append(elm) def is_empty(self): return len(self.stack) == 0 def pop(self): if self.is_empty(): raise Exception("Stack is empty.") return self.stack.pop() def top(s...
2191229b4f15a4dc11a08a5fdf1ec9f1a71129e9
aindrila2412/DSA-1
/dynamicProgramming/unbounded_knapsack/unbounded_knapsack.py
1,366
4.09375
4
""" Given a knapsack weight W and a set of n items with certain value vali and weight wti, we need to calculate the maximum amount that could make up this quantity exactly. This is different from classical Knapsack problem, here we are allowed to use unlimited number of instances of an item. Examples: Input : W = 100 ...
b77cdbe352caec79714a00d9de8536ecb1bf15a6
aindrila2412/DSA-1
/Recursion/reverse_a_stack.py
1,350
4.25
4
""" Reverse a Stack in O(1) space using Recursion. Example 1 Input: st = [1, 5, 3, 2, 4] Output:[4, 2, 3, 5, 1] Explanation: After reversing the stack [1, 5, 3, 2, 4] becomes [4, 2, 3, 5, 1]. Example 2 Input: st = [5, 17, 100, 11] Output: [11, 100, 17, 5] Explanation: After reversing the stack [5, 17, 100, 11] becom...
347f75d25348df7b96e9bb1632eea6c49aed52be
aindrila2412/DSA-1
/designPattern/builder_pattern.py
2,782
3.703125
4
""" https://sbcode.net/python/builder/ """ from abc import ABCMeta, abstractmethod class IHouseBuilder(metaclass=ABCMeta): @staticmethod @abstractmethod def set_building_type(building_type): "Building Type" @staticmethod @abstractmethod def set_wall_material(wall_material): "W...
391ce6e49583edf602e8dca5690384ca5e614bfe
aindrila2412/DSA-1
/Recursion/ways_to_climb_stairs.py
1,342
4.125
4
""" Given a staircase of n steps and a set of possible steps that we can climb at a time named possibleSteps, create a function that returns the number of ways a person can reach to the top of staircase. Example: Input: n = 10 possibleSteps = [2,4,5,8] Output: 11 Explanation: [2,2,...
03eaa82c091996233aece88866bdf83c04b43d0a
aindrila2412/DSA-1
/crackingTheCodingInterview/ArrayAndStrings/largest_number_at_least_twice_of_others.py
1,445
4.3125
4
""" You are given an integer array nums where the largest integer is unique. Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise. Example 1: Input: nums = [3,6,1,0] Output: 1 Expla...
63a978b9e6d02db93ae26a514497834422f61e0b
marzan-666/Learn-Python-Giraffe-Academy
/WhileLoop.py
84
3.75
4
i=1 while i <= 10: print(i) i += 1 # i= i+1 print("Done with loop")
1fdd6075771cd4e7a14bf39da34286f58febb8cb
sourajeetmohanty/Disease-Reporting-System
/disdata/projections/ODESolver.py
1,173
3.65625
4
import numpy as np class ODESolver: """ODESolver superclass Any classes inheriting from this superclass must implement advance() method. """ def __init__(self, f): self.f = f def advance(self): """Advance solution one time step.""" raise NotImplementedError ...
660e974af08881430e7e669d534976b5f2a01b63
SaturdayGenfo/quines
/python_quine.py
477
3.78125
4
def escape(s): x = '' for c in s: if c == '\n': x += '\\n' elif c == '\\': x += '\\\\' else: x+= c return x s = "def escape(s):\n x = ''\n for c in s:\n if c == '\\n':\n x += '\\\\n'\n elif c == '\\\\':\n ...
9bb56f95c93a03afdd983e623f94dad18e526228
alicetientran/CodeWithTienAndHieu
/1-introduction/Task1-tien.py
914
4.3125
4
""" Task: Ask the user for a number Tell the user if the number is odd or even Hint: use % operator Extras: If the number is a multiple of 3, print "Third time's a charm" Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If {check} divides e...
b24e15f6714bd51c24148ecc514362f850623233
houtan1/Python_Data_Cleaner
/helloworld.py
888
4.25
4
# run with python helloworld.py # print("hello world") # tab delimited text dataset downloaded from https://doi.pangaea.de/10.1594/PANGAEA.885775 as Doering-etal_2018.tab # let's read in that data file = open("data/Doering-etal_2018.tab", "r") line = file.readlines() # print(line[28]) # print(len(line)) for x in rang...
4cacecee881f24831064c88fc0e61f7a97235358
571031767/py
/index.py
398
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- print(100+200+300) print('hello word') print(''' nihao nibuhao ni hao bu hao ''') a= input('请输入一个数值') if int(a) > 50: print('您所输入的数值是'+a+'ta 大于50') else: print('您所输入的数值是'+a+'ta 不大于50') name = input('请输入您的姓名') print('你好,'+name+'欢迎学习python')
821debae535321467b498e0782cca29963648ecf
tzwyf/Learning
/python/moudle/test_mode/装饰器.py
4,368
3.546875
4
# -*- coding: cp936 -*- # װ # # LEGB L > E > G > B # L : local ڲ # E : enclosing ڲǶ֮ # G : global ȫ # B : build-in # Ҳв # Pythonհ # հĸ # ڲжenclosingı # ӣ def func(var) : def in_func() : return var return in_func f = func(89) print f # <function in_func at 0x03081AF0> print f() # 89 # ñհǾͿԵõ...
a583763a983846a55d86f58a5ac5146e40d273ce
tzwyf/Learning
/python/学习笔记/输入输出.py
883
4.5
4
# 用户输入 def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input("Enter text: ") if(is_palindrome(something)): print("Yes, it is a palindrome") else: print("No,it is not a palindrome") #pickle 模块 #Python 提供了一个叫做 p...
dd54ec0f8a277ef9eae6ddcdcc66dfea7f16a2ab
Iboatwright/mod10homework
/speed_of_sound.py
3,299
4.375
4
# speed_of_sound.py # Exercise selected: Chapter 11 program 7 # Name of program: Speed of Sound # Description of program: This program displays a menu allowing the user # to select air, water, or steel. After the user has made a selection, # he or she should be asked to enter the number of seconds the sound # wil...
b70ad2a0f68592c0d07eded8bcacf1b288607f52
morganjwilliams/pyrolite
/pyrolite/util/plot/transform.py
3,237
3.546875
4
""" Transformation utilites for matplotlib. """ import numpy as np from ...comp.codata import close from ..log import Handle logger = Handle(__name__) def affine_transform(mtx=np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])): """ Construct a function which will perform a 2D affine transform based o...
e7f5f1d44fa87dc53f3f65a59a276c1f47b7177f
TimKindervatter/Intro-to-Data-Science
/Intro_to_Pandas.py
3,474
3.53125
4
#%% import pandas as pd #%% [markdown] #$\alpha + \frac{\beta}{\gamma} - \delta = 1$ #%% #Specifying which columns to scrape from the database u_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code'] #Reading in user data from the database users = pd.read_csv( 'http://files.grouplens.org/datasets/movielen...
adde8bcdf70592e681d642befa152e0737ffc754
marat-biriushev/PY4E
/py.py
2,071
4.21875
4
#!/usr/bin/python3 def f(x, y = 1): """ Returns x * y :param x: int first integer to be added. :param y: int second integer to be added (Not requared, 1 by default). :return : int multiplication of x and y. """ return x * y x = 5 #print(f(2)) #a = int(input('type a number')) #b = int(input(...
0f71e4012a72306a5c67cae91d404a2229d641c4
marat-biriushev/PY4E
/ex_7_1.py
2,122
4.625
5
#!/usr/bin/python3 ''' Exercise 1: Write a program to read through a file and print the contents of the file (line by line) all in upper case.''' fname = input('Enter a filename: ') fhand = open(fname) for line in fhand: line = line.upper() line = line.rstrip() print(line) #################################...
7e9e66ea04d095b48f72708dc586cdbe53ba0054
Rodrigs22/ExerciciosCursoEmvideo
/ex051.py
559
3.859375
4
#Meu algoritimo ''' termo = int(input('Digite o prmeiro termo da PA: ')) razao = int(input('Digite a razao da PA: ')) quantidade = int(input('Digite quantos termos quer ver: ')) ultimo = termo + (quantidade-1)*razao ultimo = ultimo + 1 for c in range(termo, ultimo, +razao): print(c) print('Fim') ''' #Algoritimo do ...
889e82e3ca53f9e78d1ed1aaf2573b2fc32ab599
Rodrigs22/ExerciciosCursoEmvideo
/PycharmProjects/PythonexExercícios/ex037.py
547
4.1875
4
numero = int(input('digite um numero inteiro para transformar: ')) c1 = int(input('''[ 1 ] converter para BINÁRIO [ 2 ] converter para OCTAL [ 3 ] converter para HEXADECIMAL Escolha: ''')) if c1 == 1: print('O numero {} convertido em binário é, {}.'.format(numero, bin(numero)[2:])) elif c1 == 2: print('o Numero...
098c87461e6bacc9dcd308c28a2c44aaa34216f6
Rodrigs22/ExerciciosCursoEmvideo
/cod/ex007.py
371
3.515625
4
cores = {'limpa': '\033[m', 'azul': '\033[34m', 'verde': '\033[32m',} nome = input('Digite o nome do aluno: ') n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) media = (n1 + n2) / 2 print('A média do aluno {}{}{} é {}{}{}.'.format(cores['azul'], nome, cores['l...
755ed9cf53edceab9b4e32b8d5e8868198da556e
Rodrigs22/ExerciciosCursoEmvideo
/cod/ex046.py
298
3.625
4
from time import sleep ''' from time import sleep time = int(input('Digite o valor da contagem regressiva: ')) for c in range(time, 0, -1): sleep(1) print(c) print('boom, poooow') ''' #forma do guanabara for cont in range(10, -1, -1): print(cont) sleep(1) print('Bum, boom, pooow ')
84d1d738af4871eb12a0e323f4e5bb6f7f4fb9d7
Rodrigs22/ExerciciosCursoEmvideo
/PycharmProjects/PythonexExercícios/cod/ex039.py
1,507
3.84375
4
from time import sleep from datetime import date # cores cores = {'limpa': '\033[m', 'ciano': '\033[36m', 'amarelo': '\033[33m', 'vermelho': '\033[31m', 'verde': '\033[32m'} # estética print(cores['ciano']) print('-=' * 22) print(cores['limpa']) print(cores['amarelo']) print('DESCUBR...
4ac94ba83e6e1d85bbc3c9f426faa03a25d5f13b
Rodrigs22/ExerciciosCursoEmvideo
/cod/ex045.py
1,812
3.53125
4
from random import choice from time import sleep # cores cores = {'limpa': '\033[m', 'ciano': '\033[36m', 'verde': '\033[32m'} # estética print(cores['ciano']) print('-=' * 22) print(cores['limpa']) print(cores['verde']) print(' VAMOS JOGAR JOKENPO') print('PROMETO NÃO TRAPACEAR!') print(cores['limpa'...
a35a5fd89c35096c2e314451fa85db9b55d8e0f5
Rodrigs22/ExerciciosCursoEmvideo
/cod/ex061.py
292
3.921875
4
pritermo = int(input('digite o primeiro termo: ')) razao = int(input('Digite o segundo termo: ')) quanttermos = int(input('Digite quantos termos deseja ver: ')) cont = 1 while cont <= quanttermos: print('{} --> '.format(pritermo), end='') pritermo += razao cont += 1 print('fim')
13493f66892b1506b94c66b9331b1aba0ff9f54a
Rodrigs22/ExerciciosCursoEmvideo
/ex016.py
160
3.625
4
import math n = float(input('Digite um numero com 3 casas decimais: ')) print('\033[34m') print('O numero inteiro é {}.'.format(math.trunc(n))) print('\033[m')
0a4f623d65cf58d087e857d09974804b4feb3a26
AWarno/CodeHateChallenge
/src/augment/eda_nlp/code/augment.py
2,885
3.5
4
# Easy data augmentation techniques for text classification # Jason Wei and Kai Zou from src.augment.eda_nlp.code.eda import * #arguments to be parsed from command line import argparse ap = argparse.ArgumentParser() ap.add_argument("--input", required=True, type=str, help="input file of unaugmented data") ap.add_ar...
31b20b18b7c2c4858113df39e682cdd04dff790f
clickok/Code-Snippets
/Python-Programming/digraph.py
6,662
3.71875
4
""" A relatively generic implementation of a directed graph in Python """ class GraphNode: """ A node in the graph, with its parents & children stored as a set of keys, and the ability to initialize with a set of keys/values as a dict. """ def __init__(self, **kwargs): self.__dict__['childr...