Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return (-1, -1).
For example, find_two_sum([1, 3, 5, 7, 9], 12) should return a tuple containing any of the following pairs of indices:
1 and 4 (3 + 9 = 12)
2 and 3 (5 + 7 = 12)
3 and 2 (7 + 5 = 12)
4 and 1 (9 + 3 = 12)
In [7]:
# Это единственный комментарий который имеет смысл
# I s
def find_index(m,a):
try:
return a.index(m)
except :
return -1
def find_two_sum(a, s):
'''
>>> (3, 5) == find_two_sum([1, 3, 5, 7, 9], 12)
True
'''
if len(a)<2:
return (-1,-1)
idx = dict( (v,i) for i,v in enumerate(a) )
for i in a:
m = s - i
k = idx.get(m,-1)
if k != -1 :
return (i,k)
return (-1, -1)
print(find_two_sum([1, 3, 5, 7, 9], 12))
if __name__ == '__main__':
import doctest; doctest.testmod()
https://stackoverflow.com/questions/28309430/edit-ipython-cell-in-an-external-editor
This is what I came up with. I added 2 shortcuts:
Just execute this cell to enable these features:
In [14]:
%%javascript
IPython.keyboard_manager.command_shortcuts.add_shortcut('g', {
handler : function (event) {
var input = IPython.notebook.get_selected_cell().get_text();
var cmd = "f = open('.toto.py', 'w');f.close()";
if (input != "") {
cmd = '%%writefile .toto.py\n' + input;
}
IPython.notebook.kernel.execute(cmd);
//cmd = "import os;os.system('open -a /Applications/MacVim.app .toto.py')";
//cmd = "!open -a /Applications/MacVim.app .toto.py";
cmd = "!code .toto.py";
IPython.notebook.kernel.execute(cmd);
return false;
}}
);
IPython.keyboard_manager.command_shortcuts.add_shortcut('u', {
handler : function (event) {
function handle_output(msg) {
var ret = msg.content.text;
IPython.notebook.get_selected_cell().set_text(ret);
}
var callback = {'output': handle_output};
var cmd = "f = open('.toto.py', 'r');print(f.read())";
IPython.notebook.kernel.execute(cmd, {iopub: callback}, {silent: false});
return false;
}}
);
In [49]:
# v=getattr(a, 'pop')(1)
s='print 4 7 '
commands={
'print':print,
'len':len
}
def exec_string(s):
global commands
chunks=s.split()
func_name=chunks[0] if len(chunks) else 'blbl'
func=commands.get(func_name,None)
params=[int(x) for x in chunks[1:]]
if func:
func(*params)
exec_string(s)
https://www.hackerrank.com/challenges/symmetric-difference/problem
Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both.
The first line of input contains an integer, . The second line contains space-separated integers. The third line contains an integer, . The fourth line contains space-separated integers.
Output the symmetric difference integers in ascending order, one per line.
4
2 4 5 9
4
2 4 11 12
5
9
11
12
In [5]:
M = int(input())
m =set((map(int,input().split())))
N = int(input())
n =set((map(int,input().split())))
In [9]:
m ^ n
Out[9]:
In [35]:
S='add 5 6'
method, *args = S.split()
print(method)
print(*map(int,args))
method,(*map(int,args))
# methods
# (*map(int,args))
# command='add'.split()
# method, args = command[0], list(map(int,command[1:]))
# method, args
Out[35]:
In [40]:
for _ in range(2):
met, *args = input().split()
print(met, args)
try:
pass
# methods[met](*list(map(int,args)))
except:
pass
In [13]:
class Stack:
def __init__(self):
self.data = []
def is_empty(self):
return self.data == []
def size(self):
return len(self.data)
def push(self, val):
self.data.append(val)
def clear(self):
self.data.clear()
def pop(self):
return self.data.pop()
def __repr__(self):
return "Stack("+str(self.data)+")"
Out[13]:
In [39]:
def sum_list(ls):
if len(ls)==0:
return 0
elif len(ls)==1:
return ls[0]
else:
return ls[0] + sum_list(ls[1:])
def max_list(ls):
print(ls)
if len(ls)==0:
return None
elif len(ls)==1:
return ls[0]
else:
m = max_list(ls[1:])
return ls[0] if ls[0]>m else m
def reverse_list(ls):
if len(ls)<2:
return ls
return reverse_list(ls[1:])+ls[0:1]
def is_ana(s=''):
if len(s)<2:
return True
return s[0]==s[-1] and is_ana(s[1:len(s)-1])
print(is_ana("abc"))
In [20]:
import turtle
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
def drawSpiral(myTurtle, lineLen):
if lineLen > 0:
myTurtle.forward(lineLen)
myTurtle.right(90)
drawSpiral(myTurtle,lineLen-5)
drawSpiral(myTurtle,100)
# myWin.exitonclick()
In [13]:
t.forward(100)
In [55]:
from itertools import combinations_with_replacement
list(combinations_with_replacement([1,1,3,3,3],2))
Out[55]:
In [62]:
hash((1,2))
Out[62]:
In [104]:
# 4
# a a c d
# 2
from itertools import combinations
# N=int(input())
# s=input().split()
# k=int(input())
s='a a c d'.split()
k=2
combs=list(combinations(s,k))
print('{:.4f}'.format(len([x for x in combs if 'a' in x])/len(combs)))
# ------------------------------------------
import random
num_trials=10000
num_found=0
for i in range(num_trials):
if 'a' in random.sample(s,k):
num_found+=1
print('{:.4f}'.format(num_found/num_trials))
In [108]:
dir(5)
Out[108]:
In [ ]: