#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int s = 0, t = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') t = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9')
    s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
  return s * t;
}
const int N = 505;
const int M = (1 << 16);
const int P = 1e9 + 7;
char s[N];
int n, m, U, Ans, h[16][5];
int Mod(int x) { return x >= P ? x - P : x; }
struct Node {
  int a[M];
  int& operator[](int i) { return a[i]; }
  void Rev() {
    for (int i = 0; i <= U; i++)
      if (i < (U ^ i)) swap(a[i], a[U ^ i]);
  }
  void FMT() {
    for (int i = 1; i <= U; i <<= 1)
      for (int j = 0; j <= U; j += (i << 1))
        for (int k = 0; k < i; k++) a[i + j + k] = Mod(a[i + j + k] + a[j + k]);
  }
  void IFMT() {
    for (int i = 1; i <= U; i <<= 1)
      for (int j = 0; j <= U; j += (i << 1))
        for (int k = 0; k < i; k++)
          a[i + j + k] = Mod(a[i + j + k] + P - a[j + k]);
  }
} f[N];
Node operator|(Node A, Node B) {
  A.FMT(), B.FMT();
  for (int i = 0; i <= U; i++) A[i] = 1ll * A[i] * B[i] % P;
  return A.IFMT(), A;
}
Node operator&(Node A, Node B) {
  A.Rev(), B.Rev();
  return A = A | B, A.Rev(), A;
}
Node operator+(Node A, Node B) {
  for (int i = 0; i <= U; i++) A[i] = Mod(A[i] + B[i]);
  return A;
}
void DFS(int x, int l, int r) {
  if (r - l <= 2) {
    int d = 0, u = 0, f0 = 0, f1 = 0, p = l + (r > l);
    if (s[p] == '?')
      f0 = f1 = 1, d = 0, u = 3;
    else if (s[p] <= 'D')
      f0 = 1, d = u = s[p] - 'A';
    else
      f1 = 1, d = u = s[p] - 'a';
    for (int c = d; c <= u; c++) {
      int S = 0;
      for (int i = 0; i < m; i++) S |= h[i][c] << i;
      f[x][S] += f0, f[x][U ^ S] += f1;
    }
    return;
  }
  for (int t = 0, d = l; d <= r; d++) {
    if (s[d] == '(')
      t++;
    else if (s[d] == ')')
      t--;
    else if (!t) {
      DFS(d - 1, l + 1, d - 2), DFS(d + 1, d + 2, r - 1);
      if (s[d] == '&' || s[d] == '?') f[x] = f[x] + (f[d - 1] & f[d + 1]);
      if (s[d] == '|' || s[d] == '?') f[x] = f[x] + (f[d - 1] | f[d + 1]);
    }
  }
}
int main() {
  scanf("%s", s + 1), n = strlen(s + 1);
  m = read(), U = (1 << m) - 1;
  for (int i = 0; i < m; i++) {
    for (int j = 0; j <= 4; j++) h[i][j] = read();
    Ans |= h[i][4] << i;
  }
  DFS(1, 1, n), printf("%d", f[1][Ans]);
  return 0;
}
