#include<iostream>
#include<vector>
using namespace std;
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n)   REP(i,0,n)

int cnt=0;

#define A 0
#define O 1
#define X 2

class state{
public:
  int num[(1<<4)];
  
};
const int lim = ( 1 << 4);
int table[8][(1<<4)];
int data[8];

state parse(string &in,int &p){
  state ret;
  rep(i,lim)ret.num[i]=0;
  if ( in[p]== '('){
    p++;
    state left = parse(in,p);
    p++;//space
    state right =parse(in,p);
    p++;


    rep(i,lim){
      rep(j,lim){
	int val1=i&j,val2=i|j,val3=i^j;

	int add=left.num[i]*right.num[j];
	ret.num[val1]+=add;
	ret.num[val2]+=add;
	ret.num[val3]+=add;
      }
    }
  }else if ( in[p] <='9' && in[p] >='0'){
    int now = in[p]-'0';
    now--;
    ret.num[data[now]]=1;
    p++;
  }
  return ret;
}


main(){
  string t;
  while(getline(cin,t) && t != "END"){
    int n;
    cin>>n;
    
    int num=0;
    int p=0;
    rep(i,n){
      data[i]=0;
      int kari;
      rep(j,4)cin>>kari,data[i]|=(kari<<j);
    }
    
    state ans = parse(t,p);
    cout << ans.num[(1<<4)-1]<<endl;
    getline(cin,t);
  }
  return false;
}

  