最初にファイルを読み取り、そのA
内容を変数に保存します ( を使用file.read
)。
with open('A.txt') as f:
data = f.read() # now data is: "This is a test"
# now data is string that dontains all data of the file A.
# But as searching a character in a string is an O(N) operation
# so we must convert this string to a better data-structure.
# As we need the item as well as their first index so we
# should create a dict here, with character as the key and
# it's first appearance(first index) as it's value.
# Dicts provide O(1) lookup.
dic = {}
for ind, char in enumerate(data):
# store the character in dict only if it is an alphabet
# also check if it's already present is dict or not.
if char.isalpha() and char not in dic:
dic[char] = ind
#dic is {'a': 8, 'e': 11, 'i': 2, 'h': 1, 's': 3, 'T': 0, 't': 10}
次に、ファイルを開き、B
for ループを使用して反復処理します。ファイル イテレータに対する for ループは、一度に 1 行ずつ返します (メモリ効率の高いアプローチ)。
with open('B.txt') as f:
for char in f: #iterate one line at a time
char = char.strip() #str.strip strips off whitespaces like '\n'
if char in dic:
print dic[char] # if character is found in dict then
# print it's value, i.e index
...
1
10
3
2
8