A generating function method for eliminating anomalous diagrams in statistical mechanics