text
stringlengths
5
121k
print(str(2)+str(1))
new_list=[''.join(str(y) for x in z for y in x) for z in my_list]
mystr = "path: %s curr: %s prev: %s" % (mydict[path], curr, prev)
import fileinput for line in fileinput.input(filename, inplace=True): print(line.replace(string_to_replace, new_string))
for i in list: print('bla1') print('bla2')
words=f.readlines()
x = "(1,2,3)" t = tuple(int(v) for v in re.findall("[0-9]+", x))
X = [sqrt(2)] for i in range(1,10): X.append(sqrt(2*X[i-1]))
myDic = {} for list in lists: myDic[list[0]] = list[:]
with open(output_file, 'w') as f: for word, count in word_list: f.write("{0}\t{1}\n".format(word, count))
[ x[2] for x in score.keys() if x[0:2] == (0,1)]
def listfiles(directory): return [f for f in os.listdir(directory) if os.path.isdir(os.path.join(directory, f))]
fibonacci(number-1) + fibonacci(number-2)
re.sub(r'<p>(?=[A-Z]{2,})','<i>',MyText)
s = "Kilometer" print(s.lower())
y += [1,3] y = y+[1,3]
[t for t in list_of_tuples if t[1] == n or t[2] == n]
sorted(the_list, key = lambda x: int(x.split("_")[1]))
r, g, b = im.split() im = Image.merge("RGB", (g, g, g))
re.findall("([%]+)([^%]+)(?=([%]+))".replace("%", "".join(VOWELS)), word)
indices = 0, 2 somelist = [i for j, i in enumerate(somelist) if j not in indices]
listo = [('a','1'),('b','0'),('c','2'),('d','0')] minValue = min(listo, key=lambda x: x[1])[1] minValueList = [x for x in listo if x[1] == minValue]
array = [(126,150),(124,154),(123,145),(123,149)] inversed = [(item[1],item[0]) for item in array]
tuple(int(x.strip()) for x in raw_input().split(','))
i = cv2.imread(imgNameIn, cv2.CV_LOAD_IMAGE_COLOR) img = np.array(i, dtype=np.uint16) img *= 256
for key1 in dict: for key2 in dict[key1]: dict[key1][key2]['time'] = 'newTime'
my_str = "(4,301)" num = -int(my_str.translate(None,"(),"))
res = sum(x for x in range(100, 2001) if x % 3 == 0)
location = location + sum(mot[x][1] for x in mot if x in str2)
MyString = MyString.strip(", ").replace(", , ", "")
str1 = '$2a$10$.XfjKl/,abcd, 1, ##, s, for free,2-3-4' parts = str1.split(',') str2 = '{},{},{}'.format(parts[0],'_'.join(parts[1:-1]),parts[-1])
i = 1 data = [[1,10],[2,20],[3,30]] result = [d[i] for d in data]
the_string = raw_input() name, age = the_string.split()
print("Your income tax is ${:,}".format(income))
def slope(x1, y1, x2, y2): return (y1 - y2) / (x1 - x2)
import itertools x = {"a": 600, "b": 75, "c": 75, "d": 90} [(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]
import itertools [''.join(value) for key, value in itertools.groupby(my_str)]
dict = { 'a': [ "hello", "hey", "hi" ] }
for i in mylist: if i not in newlist: newlist.append(i)
splits = x['name'].split() df['first'] = splits.str[0] df['last'] = splits.str[1]
cpt1 = sum(1 for x in liste if x != 2) cpt2 = sum(1 for x in liste if x == 2)
def evenlengthchecker(nestedlist): a = [len(i) for i in nestedlist] return len(set(a)) ==1
from datetime import datetime today = datetime.today() b.utcoffset(today) == c.utcoffset(today)
numrows = len(input) numcols = len(input[0])
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)
new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]
for fruit, colors in fruitdict.items(): print('{} have {} color.'.format(fruit, ' '.join(colors)))
indices = [i for i, s in enumerate(mylist) if 'aa' in s]
def is_square(x): s = int(sqrt(x) + 0.5) return s * s == x
while (userin!="c" or low == high): userin = raw_input()
import re with open('filename', 'r') as f: list1 = [re.split('[(#]+', line.strip())[0].split() for line in f]
chris = {'name': 'chris', 'avg': (test1['chris']+test2['chris']+test3['chris'])/3}
with open('infile.txt') as infile, open('outfile.txt', 'w') as outfile: outfile.write(', '.join(infile.read().split('\n')) + '\n')
for index in range(len(listOne)): listThree.append((listOne[index],listTwo[index]))
chr(ord(ch)+2)
fields = ('name', 'school') match_found = any(all(x[f]==example[f] for f in fields) for x in myList)
def checkString(a, b): return a.lower() in b.lower()
def equalize_lengths(l): length = len(max(l, key=len)) return [e.ljust(length) for e in l]
print('\n', even_count, ' even numbers total to ', even_sum, sep='')
all_my_lists = {} all_my_list[listx[2]] = listx
a += 3 if condition else 1
f.write("value of a is: %d" % (a))
f = open(r"temp.txt") [[c for c in line] for line in f]
age = raw_input("Hello %s, please enter your age" % name)
l[l.index(start): l.index(end) + 1]
sorted([0,1,2,3,4,5], key=lambda x: x == 2, reverse=True)
''' Este es un comentario de varias lineas ''' print('Hola') mivariable = 0 x = 5.10 y = 'Hola Mundo' x1= 5 y2 = 'David' x = 5 x = 'Wilder' print(x) nombre = 'Wilder' nombre2 = "Wilder" print('Nombre 1: ' + nombre + " Nombre 2: " + nombre2) x, y, z = 'Naranja', 'Amarillo', 'Rojo' x = y = z = 'Naran...
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): ...
""" Homeworks - Question 4 """ img= cv2.imread('./imagesHW/hw3_road_sign_school_blurry.JPG',0) im = img.copy() W = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)) for i in range(10): im_d = cv2.dilate(im,W) im_e = cv2.erode(im,W) im_h = cv2.addWeighted(im_d,0.5,im_e,0.5,0) fo...
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: tak...
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 def add(self, key, value=None): ...
"""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 (amy.solman19@imperial.ac.uk)' __version__ = '0.0.1' import sys import pandas as pd import os import math MyDF = pd.read_csv(sys.argv[1...
"""In shell either run using_name.py (for ipython) or python3 using_name.py. Script will generate several different functions using different conditionals.""" if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module') print("Thi...
__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. """ my_dictionary = {"a key": 10, "another key": 11} impo...
friends = ["Joe", "Jack", "Jessica", "Oscar", "Poe", "Tim", "Mike", "Jim"] print(friends) print(friends[-1]) print(friends[1:3])
def testPair(a, b): sum = a + b _min = min(a, b) power = sum // 2 // _min if(sum % 2 == 0 and sum % _min == 0 and (power & (power - 1)) == 0): return False else: return True def solution(banana_list): l = len(banana_list) pairs = [] guards = [{"id": idx, ...
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()
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')
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 el...
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)
""" 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)) : c = match.group(1) return [c] ...
""" 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) ...
""" 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_inst...
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) wh...
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: ...
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): ...
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: ...
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' : ...
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
spam = 0 while spam < 10: print("T'is but a scratch!") spam = spam + 1
def plus_one(num): num = num + 1 if num % 2 == 0: num2 = (num + 1) * 2 print(num2) else: print(num) plus_one(4) plus_one(80) plus_one(33)
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)
string = input() first, last = string.find("h"), string.rfind("h") print(string[:first] + string[last + 1:])
n = int(input()) x = float(input()) total = 0 for _ in range(n + 1): total += float(input()) * x ** n n -= 1 print(total)
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")
string = input() first = string.find("h") last = string.rfind("h") print(string[:first + 1] + string[first + 1: last].replace("h", "H") + string[last:])
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))
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=" ")
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: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: ...
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)