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
476dddd1cd9422027cc144df149f423f79cf4bea
AK-1121/code_extraction
/python/python_23686.py
112
3.78125
4
# Python program that tells you the slope of a line def slope(x1, y1, x2, y2): return (y1 - y2) / (x1 - x2)
1076b7c138e0bbfde4a6a75d0fb2d02bd8098b76
AK-1121/code_extraction
/python/python_22401.py
134
3.8125
4
# Python dict print One per line with Key in each line for k, v in dict.iteritems(): for item in v: print item, k
b794117908cc5a5fdf872d09dc410759a700196e
AK-1121/code_extraction
/python/python_1889.py
193
3.828125
4
# How many items in a dictionary share the same value in Python import itertools x = {"a": 600, "b": 75, "c": 75, "d": 90} [(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]
c88b7692f63fb2293176c795e0c836546cc61cbf
AK-1121/code_extraction
/python/python_6729.py
135
3.953125
4
# How to find and split a string by repeated characters? import itertools [''.join(value) for key, value in itertools.groupby(my_str)]
580f93b43a77ab44a2a1db92c44afec1a4f891d8
AK-1121/code_extraction
/python/python_8360.py
100
3.578125
4
# How can I re-order the values of a dictionary in python? dict = { 'a': [ "hello", "hey", "hi" ] }
1344c1b2ae8a0eb3790ece2b56558107650bd8e4
AK-1121/code_extraction
/python/python_16516.py
139
3.765625
4
# Get values in Python dictionary from list of keys >>> d = {'a':1, 'b':2 , 'c': 3} >>> [d[k] for k in ['a','b']] [1, 2]
c752436b645b522e14f3754c6b62b4e28cdbb84a
AK-1121/code_extraction
/python/python_7488.py
118
3.59375
4
# If clause in regular Python for-loop for elem in (item for item in my_list if not (item=='')): #Do something...
b9a4669298be2e54294d5e561730c87213901b3c
AK-1121/code_extraction
/python/python_15473.py
184
4.09375
4
# How do I capture words wrapped in parentheses with a regex in Python? >>> print re.search("(\w+) vs (\w+) \(\s?(\w+)",my_string).groups() (u'Hibbert', u'Bosh', u'Chalmers')
72198b39cfa9f4a50e01925e36c0e31705076cc1
AK-1121/code_extraction
/python/python_11332.py
166
3.640625
4
# Print a string as hex bytes? >>> s = "Hello world !!" >>> ":".join("{:02x}".format(ord(c)) for c in s) '48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21
548499cad3c1943ee6dfd5b217896a3d8980ebf1
AK-1121/code_extraction
/python/python_810.py
178
3.53125
4
# How do we remove all non-numeric characters from a string in Python? >>> import re >>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd") '987978098098098'
a44ff01fbfad42e5ad4c3832fbf12275761f2752
AK-1121/code_extraction
/python/python_6280.py
118
3.828125
4
# Python: How to remove all duplicate items from a list for i in mylist: if i not in newlist: newlist.append(i)
a40fe3f3c05f44275f813b77dd30d30b52d9ce51
AK-1121/code_extraction
/python/python_11911.py
141
3.546875
4
# Quickly applying string operations in a pandas DataFrame splits = x['name'].split() df['first'] = splits.str[0] df['last'] = splits.str[1]
147f61e09873b1a06d43ac89e62dd911f2255358
AK-1121/code_extraction
/python/python_12526.py
115
3.515625
4
# Python list iteration and deletion cpt1 = sum(1 for x in liste if x != 2) cpt2 = sum(1 for x in liste if x == 2)
7ad81539ef1f7c2a96eda52d75946e02bf6ef0ff
AK-1121/code_extraction
/python/python_19506.py
261
3.6875
4
# How to turn multiple lists into a list of sublists where each sublist is made up of the same index items across all lists? >>> [list(x) for x in zip(lsta, lstb, lstc)] [['a', 'a', 'a'], ['b', 'b', 'b'], ['c', 'c', 'c'], ['d', 'd', 'd']] >>>
4c995afb28c05267673a570e2b7db969e4753119
AK-1121/code_extraction
/python/python_27527.py
179
3.59375
4
# Python - How to ensure all lengths of elements in a nested list are the same? def evenlengthchecker(nestedlist): a = [len(i) for i in nestedlist] return len(set(a)) ==1
6b63ae2af00ca8f44e2db16e6de01edfc9d93204
AK-1121/code_extraction
/python/python_22105.py
138
3.5625
4
# How to compare two timezones in python? from datetime import datetime today = datetime.today() b.utcoffset(today) == c.utcoffset(today)
35a0b2ff6bac17344addaf96bc1be0ca15a08161
AK-1121/code_extraction
/python/python_9812.py
134
3.6875
4
# Find length of 2D array Python numrows = len(input) # 3 rows in your example numcols = len(input[0]) # 2 columns in your example
5b5d6d3d45147d2580854262e451114d5057b774
AK-1121/code_extraction
/python/python_4038.py
152
3.578125
4
# Python - extracting a list of sub strings >>> import re >>> re.findall("{{(.*?)}}", "this {{is}} a sample {{text}}") ['is', 'text']
0d66f830a27373ca25b591cfaee034782d8a68f9
AK-1121/code_extraction
/python/python_16345.py
197
3.78125
4
# Count of a given item in a particular position across sublists in a list a = [[(1, 2), (2, 1)], [(1, 2), (1, 2)], [(2, 3), (2, 2)]] item = (1,2) count = [sublist[0] for sublist in a].count(item)
78b2c424f665f1102bf6c03717acfad82bcae5cc
AK-1121/code_extraction
/python/python_23709.py
127
3.53125
4
# Possible to extract a List from a Dictionary of Lists in Python? >>> [v[2] for v in dictionary1.values()] [3, 8, 4]
2e6df9b4398fb70a7ffcee5946a46dbd3760e2b8
AK-1121/code_extraction
/python/python_10090.py
130
3.515625
4
# Python creating a list with itertools.product? new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]
41aa661021a9cdc427acf900aa3b113dd9148175
AK-1121/code_extraction
/python/python_27233.py
153
3.859375
4
# how to search and print dictionary with python? for fruit, colors in fruitdict.items(): print('{} have {} color.'.format(fruit, ' '.join(colors)))
1c7dba4975d98b94c818f19407521072526835e7
AK-1121/code_extraction
/python/python_13725.py
119
3.578125
4
# python - find index postion in list based of partial string indices = [i for i, s in enumerate(mylist) if 'aa' in s]
9541deba98d2ac5e7aa48210bc3c00ec3cccc14e
AK-1121/code_extraction
/python/python_20777.py
132
3.796875
4
# How to check if number is integer number, with good precision? def is_square(x): s = int(sqrt(x) + 0.5) return s * s == x
c3f56f9899499a6d739b35609510ad2fd1ac2f3f
AK-1121/code_extraction
/python/python_28511.py
159
4.125
4
# How do I check if a string with a user given input is equal to a certain letter/ word in Python while (userin!="c" or low == high): userin = raw_input()
055d3ddebde5f37f0be08e61e5d92cf8ad404085
AK-1121/code_extraction
/python/python_4982.py
214
3.90625
4
# How to turn a string of letters into 3 letter words in Python 2.7.1 >>> a = "aaabbbcccdddeeefffggg" >>> [a[i:i+3] for i in range(0, len(a), 3)] ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg']
a2138590d660f64db3986ecceddd12f2aa468ada
AK-1121/code_extraction
/python/python_17964.py
158
3.65625
4
# read a file into python and remove values import re with open('filename', 'r') as f: list1 = [re.split('[(#]+', line.strip())[0].split() for line in f]
579335e8b69662eb02c7b03955176d3a7092c406
AK-1121/code_extraction
/python/python_25897.py
142
3.65625
4
# Can't show the key along with the value (dict) in Python chris = {'name': 'chris', 'avg': (test1['chris']+test2['chris']+test3['chris'])/3}
3baafdb2f02476dabfe5a2fef5497e7339fde92e
AK-1121/code_extraction
/python/python_7542.py
244
3.640625
4
# Using append() on transient anonymous lists inside of a list comprehension in Python >>> mylist = [['A;B', 'C'], ['D;E', 'F']] >>> [first.split(';') + [second] for first, second in mylist] [['A', 'B', 'C'], ['D', 'E', 'F']]
c0d5a3602f4eb79c2b43e626893c6247407b876b
AK-1121/code_extraction
/python/python_5763.py
106
4.46875
4
# Determining whether an value is a whole number in Python if x % 3 == 0: print 'x is divisible by 3'
378ca5bd0cba18a6fc426830d426a9da86b9d8a8
AK-1121/code_extraction
/python/python_10377.py
173
3.546875
4
# Python comma delimiting a text file with open('infile.txt') as infile, open('outfile.txt', 'w') as outfile: outfile.write(', '.join(infile.read().split('\n')) + '\n')
b681468218d7c401794d2b647c44143f29def2c7
AK-1121/code_extraction
/python/python_20575.py
159
3.828125
4
# nested lists and for loops program in python gives me a crazy result for index in range(len(listOne)): listThree.append((listOne[index],listTwo[index]))
3ac026d604620fde8e9c43fd5d3a3927c0fbbe0b
AK-1121/code_extraction
/python/python_1413.py
65
3.5
4
# Convert string / character to integer in python chr(ord(ch)+2)
16841661256962d06c4ed690fad2a2bf36bd7e48
AK-1121/code_extraction
/python/python_11305.py
239
3.71875
4
# Generate arrays that contain every combination of elements from an array >>> from itertools import combinations >>> list(combinations('ABCD', 2)) [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
9b60a2532870799654cd3ac4270073524b0c935a
AK-1121/code_extraction
/python/python_6006.py
156
3.59375
4
# In list of dicts, match dict based on one key/value? fields = ('name', 'school') match_found = any(all(x[f]==example[f] for f in fields) for x in myList)
d53208c80311d53fb840a9251357b2aca4858ac9
AK-1121/code_extraction
/python/python_21646.py
172
3.90625
4
# how to check whether a string A is contained into a longer string B for any combination of upper/lower character def checkString(a, b): return a.lower() in b.lower()
591d16c6d2897f2eb88c4e674bb724cf6397fe83
AK-1121/code_extraction
/python/python_24770.py
139
3.53125
4
# Adding spaces in elements of list(PY) def equalize_lengths(l): length = len(max(l, key=len)) return [e.ljust(length) for e in l]
fb54a3820745b1b0655c507133caa2b4e93c9646
AK-1121/code_extraction
/python/python_23285.py
99
3.515625
4
# Python 3.4.1 Print new line print('\n', even_count, ' even numbers total to ', even_sum, sep='')
444b0159c5387f71d09d0b5171787b4e6d36a73c
AK-1121/code_extraction
/python/python_18020.py
150
3.78125
4
# Python, rename a list with one of its values all_my_lists = {} #USE A DICT!!! all_my_list[listx[2]] = listx #listx[2] gives the 3rd value in listx
39cfa8c5c6723a90dcaa140d5e69d51bed4b11e6
AK-1121/code_extraction
/python/python_24967.py
121
3.546875
4
# I would like explanations on python list management optimisation, and overall, optimisation a += 3 if condition else 1
8fecdcad39c372035ef51216a7a4b9bb7ee7d63a
AK-1121/code_extraction
/python/python_7787.py
105
3.53125
4
# Convert string to ASCII value python >>> s = 'hi' >>> [ord(c) for c in s] [104, 105]
8a0a6d2153984e1230e000ae3a61a97cc740aa71
AK-1121/code_extraction
/python/python_26679.py
207
3.78125
4
# Using regular expression to catch phrases in Python >>> regex = re.compile("Who created (.*?)\?", re.I) >>> regex.search("Who created Lord of the Rings?").groups()[0] 'Lord of the Rings'
d7d60b7a4305b0dcfa39a431103cb337dfefd191
AK-1121/code_extraction
/python/python_21764.py
149
3.515625
4
# how to write contents into a file in python where one part holds a variable and other just a display statement? f.write("value of a is: %d" % (a))
625d22b61e26d16297b45175effab19759669a86
AK-1121/code_extraction
/python/python_1460.py
122
3.609375
4
# nesting python list comprehensions to construct a list of lists f = open(r"temp.txt") [[c for c in line] for line in f]
41b6edffae54c2430c509a9232f5edf73a69336e
AK-1121/code_extraction
/python/python_18977.py
141
3.78125
4
# How to convert a list into a column in python? >>> y = [1,2,3,4,5,6] >>> [[i] for i in y] [[1], [2], [3], [4], [5], [6]]
acb16498a7ffd9d530ddbe1aeeb9a569ca3470a2
AK-1121/code_extraction
/python/python_21197.py
117
3.71875
4
# String replacement using modulo in Python for raw_input? age = raw_input("Hello %s, please enter your age" % name)
74cb69dab523fb7efd2b3c073308e61d5cf40635
AK-1121/code_extraction
/python/python_16917.py
136
3.59375
4
# How to delete items on the left of value1 and on the right of value2 in a list of ints in Python? l[l.index(start): l.index(end) + 1]
494f1fb26d7ed8cfe6a446f3a1bdaf825c79c7b7
AK-1121/code_extraction
/python/python_25229.py
128
3.5
4
# I want to move a item to first index in list. How to simplify code? sorted([0,1,2,3,4,5], key=lambda x: x == 2, reverse=True)
1d5bc806fb435f6b85c866c1aa93088f1ba3edb4
AK-1121/code_extraction
/python/python_3461.py
87
3.6875
4
# Using Python's re to swap case >>> s = "AbcD" >>> s.lower() 'abcd'
046892680ee0760bff80a0385b0b8c25cf07a457
AK-1121/code_extraction
/python/python_23262.py
104
3.65625
4
# Printing every item on a new line in Python print '\n'.join([str(factorial(x)) for x in range(0, 6)])
fafd811980cf1546673b90d336d5e5a01632b099
lensvol/advcode2016
/python/day1.py
2,073
3.640625
4
# -*- coding: utf-8 -*- ''' Day 1 of the Advent of Code challenge, parts A and B ''' import sys NORTH = 'N' SOUTH = 'S' EAST = 'E' WEST = 'W' LEFT = 'L' RIGHT = 'R' MOVEMENTS = { (NORTH, LEFT): ((-1, 0), WEST), (NORTH, RIGHT): ((1, 0), EAST), (SOUTH, LEFT): ((1, 0), EAST), (SOUTH, RIGHT): ((-1, 0), WEST), (EAST, LEFT): ((0, 1), NORTH), (EAST, RIGHT): ((0, -1), SOUTH), (WEST, LEFT): ((0, -1), SOUTH), (WEST, RIGHT): ((0, 1), NORTH), } def calculate_distance(p1, p2): ''' Calculate taxicab distance between two points on a city grid. ''' x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2) def parse_path(text): ''' Calculate distance between starting position and end of the path, specified by directions. ''' parts = text.split(', ') heading = NORTH current_position = (0, 0) first_revisited = None visited = set() for part in parts: direction, steps = part[0], int(part[1:]) delta, next_heading = MOVEMENTS[(heading, direction)] # We need for _ in xrange(steps): current_position = ( current_position[0] + delta[0], current_position[1] + delta[1], ) # We need to remember our first revisited point to complete Part B # (Easter Bunny waits for us at those coordinates) if current_position in visited and first_revisited is None: first_revisited = current_position visited.add(current_position) heading = next_heading return ( calculate_distance((0, 0), current_position), calculate_distance((0, 0), first_revisited), ) if __name__ == '__main__': with open(sys.argv[1]) as fp: directions = fp.read().strip() distance_to_end, distance_to_revisited = parse_path(directions) print 'Distances\n=========' print 'First revisited point: {0}'.format(distance_to_revisited) print 'End of the path: {0}'.format(distance_to_end)
bee23ecce30ac852f84b350b7fe484a9af1ec369
vikramcse/Hackerrank
/Algorithms/Strings/Pangrams/panagram.py
256
3.671875
4
str = raw_input().strip().lower() alpha_positions = [0] * 26 flag = True for c in str: if c != " ": pos = ord(c) % 26 alpha_positions[pos] = 1 for i in alpha_positions: if not i: flag = False if flag: print "pangram" else: print "not pangram"
63f0ad6223769c03f80c5fd6e8f6d6ccef18c849
WilderSiguantay/PythonBasico
/Clase 2/Clase2.py
2,138
4.09375
4
#Esto es un comentario de una linea ''' Este es un comentario de varias lineas ''' #La funcion print se usa a menudo para imprimir variables print('Hola') #Python no tiene ningun comando para declarar variables mivariable = 0 x = 5.10 y = 'Hola Mundo' x1= 5 y2 = 'David' #Las variables incluso pueden cambiarse de tipo de datos despues de haberle establecido anteriormente. x = 5 x = 'Wilder' print(x) #Los datos de tipo string o cadena se pueden declarar utilizando comillas simples o comillas dobles. nombre = 'Wilder' nombre2 = "Wilder" print('Nombre 1: ' + nombre + " Nombre 2: " + nombre2) #podemos asignar valores a variables multiples en una misma linea x, y, z = 'Naranja', 'Amarillo', 'Rojo' #podemos asignar el mismo valor a multiples variables. x = y = z = 'Naranja' print(x," ", y," ", z) #Para combinar texto y variables print('Nombre 1: ' + nombre + " Nombre 2: " + nombre2) print(x," ", y," ", z) #Si tenemos variables de tipo numero x = 5 y = 10 #Si combinamos texto y numero y = 'Wilder' #print(x + y) #Si utilizamos el caracter "," nos permite combinar enteros y texto print(x,y) z = "lo que sea" #cadena = y + " " + str(x) + " " + z print( y + " " + str(x) + " " + z) #TIPOS DE DATOS x = 5 print(x, type(x)) y = 'Wilder' print(y, type(y)) #Esta es una variable string que luego la cambiamos a tipo int z = int("5") print(z, type(z)) #OPERADORES #operadores aritmeticos print("------------Operadores Aritméticos---------") x = 1+1 print(x) x = 1-1 print(x) x = 3**2 print(x) x = 16**(1/2) print(x) #Operadores de asignacion print('--------Operadores de Asignacion--------') x = 4 print(x) x +=2 print(x) x *=3 print(x) x /=9 print(x) #Operadores de comparacion print('--------------Operadores de comparación-----------') y = 5 > 8 print(y) x = 1 == 1 print(x) x = 1 != 1 print(x) #Operadores Lógicos print('--------Operadores Lógicos-----') y = 5 < 8 and 1 == 1 print(y) y = 5>8 or 1 == 1 print(y) y = not(1 != 1) print(y) #Funciones nativas de python x = input('Digite un valor para x: ') print(x, type(x)) print('El valor que el usuario nos ingresa es: ' + x)
7dd862e71dc7a9e1aa21bdee868db02e5fd371ae
Pikselas/word-detector
/main.py
2,136
3.703125
4
# word detector and replacer import os import tkinter as ui def Search(WORD,REPLACE,extension): print("WORD ->> "+str(WORD)+"\nREPLACER ->> "+str(REPLACE)+"\nEXTENSION ->>"+str(extension)) print("**********SUMMARY*************") contents = os.listdir("Input//") for items in contents: if items.endswith(extension): with open(("Input//"+items),'r') as file: text = file.read() if WORD in text: print("FOUND in ->>"+str(items)) Remove(items,WORD,REPLACE) print("STATUS: REPLACED") else: return False file.close() def Remove(Filename,OLD,NEW): File = open(("Input//"+Filename),'r') Contents = File.read() Contents = Contents.replace(OLD,NEW) File.close() File = open(("Output//"+Filename),'w') File.write(Contents) File.close() def Window(): window = ui.Tk() window.geometry("350x150") window.title("Detector") ui.Label(window,text = "Enter Word to be detected:").grid(row = "1",column = "0",sticky = "W") EntryWord = ui.Entry(window)#Entry detectable word EntryWord.grid(row = "1",column = "1") ui.Label(window,text = "Enter word to be replaced with:").grid(row = "2" , column = "0",sticky = "W") EntryReplace = ui.Entry(window)#replaceable word EntryReplace.grid(row = "2" , column = "1") ui.Label(window,text = "Extension:").grid(row = "3",column = "0") EntryExtension = ui.Entry(window) EntryExtension.grid(row = "3" , column = "1") ui.Button(window,text = "Scan",width = "10", height = "2",command = lambda: Search(EntryWord.get(),EntryReplace.get(),EntryExtension.get())).grid(row = "4" ,column = "1") window.mainloop() if __name__ == "__main__": try: Window() except FileExistsError: print("FILE NOT EXIST") except FileNotFoundError: print("FILE NOT FOUND") except Exception as e: print("SOMETHING WENT WRONG\nContact ARITRA and show bellow error") print(e)
ec82f694bad7211232ba662b9fc09748123d9661
jdaekwang/Algebra-
/chapter3.py
653
3.890625
4
from chapter2 import * from inspect import signature def is_commutative(f_binary,domain): i = 0 while i < len(domain): j = 0 while j < len(domain): try1=f_binary(domain[i],domain[j]) try2= f_binary(domain[j],domain[i]) if try1 != try2: return False j = j + 1 i = i + 1 return True def is_associative(f_binary,domain): i= 0 while i < len(domain): j = 0 while j < len(domain): k = 0 while k < len(domain): try1 = f_binary(domain[i],f_binary(domain[j],domain[k])) def is_binary(f):
cb34a9664bd64f3c81e23a5fb1fbda0b8d52b510
fischly/FoIP-2020
/homeworks/question4.py
1,053
3.5
4
# -*- coding: utf-8 -*- """ Homeworks - Question 4 """ # read the image img= cv2.imread('./imagesHW/hw3_road_sign_school_blurry.JPG',0) # copy the image to perform the transformations im = img.copy() # select the kernel that is used for dilation-erosion W = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)) # apply the given algorithm for i in range(10): im_d = cv2.dilate(im,W) # first dilate im_e = cv2.erode(im,W) # then erode im_h = cv2.addWeighted(im_d,0.5,im_e,0.5,0) # then add images # for every pixel perform the following test for y in range(im.shape[1]): for x in range(im.shape[0]): im[x, y] = im_d[x, y] if im[x, y] >= im_h[x, y] else im_e[x, y] # plot results fig = plt.figure(figsize=(19.20,10.80)) plt.subplot(121),plt.imshow(img,cmap='gray'), plt.title('Original') plt.subplot(122),plt.imshow(im,cmap='gray'), plt.title('Edited') plt.show() # save resulting image plt.imsave('./results/question_4_road_sign_school_blurry_filtered.jpg', im, cmap = 'gray')
c7805ecaa052f94617ccf5043eb2ae78e20ee1ba
yngz/discrete-optimisation
/knapsack/algos.py
2,024
4.09375
4
def greedy_trivial(capacity, items): """A trivial greedy algorithm for filling the knapsack. It takes items in-order until the knapsack is full. """ value = 0 weight = 0 taken = [0]*len(items) is_optimal = 0 for item in items: if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight return value, is_optimal, taken def greedy_density(capacity, items): """A simple baseline.""" value = 0 weight = 0 taken = [0]*len(items) is_optimal = 0 # Sort items by value-to-weight desc. items = sorted(items, key=lambda x: x.value / x.weight, reverse=True) for item in items: if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight return value, is_optimal, taken def dynamic_programming(capacity, items): """ The dimension of the table is (capacity + 1) x (#items + 1). Column N is the (N-1)th element in the lists (e.g. items, taken). """ is_optimal = 1 table = [[0 for c in range(len(items)+1)] for r in range(capacity+1)] for col in range(1, len(items)+1): # skip 1st col, which is always 0's wt = items[col-1].weight val = items[col-1].value for row in range(capacity+1): if wt > row: # cannot select this item table[row][col] = table[row][col-1] else: # value of not selecting it vs selecting it table[row][col] = max(table[row][col-1], val + table[row-wt][col-1]) # trace back for the solution row = capacity value = 0 taken = [0] * len(items) for col in range(len(items), 0, -1): wt = items[col-1].weight val = items[col-1].value if table[row][col] > table[row][col-1]: # the item was selected taken[col-1] = 1 row -= wt value += val return value, is_optimal, taken
6ba104c9ea7ebcaff8d1a310adaf414fc4e90ed3
ngk3/AdventOfCode2017
/Star17.py
2,155
3.890625
4
# Function used to get the total_score from a string of groupings (garbage is erased) def get_total_score(group_string): # total_count tracks the total score, count tracks the current grouping score total_score = 0 count = 0 # Go through each character in the string for gs in group_string: # If a new group is found, increase the current grouping score and total_score if gs == "{": count += 1 total_score += count # If a group is found to be closed, decrease the current grouping score elif gs == "}": count -= 1 return total_score # Function used to read the input file and erase all the garbage def read_file(file_name): # non_garbage is the input without any garbage to be returned, # garbage_count tracks the number of non-canceled characters that are within garbage, non_garbage = "" garbage_count = 0 line = open(file_name).readline() current_index = 0 in_garbage = False # Go through the string while current_index < len(line): # If canceling characters, skip the next character if line[current_index] == "!": current_index += 1 # If '<' and not in garbage, string is in garbage currently elif line[current_index] == "<" and not in_garbage: in_garbage = True # If '>' is found and in garbage, string exists garbage elif line[current_index] == ">" and in_garbage: in_garbage = False # Otherwise, if not in garbage, add the character to non_garbage elif not in_garbage: non_garbage += line[current_index] else: garbage_count += 1 current_index += 1 return [non_garbage, garbage_count] non_garbage_stream = read_file("star17_input.txt") print non_garbage_stream[0] print "Total Score:", get_total_score(non_garbage_stream[0]) print "Non-canceled in Garbage:", non_garbage_stream[1] testing_stuffs = read_file("testing.txt") print testing_stuffs[0] print "Total Score:", get_total_score(testing_stuffs[0]) print "Non-canceled in Garbage:", testing_stuffs[1]
221e4d56f9112b5c58c93a9fe0b9b4833a9aecce
ngk3/AdventOfCode2017
/Star12.py
2,027
4.09375
4
# Function used to turn the banks into a String representation def banks_to_string(banks): returning = "" for i in banks: returning += str(i) + " " return returning.strip() # Function used to redistribute the banks based on the given position and the highest value found def redistribute(banks, position, highest_value): # Reset the highest bank to 0 and start index on bank after position bank banks[position] = 0 tracker = position + 1 # Redistribute all of position bank, wraparound until finished while highest_value > 0: if tracker == len(banks): tracker = 0 banks[tracker] += 1 highest_value -= 1 tracker += 1 # Function that performs all needed redistribution on the banks until the infinite cycle is found def perform_redistribution(banks): # visited stores all visited String representation of the banks visited = [] visited.append(banks_to_string(banks)) # Continue until the cycle is found count = 0 infinite_found = "" while True: position = 0 highest_value = 0 # Find the bank with the highest value for i in range(len(banks)): if banks[i] > highest_value: position = i highest_value = banks[i] # Redistribute the highest bank and increase cycle count redistribute(banks, position, highest_value) count += 1 new_banks = banks_to_string(banks) # If the current bank has been seen before, # return the different between the cycle_count and the first appearance of the current bank # Otherwise, add the new bank into visited if new_banks in visited: infinite_found = new_banks break visited.append(new_banks) return count - visited.index(new_banks) # Function used to read a file and get the cycle counts based on redistribution def read_file_and_get_redistribution(file_name): banks = [] for line in open(file_name): for s in line.split("\t"): banks.append(int(s)) return perform_redistribution(banks) print read_file_and_get_redistribution("star11_input.txt")
3f33c301eea0937ba8c14e60b30a9133c2770a7f
ngk3/AdventOfCode2017
/Star42.py
7,141
3.5625
4
# class to represent a Grid of lights class Grid: # Initializes a grid based on a gridstring (look at input file to see gridstring format) def __init__(self, gridString = ".#./..#/###"): gridString_splitted = gridString.split("/") self.map = [] for gs in gridString_splitted: temp = [] for g in gs: temp.append(g) self.map.append(temp) self.size = len(self.map) # Function that returns a copy of the Grid's map def copyMap(self): new_map = [] for i in range(self.size): temp = [] for j in range(self.size): temp.append(self.map[i][j]) new_map.append(temp) return new_map # Function used to flip the Grid horizontally and return a new flipped Grid def flipHorizontal(self): new_map = self.copyMap() for i in range(self.size): for j in range(self.size / 2): temp = new_map[i][j] new_map[i][j] = new_map[i][-(j+1)] new_map[i][-(j+1)] = temp return Grid(toString(new_map)) # Function used to flip the Grid vertically and return a new flipped Grid def flipVertical(self): new_map = self.copyMap() for i in range(self.size / 2): temp = new_map[i] new_map[i] = new_map[-(i+1)] new_map[-(i+1)] = temp return Grid(toString(new_map)) # Function used to rotate the Grid clockwise and return the new rotated Grid def rotateClockwise(self): new_map = self.copyMap() rows = [] for i in range(self.size): temp = [] for j in range(self.size): temp.append(new_map[i][j]) rows.append(temp) for i in range(self.size): for j in range(self.size): new_map[j][i] = rows[self.size - i - 1][j] return Grid(toString(new_map)) # Function used to create and return the gridstring representation of the Grid def toString(self): returning = "" for m in range(self.size): for n in range(self.size): returning += self.map[m][n] if m != self.size - 1: returning += "/" return returning # Helper Function to divide the map from start_x - start_x + size, start_y - start_y + size grid def divideMap(self, start_x, start_y, size): returning_map = [] for i in range(start_x, start_x+size): column = [] for j in range(start_y, start_y+size): column.append(self.map[i][j]) returning_map.append(column) return toString(returning_map) # Function that divides the grid according to the ruleset and return the gridstring of each division in a list[columns] format def divideGrid(self): divided_grids = [] division_num = 3 if self.size % 2 == 0: division_num = 2 tracker_y = 0 while (tracker_y < self.size): addition = [] tracker_x = 0 while (tracker_x < self.size): addition.append(self.divideMap(tracker_x, tracker_y, division_num)) tracker_x += division_num divided_grids.append(addition) tracker_y += division_num return divided_grids; # Function used to print the Grid as a Map def printMap(self): for i in range(self.size): temp = "" for j in range(self.size): temp += self.map[i][j] print temp print # Function used to count and return the number of pixels that are on def getNumOn(self): count = 0 for i in range(self.size): for j in range(self.size): if self.map[i][j] == "#": count += 1 return count # Function to return the gridstring representation of a grid Map def toString(new_map): returning = "" for m in range(len(new_map)): for n in range(len(new_map)): returning += new_map[m][n] if m != len(new_map) - 1: returning += "/" return returning # Function used to read the input file and get all the image creation rules def readFileAndGetRules(file_name): rules = dict([]) for line in open(file_name, 'r'): line_splitted = line.strip().split(" => ") rules[line_splitted[0]] = line_splitted[1] return rules # Function that returns a list of possible grid transformations of a Grid def getCombinationGrids(grid): combin_grids = [] for i in range(4): combin_grids.append(grid) combin_grids.append(grid.flipHorizontal()) combin_grids.append(grid.flipVertical()) grid = grid.rotateClockwise() return combin_grids # Function that translate the list of divided grids based on the given ruleset def translateGrids(rules, list_divided_grids): for i in range(len(list_divided_grids)): for j in range(len(list_divided_grids)): grid_rep = getCombinationGrids(Grid(list_divided_grids[i][j])) for g in grid_rep: try: list_divided_grids[i][j] = rules[g.toString()] break except: continue # Function that takes a list of divided grids and combines them into a gridstring def combineGrids(list_divided_grids): # Initializes the dictionary to get the gridstrings of each row combined_grid = dict([]) tracker = 1 for col in list_divided_grids[0]: for col_splitted in col.split("/"): combined_grid[tracker] = "" tracker += 1 # Get the gridstrings of each row for col in list_divided_grids: tracker = 1 for c in col: for c_splitted in c.split("/"): combined_grid[tracker] += c_splitted tracker += 1 start = time.time() # Return the combined gridstring returning_string = ""; for cg in range(1, len(combined_grid) + 1): returning_string += combined_grid[cg] if cg != len(combined_grid): returning_string += "/" return returning_string # Function that takes in the number of iterations and the rule input file and returns the number of lights on in the end image def runIterations(num_iterations, input_file): # Get the rules and initialize the grid rules = readFileAndGetRules(input_file) start_grid = Grid() # Run through division, translation, and combination of grids num_iteration times for i in range(num_iterations): divided_grids = start_grid.divideGrid() translateGrids(rules, divided_grids) start_grid = Grid(combineGrids(divided_grids)) # Return the number of lights on in the grid return start_grid.getNumOn() print "Number of lights on after 18 iterations = ", runIterations(18, "Star41_input.txt")
fa5a41a746942e83af4c38071143488552fd6f84
i-vs/tree-practice
/binary_search_tree/tree.py
4,323
3.9375
4
# some descriptive blocks and None's are for readability class TreeNode: def __init__(self, key, val=None): if val == None: val = key self.key = key self.value = val self.left = None self.right = None class Tree: def __init__(self): self.root = None # Time Complexity: if balanced, O(log n); else: O(n) # Space Complexity: O(1) def add(self, key, value=None): if self.root is None: self.root = TreeNode(key, value) else: current = self.root while True: if key > current.key: if current.right is None: current.right = TreeNode(key, value) return current = current.right else: if current.left is None: current.left = TreeNode(key, value) return current = current.left # --------------------------------------------------------------- # Time Complexity: if balanced, O(log n); else: O(n) # Space Complexity: O(1) def find(self, key): return self.find_recursive(key, self.root) def find_recursive(self, key, current_node): if current_node is None: return None if key == current_node.key: return current_node.value if key > current_node.key: return self.find_recursive(key, current_node.right) else: return self.find_recursive(key, current_node.left) # --------------------------------------------------------------- # Time Complexity: O(n) # Space Complexity: O(n) def inorder(self): node_list = [] self.inorder_recursive(self.root, node_list) return node_list def inorder_recursive(self, node, node_list): if node is None: return self.inorder_recursive(node.left, node_list) node_list.append(self.to_dic(node)) self.inorder_recursive(node.right, node_list) # --------------------------------------------------------------- # Time Complexity: O(n) # Space Complexity: O(n) def preorder(self): node_list = [] self.preorder_recursive(self.root, node_list) return node_list def preorder_recursive(self, node, node_list): if node is None: return node_list.append(self.to_dic(node)) self.preorder_recursive(node.left, node_list) self.preorder_recursive(node.right, node_list) # --------------------------------------------------------------- # Time Complexity: O(n) # Space Complexity: O(n) def postorder(self): node_list = [] self.postorder_recursive(self.root, node_list) return node_list def postorder_recursive(self, node, node_list): if node is None: return self.postorder_recursive(node.left, node_list) self.postorder_recursive(node.right, node_list) node_list.append(self.to_dic(node)) # --------------------------------------------------------------- # Time Complexity: O(n) # Space Complexity: O(n) def height(self): return self.height_recursive(self.root) def height_recursive(self, node): if node is None: return 0 return max(self.height_recursive(node.left), self.height_recursive(node.right)) + 1 # ..🌝 # --------------------------------------------------------------- # # Optional Method # # Time Complexity: O(n) # # Space Complexity: O(n) def bfs(self): result = [] if self.root is None: return result queue = [] queue.append(self.root) while len(queue) > 0: current = queue.pop(0) result.append(self.to_dic(current)) if current.left: queue.append(current.left) if current.right: queue.append(current.right) print(result) return result # --------------------------------------------------------------- # # Useful for printing def to_s(self): return f"{self.inorder()}" def to_dic(self, node): return {"key": node.key, "value": node.value}
b3a16e0f14a5221be418de9d5162ad97cff9fba0
JoelDarnes88/primer_programa
/2.0.-Come_helado.py
532
4.1875
4
apetece_helado = input("¿Te apetece helado? (Si/No): ") tiene_dinero = input("Tienes dinero (Si/No): ") esta_el_señor_de_los_helados = input("esta el señor de los helados (Si/No) ") esta_tu_tia = input("¿Estás con tu tía? (Si/No)") Te_apetece_helado = apetece_helado == "Si" puedes_permitirtelo = tiene_dinero == "Si" or esta_tu_tia == "Si" esta_el_señor = esta_el_señor_de_los_helados == "Si" if Te_apetece_helado and puedes_permitirtelo and esta_el_señor: print("pues_comete_un_helado") else: print("pues_nada")
ebe6c06d7f547761f10f2c10df4f4cd033009859
amysolman/CMEECourseWork
/Week3/Code/get_TreeHeight.py
867
3.5625
4
#!/usr/bin/env python3 # Date: Dec 2019 """Takes input file of tree distances and degress, calculates height and outputs results file with input file name.""" __appname__ = 'get_TreeHeight.py' __author__ = 'Amy Solman ([email protected])' __version__ = '0.0.1' import sys import pandas as pd import os import math MyDF = pd.read_csv(sys.argv[1], sep=',') inputfile = sys.argv[1] TreeDistance = MyDF.iloc[:, 1] TreeDegrees = MyDF.iloc[:, 2] def Tree_Height(degrees, distance): radians = degrees*math.pi/180 height = distance*radians.astype(float).map(math.tan) return(height) TreeHeight = Tree_Height(TreeDegrees, TreeDistance) MyDF['TreeHeight'] = TreeHeight file_dir = "../Results" outputfile = inputfile.split(".")[0] + "_treeheights_py.csv" final_path = os.path.join(file_dir, outputfile) export_csv = MyDF.to_csv(final_path, header=True, index=False)
ce7f395b4defb63095c402233d486ebb73724b4a
amysolman/CMEECourseWork
/Week2/Code/using_name.py
1,008
3.78125
4
#!/usr/bin/env python3 # Date: Oct 2019 # Filename: using_name.py """In shell either run using_name.py (for ipython) or python3 using_name.py. Script will generate several different functions using different conditionals.""" # Before python runs the code in a file it sets a few special variables, # __name__ is one of them. When it runs the file directly it sets the __name__ variable # equal to __main__. But we can also import modules! Whenever we import a module # from another program/module, it sets the __name__ variable to the name of the file. # In this case __using_name__. It does this because the module is no longer being run directly # from Python, it is being imported. This is useful because we can check if the file # is being run directly from Python or imported. if __name__ == '__main__': print('This program is being run by itself') # This program is being run directly! else: print('I am being imported from another module') print("This module's name is: " + __name__)
0429ec1c03247b819b282ebb33731b095d39a2da
amysolman/CMEECourseWork
/Week2/Code/basic_io3.py
1,023
3.6875
4
##!/usr/bin/env python3 ############################# # STORING OBJECTS ############################# __appname__ = 'basic_io3.py' __version__ = '0.0.1' """ In shell either run basic_io3.py (for ipython) or python3 basic_io3.py. Script will create a dictionary and save it to testp.p then load the data again and save to another_dictionary then print. """ # To save an object (even complex) for later use my_dictionary = {"a key": 10, "another key": 11} # pickle module implements binary protocols for serializing/ # de-serializing an object structure. # Converts an object in memory to a byte stream than can be stored or sent over network. import pickle f = open('../sandbox/testp.p', 'wb') ## note the b: accept binary files pickle.dump(my_dictionary, f) #put the binary version of my dictionary into the file f.close() ## Load the data again f = open('../sandbox/testp.p', 'rb') another_dictionary = pickle.load(f) #load the binary data from the file into another_dictionary f.close() print(another_dictionary)
6dd8b8449ec2670b9dd39bbd8decf2ba67171437
niksimon/python-stuff
/tutorial/lists.py
148
3.796875
4
friends = ["Joe", "Jack", "Jessica", "Oscar", "Poe", "Tim", "Mike", "Jim"] print(friends) print(friends[-1]) #print(friends[1:]) print(friends[1:3])
96eade2293d5ca717943b148bb12d21dd1110912
niksimon/python-stuff
/google-foobar-challenges/google_lvl4_challenge1.py
3,747
3.6875
4
def testPair(a, b): sum = a + b _min = min(a, b) # If sum of two numbers is divisible by min number and (sum / 2) / min is a power of two then two guards will reach same number of bananas and we don't want that pair so return False power = sum // 2 // _min if(sum % 2 == 0 and sum % _min == 0 and (power & (power - 1)) == 0): return False # Else they will never reach same number of bananas, will go to infinity else: return True def solution(banana_list): l = len(banana_list) pairs = [] guards = [{"id": idx, "connections": []} for idx, i in enumerate(banana_list)] print(guards) for i in range(l - 1): for j in range(i + 1, l): if(testPair(banana_list[i], banana_list[j])): guards[i]["connections"].append(j) guards[j]["connections"].append(i) print(guards) for guard in guards: for connection in guard["connections"]: if(not guard["id"] in pairs and not connection in pairs): pairs += [guard["id"], connection] print(pairs) return l - len(pairs) print(solution([1,4,5,35])) """ Distract the Guards =================== The time for the mass escape has come, and you need to distract the guards so that the bunny prisoners can make it out! Unfortunately for you, they're watching the bunnies closely. Fortunately, this means they haven't realized yet that the space station is about to explode due to the destruction of the LAMBCHOP doomsday device. Also fortunately, all that time you spent working as first a minion and then a henchman means that you know the guards are fond of bananas. And gambling. And thumb wrestling. The guards, being bored, readily accept your suggestion to play the Banana Games. You will set up simultaneous thumb wrestling matches. In each match, two guards will pair off to thumb wrestle. The guard with fewer bananas will bet all their bananas, and the other guard will match the bet. The winner will receive all of the bet bananas. You don't pair off guards with the same number of bananas (you will see why, shortly). You know enough guard psychology to know that the one who has more bananas always gets over-confident and loses. Once a match begins, the pair of guards will continue to thumb wrestle and exchange bananas, until both of them have the same number of bananas. Once that happens, both of them will lose interest and go back to guarding the prisoners, and you don't want THAT to happen! For example, if the two guards that were paired started with 3 and 5 bananas, after the first round of thumb wrestling they will have 6 and 2 (the one with 3 bananas wins and gets 3 bananas from the loser). After the second round, they will have 4 and 4 (the one with 6 bananas loses 2 bananas). At that point they stop and get back to guarding. How is all this useful to distract the guards? Notice that if the guards had started with 1 and 4 bananas, then they keep thumb wrestling! 1, 4 -> 2, 3 -> 4, 1 -> 3, 2 -> 1, 4 and so on. Now your plan is clear. You must pair up the guards in such a way that the maximum number of guards go into an infinite thumb wrestling loop! Write a function solution(banana_list) which, given a list of positive integers depicting the amount of bananas the each guard starts with, returns the fewest possible number of guards that will be left to watch the prisoners. Element i of the list will be the number of bananas that guard i (counting from 0) starts with. The number of guards will be at least 1 and not more than 100, and the number of bananas each guard starts with will be a positive integer no more than 1073741823 (i.e. 2^30 -1). Some of them stockpile a LOT of bananas."""
3e2ba4c06bbdecb708dbcbdfbbbd3311c4ebce80
niksimon/python-stuff
/tutorial/classes.py
273
3.734375
4
class Student: def __init__(self, name, age, is_on_probation): self.name = name self.age = age self.is_on_probation = is_on_probation def print(self): print(self.name + " " + str(self.age)) s = Student("simon", 26, False) s.print()
48551a04d331f77d4fe2fa110c1f647ba6d07e28
Haseenamenda/pal
/sta.py
273
3.71875
4
def midchenge(): k=input() n=len(k) l=list(k) k='' if n%2!=0: for i in range(n//2): k+=l[i] k+='*' j=n//2+1 else: for i in range(n//2-1): k+=l[i] k+='**' j=n//2+1 for i in range(j,n): k+=l[i] print(k) try: midchenge() except: print('invalid')
7d81a11bce57d7cc0f2105630ef611762a195882
mariumi96/lab2_repo
/arr_algs.py
474
3.84375
4
def find_min(arr): if arr: min = arr[0] for el in arr: if el < min: min = el return min else: print('Массив пуст!') def avr(arr): if arr: a = 0 for el in arr: a = a + el n = len(arr) return a / n else: print('Массив пуст!') a = [2, 8, 9, 11, 78, 1] print(find_min(a)) print(avr(a)) b = [] print(find_min(b)) print(avr(b))
6cada4baa7361aa9b5180f270bf09423e33b11e6
Kole19/pyVezbe
/Prost broj.py
284
3.59375
4
def prost_br(broj): dalije=0 for x in range(2,broj): if broj%x is 0: dalije+=1 if dalije >= 1: print("Broj nije prost.") else: print("Broj je prost.") a = input("Unesi broj: ") broj = int(a) prost_br(broj)
ec0f71c1275537052ef07e924758a5bcbe4786b3
hsherkat/AOC2020
/day19.py
1,826
3.5625
4
""" Advent of Code 2020: Day 19 https://adventofcode.com/2020/day/19 """ import re from itertools import product from typing import Dict def get_matches(rule: str, rules_dict: Dict[str, str]): pattern = r'"([a-z]+)"' if (match := re.search(pattern, rule)) : # base case, single letter c = match.group(1) return [c] elif "|" in rule: # two possibilities rule1, rule2 = [r.strip() for r in rule.split("|")] return get_matches(rule1, rules_dict) + (get_matches(rule2, rules_dict)) else: # join them together return [ "".join(x) for x in product( *[get_matches(rules_dict[i], rules_dict) for i in rule.split()] ) ] def parse_input(raw_input): d = dict(line.split(":") for line in raw_input.split("\n")) return {k.strip(): v.strip() for k, v in d.items()} def hacky(s): N = len(s) if N % 8 != 0: return False ss = "".join( [ str( "a" * ((chunk := s[8 * i : 8 * i + 8]) in matches42) + "b" * (chunk in matches31) + "c" * (chunk not in matches42 and chunk not in matches31) ) for i in range(N // 8) ] ) c42, c31, ccs = ss.count("a"), ss.count("b"), ss.count("c") return (c42 > c31) and (c31 > 0) and ccs == 0 and ss.endswith("b" * c31) ############### with open("input_19.txt") as f: raw_input = f.read() # "".join([line for line in f]) rules = parse_input(raw_input.split("\n\n")[0]) if __name__ == "__main__": msgs = set(line.strip() for line in raw_input.strip().split("\n\n")[1].split("\n")) matches42 = get_matches(rules["42"], rules) matches31 = get_matches(rules["31"], rules) out = sum(hacky(msg) for msg in msgs) print(out)
092393145094c02a579ac74628820ba053f1bad2
hsherkat/AOC2020
/day01.py
1,423
4.0625
4
""" Advent of Code 2020: Day 1 https://adventofcode.com/2020/day/1 """ from typing import List, Tuple from collections import Counter from itertools import product def find_pair_sums_to_N(nums: List[int], N: int) -> Tuple[int, int]: if (N % 2 == 0) and nums.count(N // 2) > 1: return (N // 2, N // 2) nums_set = set(nums) for n in nums_set: if N - n in nums_set and (n != N - n): return (n, N - n) raise ValueError("No pair found.") def overcounted(arr: List, limits: Counter) -> bool: """Determines whether any item in arr appears more times than allowed by count_limits.""" return any(arr.count(x) > limits[x] for x in set(arr)) def find_triplet_sums_to_N(nums: List[int], N: int) -> Tuple[int, int, int]: nums_counter = Counter(nums) if (N % 3 == 0) and not overcounted([N // 3] * 3, nums_counter): return (N // 3, N // 3, N // 3) nums_set = set(nums) for (m, n) in product(nums_set, nums_set): if N - m - n in nums_set and not overcounted([m, n, N - m - n], nums_counter): return (m, n, N - m - n) raise ValueError("No triplet found.") ################# with open("input_1.txt") as f: x_input = [int(x) for x in f] if __name__ == "__main__": x, y = find_pair_sums_to_N(x_input, 2020) print(f"Part 1: {x * y}") x, y, z = find_triplet_sums_to_N(x_input, 2020) print(f"Part 2: {x * y* z}")
1bc276f7d38d0414a2897aeba366acd3c2613eb1
hsherkat/AOC2020
/day08.py
1,575
3.6875
4
""" Advent of Code 2020: Day 8 https://adventofcode.com/2020/day/8 """ with open("input_8.txt") as f: x_input = [row.strip() for row in f] def parse_instruction(instr): op, num = instr.split(" ") val = int(num) return op, val def execute_instruction(instructions, row_num): op, val = parse_instruction(instructions[row_num]) next_row = row_num + 1 incr = 0 if op == "jmp": next_row = row_num + val if op == "acc": incr = val return next_row, incr def execute_all(instructions): seen_rows = set() row_num, increment = (0, 0) acc_total = 0 while True: seen_rows.add(row_num) row_num, increment = execute_instruction(instructions, row_num) acc_total += increment if row_num in seen_rows: break_cond = f"Repeat: {row_num}" break if row_num >= len(instructions): break_cond = f"Passed the end: {row_num}" break return acc_total, break_cond def modify_instructions(instructions, idx): new_instructions = instructions[:] if "nop" in instructions[idx]: new_instructions[idx] = instructions[idx].replace("nop", "jmp") elif "jmp" in instructions[idx]: new_instructions[idx] = instructions[idx].replace("jmp", "nop") return new_instructions if __name__ == "__main__": print(execute_all(x_input)) N = len(x_input) for i in range(N): out = execute_all(modify_instructions(x_input, i)) if "Passed" in out[1] and str(N) in out[1]: print(out)
af242c1ae86592272b3c02dcfdfc67575e0d3b6e
pijel/assorted-algos
/add_linked_lists.py
1,088
3.78125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None import math class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ return reverse(to_list(to_number(l1) + to_number(l2))) def to_number(head): number = 0 head = reverse(head) while head: number = 10 * number + head.val head = head.next return number def to_list(num): head = ListNode(None) start = head if num == 0: start.val = 0 return start while num > 0: head.val = num %10 num = num //10 nex = ListNode(None) head.next = nex head = nex return reverse(start).next def reverse(head): answer = None while head: next_node = head.next head.next = answer answer = head head = next_node return answer
2c2cbc8c02307881723e1a88b7b2245855164a23
pijel/assorted-algos
/remove_k_from_end.py
853
3.8125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ return remove_node(head,n) def get_list_len(head): if not head: return 0 length = 1 while head.next: length += 1 head = head.next return length def remove_node(head,n): size = get_list_len(head) if size == n: return head.next node_to_remove = size - n start = head position = 1 while head: if position == node_to_remove: head.next = head.next.next head = head.next position +=1 return start
0a19fd4970421e0ff69b418993eb302fa5f6a747
pijel/assorted-algos
/trapping_rainwater.py
1,210
3.90625
4
class Solution: def trap(self, height): """ :type height: List[int] :rtype: int """ if height == []: return 0 return how_much_water(height) def how_much_water(height): elevation = 1 rain_water = 0 while elevation <= max(height): i = 0 while i < (len(height)): #print(i) distance = 1 if height[i] >= elevation: looking_for_right_closure = True while looking_for_right_closure: while i+1 < len(height) and height[i+1] >= elevation: i += 1 distance +=1 if i+distance < len(height): if height[i+distance] >= elevation: looking_for_right_closure = False rain_water += distance - 1 #distance = 1 else: looking_for_right_closure = False if distance > 1: i += distance else: i+=1 elevation +=1 return rain_water
f9a5831098d43874164173820338090a76384130
pijel/assorted-algos
/merge_k_linked_lists.py
1,502
3.859375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ return mergeklists(lists) def mergeklists(lists): if len(lists) == 1: return lists[0] if len(lists) == 0: return None left = mergeklists([lists[j] for j in range(len(lists)//2)]) right = mergeklists([lists[j] for j in range(len(lists)//2,len(lists))]) return mergelists(left,right) def mergelists(l1,l2): if not l1 and not l2: return None if not l1: return l2 if not l2: return l1 if l1.val < l2.val: new_list = ListNode(l1.val) l1 = l1.next else: new_list = ListNode(l2.val) l2 = l2.next answer = new_list while l1 and l2: if l1.val < l2.val: new_list.next = ListNode(l1.val) new_list = new_list.next l1 = l1.next else: new_list.next = ListNode(l2.val) new_list = new_list.next l2 = l2.next while l1: new_list.next = ListNode(l1.val) new_list = new_list.next l1 = l1.next while l2: new_list.next = ListNode(l2.val) new_list = new_list.next l2 = l2.next return answer
28e9553712f9c3c8311600858170029d619dc219
renanlage/naive-bayes
/remove_old_players.py
1,558
3.65625
4
#function that removes the players from older seasons that do not have all the data available... def remove_players(regular_season_path, player_career): # opening files regular_file = open(regular_season_path, 'r') player_career_file = open(player_career, 'r') # read files to memory as lists player_career = player_career_file.readlines() regular = regular_file.readlines() # closing files player_career_file.close() regular_file.close() # start reading files print 'processing...' counter = 0 output_players = [] for player_career_line in player_career: # geting the player with the career data career_player = player_career_line.strip().split(',') player_c_name = career_player[0].upper().strip() for regular_line in regular: # geting regular season player name regular_player = regular_line.upper().strip() if player_c_name in regular_player: output_players.append(player_career_line.strip() + '\n') regular.pop(counter) counter = 0 break #index to remove from list the already added player, to optimize the algorithm... counter += 1 # write on output file and close program output_file = open('output2.csv', 'w') output_file.writelines(output_players) output_file.close() print 'finished' if __name__ == "__main__": remove_players('input_data.csv', 'nba_data/player_career.csv')
bfd4c97134b9bcae8eb5d553b94988aed968cc49
JMU-ROBOTICS-VIVA/jmu_ros2_util
/jmu_ros2_util/map_utils.py
5,643
3.5
4
"""Map class that can generate and read OccupancyGrid messages. Grid cell entries are occupancy probababilities represented as integers in the range 0-100. Value of -1 indicates unknown. Author: Nathan Sprague Version: 10/29/2020 """ import numpy as np from nav_msgs.msg import OccupancyGrid from geometry_msgs.msg import Pose from builtin_interfaces.msg import Time class Map: """ The Map class represents an occupancy grid. Map entries are stored as 8-bit integers. Public instance variables: width -- Number of columns in the occupancy grid. height -- Number of rows in the occupancy grid. resolution -- Width of each grid square in meters. origin_x -- Position of the grid cell (0,0) in origin_y -- in the map coordinate system. grid -- numpy array with height rows and width columns. Note that x increases with increasing column number and y increases with increasing row number. """ def __init__(self, *args, **kwargs): """ Construct an empty occupancy grid. Can be called -either- with a single OccupancyGrid message as the argument, or with any of the following provided as named arguments: keyword arguments: origin_x, origin_y -- The position of grid cell (0,0) in the map coordinate frame. (default -2.5, -2.5) resolution-- width and height of the grid cells in meters. (default .1) width, height -- The grid will have height rows and width columns cells. width is the size of the x-dimension and height is the size of the y-dimension. (default 50, 50) The default arguments put (0,0) in the center of the grid. """ if len(args) == 1 and isinstance(args[0], OccupancyGrid): self._init_from_message(args[0]) elif len(args) == 0: self._init_empty(kwargs) else: raise ValueError("Constructor only supports named arguments.") def _init_empty(self, kwargs): """ Set up an empty map using keyword arguments. """ self.frame_id = "map" self.stamp = Time() # There is no great way to get the actual time. self.origin_x = kwargs.get('origin_x', -2.5) self.origin_y = kwargs.get('origin_y', -2.5) self.width = kwargs.get('width', 50) self.height = kwargs.get('height', 50) self.resolution = kwargs.get('resolution', .1) self.grid = np.zeros((self.height, self.width)) def _init_from_message(self, map_message): """ Set up a map as an in-memory version of an OccupancyGrid message """ self.frame_id = map_message.header.frame_id self.stamp = map_message.header.stamp self.width = map_message.info.width self.height = map_message.info.height self.resolution = map_message.info.resolution self.origin_x = map_message.info.origin.position.x self.origin_y = map_message.info.origin.position.y self.grid = np.array(map_message.data, dtype='int8').reshape(self.height, self.width) def to_msg(self): """ Return a nav_msgs/OccupancyGrid representation of this map. """ grid_msg = OccupancyGrid() grid_msg.header.frame_id = self.frame_id grid_msg.header.stamp = self.stamp grid_msg.info.resolution = self.resolution grid_msg.info.width = self.width grid_msg.info.height = self.height grid_msg.info.origin = Pose() grid_msg.info.origin.position.x = self.origin_x grid_msg.info.origin.position.y = self.origin_y grid_msg.info.origin.orientation.x = 0.0 grid_msg.info.origin.orientation.y = 0.0 grid_msg.info.origin.orientation.z = 0.0 grid_msg.info.origin.orientation.w = 1.0 grid_msg.data = [int(val) for val in self.grid.flatten()] return grid_msg def cell_position(self, row, col): """ Determine the x, y coordinates of the center of a particular grid cell. """ x = col * self.resolution + .5 * self.resolution + self.origin_x y = row * self.resolution + .5 * self.resolution + self.origin_y return x, y def cell_index(self, x, y): """ Helper method for finding map index. x and y are in the map coordinate system. """ x -= self.origin_x y -= self.origin_y row = int(np.floor(y / self.resolution)) col = int(np.floor(x / self.resolution)) return row, col def set_cell(self, x, y, val): """ Set the value in the grid cell containing position (x,y). x and y are in the map coordinate system. No effect if (x,y) is out of bounds. """ row, col = self.cell_index(x, y) try: if row >= 0 and col >= 0: self.grid[row, col] = val except IndexError: pass def get_cell(self, x, y): """ Get the value from the grid cell containing position (x,y). x and y are in the map coordinate system. Return 'nan' if (x,y) is out of bounds. """ row, col = self.cell_index(x, y) try: if row >= 0 and col >= 0: return self.grid[row, col] else: return float('nan') except IndexError: return float('nan')
4b873329812e2af982c4c137b52cd5da86dccdeb
update-ankur/Hackerrank_30daysOFcode
/30 days of code( python)/Day 24.py
682
3.703125
4
def removeDuplicates(self,head): #Write your code here if head is None: return current_node = head counter = 0 list_data = {} index = 0 while (current_node is not None): if (list_data.get(current_node.data) is None): list_data[current_node.data] = counter counter += 1 current_node = current_node.next new_list = Solution() head = None for key in sorted(list_data): head = new_list.insert(head, key) return head
ccae5bbd74ff61ad83eb4a315f75bfa33c51a14b
update-ankur/Hackerrank_30daysOFcode
/30 days of code( python)/day10.py
558
3.609375
4
#!/bin/python3 import math import os import random import re import sys def tobinary(n): s = "" while n>0 : s = str(n%2) + s n = n//2 return s def func(n): s = tobinary(n) i = 0 mx = -1 while i < len(s): count = 0 while i < len(s) and s[i] == '1' : count = count + 1 i = i + 1 mx = max(count,mx) if count == 0: i = i + 1 return mx if __name__ == '__main__': n = int(input()) print( func(n) )
729267ed2e25066aa0aeceedd01d8168c523609a
SGiuri/word-count
/word_count.py
261
3.59375
4
import re from collections import Counter def count_words(sentence): clear_sentence = re.sub(f"[^a-zA-Z0-9\']", " ", sentence) words = [word.strip("'").lower() for word in clear_sentence.split()] all_words = Counter(words) return all_words
23ecdab8a0a6c0e0f61d41b8588e580e74169412
CdavisL-coder/automateTheBoringStuff
/spam.py
208
3.84375
4
#this is an example of a while loop #value of spam is 0 spam = 0 #while spam is less than 0, print quote while spam < 10: print("T'is but a scratch!") #adds 1 to spam every time spam = spam + 1
6f2581f4fafe6f3511327d5365f045ba579a46b1
CdavisL-coder/automateTheBoringStuff
/plusOne.py
372
4.21875
4
#adds one to a number #if number % 3 or 4 = 0, double number #this function takes in a parameter def plus_one(num): num = num + 1 #if parameter is divided by 2 and equal zero, the number is doubled if num % 2 == 0: num2 = (num + 1) * 2 print(num2) #else print the number else: print(num) plus_one(4) plus_one(80) plus_one(33)
73c96ebcfebcf11ad7fde701f001d8bdbd921b00
poljkee2010/python_basics
/week_2/2.3 max_of_three.py
215
4.1875
4
a, b, c = (int(input()) for _ in range(3)) if a < b > c: print(b) elif a < c > b: print(c) elif b < a > c: print(a) elif a > b or a > c: print(a) elif b > a or b > c: print(b) else: print(c)
753cf5fe690b21cf11c657121b12b4570a70f691
poljkee2010/python_basics
/week_3/3.16 delete_the_fragment.py
109
3.578125
4
string = input() first, last = string.find("h"), string.rfind("h") print(string[:first] + string[last + 1:])
46c7273f57bbd0d029797bef3868cbb6af63425e
poljkee2010/python_basics
/week_3/3.8 gorner_scheme.py
131
3.671875
4
n = int(input()) x = float(input()) total = 0 for _ in range(n + 1): total += float(input()) * x ** n n -= 1 print(total)
1292602718d97a0c5441e0085f947b82f45bcf57
poljkee2010/python_basics
/week_4/4.4 is_point_in_square.py
163
3.78125
4
a, b = (float(input()) for _ in range(2)) def IsPointInSquare(x, y): return -1 <= x <= 1 and -1 <= y <= 1 print("YES " if IsPointInSquare(a, b) else "NO")
a246d744c2e821983838421a0dc8df5a7ba265be
poljkee2010/python_basics
/week_3/3.23 replace_but_first_and_last.py
159
3.703125
4
string = input() first = string.find("h") last = string.rfind("h") print(string[:first + 1] + string[first + 1: last].replace("h", "H") + string[last:])
8686b7e0d8eeca93d4516689950f455193e60d06
poljkee2010/python_basics
/week_7/7.6 count_words.py
169
3.734375
4
words_set = set() with open("input.txt", "r") as f: for line in f: for word in line.strip().split(): words_set.add(word) print(len(words_set))
33938b7c55842e4bb85ce3651015dfed0704b0f1
poljkee2010/python_basics
/week_5/5.17 larger_than_previous.py
132
3.5625
4
lst = [int(num) for num in input().split()] for i in range(1, len(lst)): if lst[i] > lst[i - 1]: print(lst[i], end=" ")
56cb66f9227a10f6158b84f32fa5fda4675f70b0
maryclarecc/python-challenge
/PyPoll/main.py
2,915
3.515625
4
import os import csv import numpy as np from numpy.core.fromnumeric import mean, sort csvpath = os.path.join('Resources', 'election_data.csv') with open(csvpath, "r") as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') # Read the header row first (skip this step if there is now header) csv_header = next(csvreader) # print(f"CSV Header: {csv_header}") # # Read each row of data after the header for row in csvreader: #print(row[1]) data = list(csvreader) #The total number of votes included in the dataset, count # of rows num_rows = -1 # to account for the header for row in open(csvpath): num_rows += 1 #A complete list of candidates who received votes candidates = [] i = ["Voter ID", "County", "Candidate"] for row in data: candidates.append(row[2]) uniquecand = sort(list(set(candidates))) #print(uniquecand) #The total number of votes each candidate won khan = 0 correy = 0 li = 0 otooley = 0 for candidate in candidates: if candidate == "Khan": khan += 1 if candidate == "Correy": correy += 1 if candidate == "Li": li += 1 if candidate == "O'Tooley": otooley += 1 #The percentage of votes each candidate won khanp = round((khan/num_rows * 100), 3) correyp = round((correy/num_rows * 100), 3) lip = round((li/num_rows * 100), 3) otooleyp = round((otooley/num_rows * 100), 3) #The winner of the election based on popular vote. winner = {"Khan": khanp, "Correy": correyp, "Li": lip, "O'Tooley": otooleyp} max_value = max(winner, key = winner.get) print("Election Votes") print("-----------------------------------") print(f"Total Votes: {num_rows}") print("-----------------------------------") print(f'{uniquecand[1]}: {khanp}% ({khan})') print(f'{uniquecand[0]}: {correyp}% ({correy})') print(f'{uniquecand[2]}: {lip}% ({li})') print(f'{uniquecand[3]}: {otooleyp}% ({otooley})') print("-----------------------------------") print(f'Winner: {max_value}') print("-----------------------------------") output_path = os.path.join("analysis", "polls.txt") f = open(output_path, "w") f.write("Election Votes") f.write("\n") f.write("-----------------------------------") f.write("\n") f.write(f"Total Votes: {num_rows}") f.write("\n") f.write("-----------------------------------") f.write("\n") f.write(f'{uniquecand[1]}: {khanp}% ({khan})') f.write("\n") f.write(f'{uniquecand[0]}: {correyp}% ({correy})') f.write("\n") f.write(f'{uniquecand[2]}: {lip}% ({li})') f.write("\n") f.write(f'{uniquecand[3]}: {otooleyp}% ({otooley})') f.write("\n") f.write("-----------------------------------") f.write("\n") f.write(f'Winner: {max_value}') f.write("\n") f.write("-----------------------------------") f.close()
bade4df0766758c49699a8d4465cecc828179f8c
Roy19/codeforces
/python/4a.py
203
4
4
def divide(n): if (n % 2 != 0) or n == 2: return 'NO' else: return 'YES' if __name__ == '__main__': n = int(input().strip()) result = divide(n) print(result)
b427deccf1a96603788f6220f2d3970643586a4d
amedesc/mantsoft-fidu-2019
/jrh8.py
625
3.625
4
def darmensaje(mensaje): print("Hola Mundo" + mensaje) darmensaje(" es mi primera vez en python ") #crear una funcion PatternCount que cuenta cuántas veces aparece #un patrón Pattern en una cadena de caracteres Text. print("Buenas por favor ingrese un texto donde se repita un patrón y luego ingresa el patrón") def PatternCoun(text, pattern): cont = 0 for i in range(0, len(text) - len(pattern) + 1): if text[i : len(pattern) + i] == pattern: cont += 1 return print ("El patrón se repite "+str(cont) + " veces en el texto") PatternCoun(input(), input());
0b4c4f72772ccc99908b02721287a1b85c1157f0
amedesc/mantsoft-fidu-2019
/fertico21.py
730
3.546875
4
# Esta función concatena 2 cádenas de texto. # Recibe como parametro un mensaje y retorna "Hola mundo" + mensaje enviado. def darmensaje(mensaje): print ("Hola mundo!", mensaje) darmensaje("Fernando") # Esta Función determina la frecuencia con la que un patrón aparece en una cadena de texto. # Recibe como parámetros el texto y el patrón. Y retorna el número de veces que se encuentra ese patrón en el texto. def PatternCount(texto, patron): contador = 0 for x in range(0, len(texto)): if texto[x:len(patron)+x] == patron: contador += 1 return contador a = PatternCount("ADNABCDEFGHIJKLMNOPQRSTUWXYZADNABCDEFGHIJKLMNOPQRSTUWXYZADNABCDEFGHIJKLMNOPQRSTUWXYZADNADN","ADN") print (a)
958a950e7f1bed0601a54bd349d9bd873a12223f
Parashar7/Introduction_to_Python
/Sqaureroot.py
183
4.375
4
import math print("This is the program to find the square root of a number:") num=int(input("Enter a number:")) sqrt=math.sqrt(num) print("Square root of "+ str(num)+ " is \n" , sqrt)
c1c638da823de134b079145344476ee9aa8d9b42
Parashar7/Introduction_to_Python
/Automated_Billing.py
1,329
3.9375
4
print("\t\t\t\t\tThis is a program to automate a Billing System\n\n\n") pre_mon=int(input("Enter the Previous Month Home Units: ")) cur_mon=int(input("Enter the Current Home Month Units: ")) ac1=int(input("Enter the Previous A.C Month Units: ")) ac2=int(input("Enter the Current A.C Month Units: ")) print("Home Units", ac2-ac1) print("A.C Units", cur_mon-pre_mon ) diff=(ac2-ac1) + (cur_mon-pre_mon) +24 print("Total Unit including default 24 units is: ", diff) unit=float(input("Enter Cost Per Unit =")) total_unit= diff * unit print("Total Cost of Electricity is: ", total_unit ,"\n\n") print("Calculation of Default Charges:") t_tloss=float(input("Enter the T&T Loss: ")) mr=float(input("Enter the Meter Reading: ")) tm=float(input("Enter Transformer Maintenance Charge: ")) wm=float(input("Enter Water Management Charge: ")) ac=float(input("Enter Admin. Charges: ")) mw=float(input("Enter the Maintenance Work: ")) default=(t_tloss+mr+tm+wm+ac+mw)/3 print("Default Charge is: ",default, "\n\n") rent= int(input("Rent:")) print("Water:300") print("Maintenance:400") print("Electricity:", total_unit) print("Default:", default) due=int(input("Due, if any:")) ad=int(input("Adjusted Amount:")) water=300 maintain=400 bill=(rent+water+maintain+total_unit+default+due)-ad print("\n\nTotal Bill is:----->>>", bill)
17e5dcdb6b83c5023ea428db1e93cc494d6fe405
Parashar7/Introduction_to_Python
/Celsius_to_farenheight.py
217
4.25
4
print("This isa program to convert temprature in celcius to farenheight") temp_cel=float(input("Enter the temprature in Celsius:")) temp_faren= (temp_cel*1.8) +32 print("Temprature in Farenheight is:", temp_faren)
3e052311d7fa93da4d8d7a1c4d4a3c2c8c39e666
shirtsgroup/InterMol
/intermol/atom.py
4,182
3.703125
4
class Atom(object): """ """ def __init__(self, index, name=None, residue_index=-1, residue_name=None): """Create an Atom object Args: index (int): index of atom in the molecule name (str): name of the atom (eg., N, CH) residue_index (int): index of residue in the molecule residue_name (str): name of the residue (eg., THR, CYS) """ self.index = index self.name = name self.residue_index = residue_index self.residue_name = residue_name self._position = list() self._velocity = list() self._force = list() self._atomtype = dict() self.bondingtype = None self.atomic_number = None self.cgnr = None self._mass = dict() self._charge = dict() self.ptype = "A" self._sigma = dict() self._epsilon = dict() @property def atomtype(self): return self._atomtype @atomtype.setter def atomtype(self, index_atomtype): """Sets the atomtype Args: index_atomtype (tuple): A or B state and atomtype """ try: idx, val = index_atomtype except ValueError: raise ValueError("Pass an iterable with two items.") else: self._atomtype[idx] = val @property def sigma(self): return self._sigma @sigma.setter def sigma(self, index_sigma): """Sets the sigma Args: index_sigma (tuple): A or B state and sigma """ try: idx, val = index_sigma except ValueError: raise ValueError("Pass an iterable with two items.") else: self._sigma[idx] = val @property def epsilon(self): return self._epsilon @epsilon.setter def epsilon(self, index_epsilon): """Sets the epsilon Args: index_epsilon (tuple): A or B state and epsilon """ try: idx, val = index_epsilon except ValueError: raise ValueError("Pass an iterable with two items.") else: self._epsilon[idx] = val @property def mass(self): return self._mass @mass.setter def mass(self, index_mass): """Sets the mass Args: index_mass (tuple): A or B state and mass """ try: idx, val = index_mass except ValueError: raise ValueError("Pass an iterable with two items.") else: self._mass[idx] = val @property def charge(self): return self._charge @charge.setter def charge(self, index_charge): """Sets the charge Args: index_charge (tuple): A or B state and charge """ try: idx, val = index_charge except ValueError: raise ValueError("Pass an iterable with two items.") else: self._charge[idx] = val @property def position(self): """Return the cartesian coordinates of the atom """ return self._position @position.setter def position(self, xyz): """Sets the position of the atom Args: xyz (list, float): x, y and z coordinates """ self._position = xyz @property def velocity(self): """Return the velocity of the atom""" return self._velocity @velocity.setter def velocity(self, vxyz): """Sets the velocity of the atom Args: vxyz (list, float): x-, y- and z-directed velocity """ self._velocity = vxyz @property def force(self): """Return the force on the atom """ return self._force @force.setter def force(self, fxyz): """Sets the force on the atom Args: fxyz (list, float): x-, y- and z-directed force """ self._force = fxyz def __repr__(self): return 'Atom{0}({1}, {2})'.format(id(self), self.index, self.name) def __str__(self): return 'Atom({0}, {1})'.format(self.index, self.name)