-5

I have data which looks something like

data = [('h'), (('j','kjjy')), ((('khg','hello')))]

I would like to be able to recursively search for 'hello' and just return true or false but I am not sure how to do it.

Emiliano Ruiz
  • 412
  • 4
  • 16
m_bash
  • 103
  • 2
  • 3
    What have you tried? Please see [ask]. – r.ook Jan 24 '20 at 15:58
  • 2
    Does this answer your question? [Flatten Nested Tuples](https://stackoverflow.com/questions/52573594/flatten-nested-tuples) …More: [How do I Flatten Deeply Nested Tuples?](https://stackoverflow.com/questions/55496318/how-do-i-flatten-deeply-nested-tuples) , [Flattening a shallow list in Python](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) , [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – wwii Jan 24 '20 at 15:59
  • for item in array: if item is string, check if it's hello. If item is iterable, call recursively. – Gillespie Jan 24 '20 at 16:09

3 Answers3

0

Here is an example:

import numpy as np

array = np.asarray(a)

def searchForWord(array, word):

    #base case
    if (array.size == 0) return false

    #recursive case
    if word in array[0] return true


    array = np.delete(array, 0)
    searchForWord(array, word)



You may have an issue because the numpy array would be an array of tuples. Just let me know if it works.

0
a=[('h'), (('j','kjjy')), ((('khg','hello')))]

for x in range(len(a)):
    tup = a[x]
    print(tup)
    print('hello' in tup)

Output:

h
False
('j', 'kjjy')
False
('khg', 'hello')
True
Mike Reddington
  • 192
  • 2
  • 15
0

You can do this recursively:

def find(text, data):
    # loop over all items (tuples or strings)
    for item in data:
        # if it's a tuple, recurse
        if isinstance(item, tuple): 
            if find(text, item): 
                return True 
        # if it's a string and a match return true
        if item==text: 
            return True 
    return False 
m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
Jordan Dimov
  • 1,268
  • 12
  • 26