大家好,我正在做回文测试。我需要具有3个函数,一个将所有大写字母更改为Lcase,一个将过滤掉非字母的字母,以及一个布尔值,用于检查回文是否为真。到目前为止,这是我的代码
class palindrome
{
public:
palindrome();
void RemovNonCase();
void LowerCase();
bool IsaPalindrome(std::string phrase);
private:
std::string word;
};
#endif
// cpp file
palindrome::palindrome()
{
}
void palindrome::RemovNonCase()
{
int j = 0;
for (int i = 0; word[i] = '\0'; i++)
{
if ((word[i] >= 'a' && word[i] <= 'z')
|| (word[i] >= 'A' && word[i] <= 'Z'))
{
word[j++] = word[i];
}
word[j] = '\0';
}
}
void palindrome::LowerCase()
{
for (int i = 0; i < (word.size() - 1); i++)
{ // lower case testing
word[i] = tolower(word[i]);
}
}
bool palindrome::IsaPalindrome(string phrase)
{
word = phrase;
RemovNonCase();
LowerCase();
int len = word.size();
for (int i = 0; i < len / 2; i++)
{
if (word[i] != word[len - i - 1])
{
return false; // testing if the string is a palindrome
}
}
return true;
}
// main
int main()
{
string phrase;
cout << "Enter a word or a sentence" << endl;
getline(cin, phrase);
palindrome obj1;
if (obj1.IsaPalindrome(phrase))
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
运行此命令时,无论键入什么内容,我只会得到“ NO”。我不确定我的布尔函数在哪里不起作用,我只是没有答案。任何帮助将不胜感激。
答案 0 :(得分:1)
在
import numpy as np
import pandas as pd
import scipy
from scipy.fftpack import fft,fftfreq
import matplotlib.pyplot as plt
import csv
#Function to plot the raw data
def raw_plot(signals,time):
'''Plot the raw values in the time domain '''
plt.figure(0)
plt.plot(time,signals)
plt.xlabel("Time(s)")
plt.ylabel("Amplitude(g)")
plt.show()
#Function to plot the fft of the data
def fft_signal(signal, sampling_frequency, timestart, timeend):
T = 1 / sampling_frequency
N = (timeend - timestart) * sampling_frequency
x = np.linspace(0.0, 1.0 / (2.0 * T), int(N / 2))
# print("Values of X are :",x)
# print(len(x))
yr2 = fft(signal)
y2 = 2 / N * np.abs(yr2[0:int(N / 2)])
# amp_spec = abs(fft(signal))/N
# freq = np.linspace(0,2,num=N)
plt.figure(2)
plt.plot(x, y2)
plt.xlabel("Frequency")
plt.ylabel("Amplitude")
plt.show()
def fftsignal2(data, sampling_freq = 100, timestep = 1 ):
N = len(data)
FS = 1000
T= 1/FS
timestep = timestep
yr2 = fft(data)
y2 = 2 / N * np.abs(yr2[0:int(N / 2)])
# f= np.arange(0,N)*FS/N
# f= np.linspace(0,1.0/T,N)
frq = np.fft.fftfreq(N,d=timestep)
# f= np.linspace(0.0,int(N/2)*sampling_freq)
frq= frq[0:len(frq)//2]
print("Frequencies Length :",len(frq))
print("DATA LENGTH :",len(y2))
plt.figure(3)
plt.plot(frq,y2)
plt.xlabel("Frequency")
plt.ylabel("Amplitude")
plt.show()
Mag1_Hz = 70
Mag1_AMP = 10
Mag4_AMP = 60
Mag4_Hz= 50
Mag2_Hz = 20
Mag2_AMP = 8
time_start = 0
time_end = 4
Sampling_frequency = 100
No_of_samples = (time_end-time_start) * Sampling_frequency
time = np.linspace(time_start,time_end,No_of_samples)
#Generate the signals values
data_signal = Mag1_AMP * np.sin(2* np.pi * Mag1_Hz * time ) + Mag2_AMP * np.cos(2* np.pi * Mag2_Hz * time)
raw_plot(signals=data_signal[:800],time=time[:800])
fft_signal(data_signal,sampling_frequency=Sampling_frequency,timestart=time_start,timeend=time_end)
# for (time, datavalues) in zip(time,data_signal):
# with open("data_signals_27.csv","a",newline="") as file:
# writefile = csv.writer(file)
# print("Time%f,Data %f"%(time,datavalues))
# print(time,datavalues)
# writefile.writerow([time,datavalues])
fftsignal2(data= data_signal, sampling_freq= Sampling_frequency,timestep=2)
函数中,字符串损坏了。在此,您可以根据非字符数用RemovNonCase
覆盖字符串开头的字符。
\0
这是可能的(但未完全优化)的C ++ 11实现:
"ab55ba" => "\0\055ba"
示例输出:
#include <algorithm>
#include <cctype>
#include <iostream>
class Palindrome
{
public:
static void RemoveNonAlphabet(std::string& phrase)
{
auto toRemove = std::remove_if(phrase.begin(), phrase.end(),
[](const char c) {return !std::isalpha(c);});
phrase.erase(toRemove, phrase.end());
}
static void ToLowerCase(std::string& phrase)
{
for (auto& c : phrase)
{
c = std::tolower(c);
}
}
static bool IsPalindrome(std::string phrase)
{
RemoveNonAlphabet(phrase);
ToLowerCase(phrase);
auto start = phrase.begin();
auto rStart = phrase.rbegin();
for (; start != phrase.end(); ++start, ++rStart)
{
if (*start != *rStart)
{
return false;
}
}
return true;
}
};
int main(int argc, char* argv[])
{
std::string phrase;
std::cout << "Enter a word or sentence: ";
std::getline(std::cin, phrase);
std::cout
<< (Palindrome::IsPalindrome(std::move(phrase)) ? "YES" : "NO")
<< std::endl;
}
答案 1 :(得分:-2)
您没有将参数传递为小写并删除非大小写的函数。因此,给出的输出不正确。请比较我的代码:
#include<iostream>
using namespace std;
class palindrome
{
public:
palindrome();
void RemovNonCase(string); //changed
void LowerCase(string); //changed
bool IsaPalindrome(std::string phrase);
private:
std::string word;
};
// cpp file
palindrome::palindrome()
{
}
void palindrome::RemovNonCase(string word)
{
int j = 0;
for (int i = 0; word[i] = '\0'; i++)
{
if ((word[i] >= 'a' && word[i] <= 'z')
|| (word[i] >= 'A' && word[i] <= 'Z'))
{
word[j++] = word[i];
}
word[j] = '\0';
}
}
void palindrome::LowerCase(string word)
{
for (int i = 0; i < (word.size() - 1); i++)
{ // lower case testing
word[i] = tolower(word[i]);
}
}
bool palindrome::IsaPalindrome(string phrase)
{
word = phrase;
RemovNonCase(phrase); //changed
LowerCase(phrase); //changed
int len = word.size();
for (int i = 0; i < len; i++)
{
if (word[i] != word[len - i - 1])
{
return false; // testing if the string is a palindrome
}
}
return true;
}
// main
int main()
{
string phrase;
cout << "Enter a word or a sentence" << endl;
getline(cin, phrase);
palindrome obj1;
if (obj1.IsaPalindrome(phrase))
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
这是输出图片...程序完全正确....如果有任何错误,请共享屏幕截图: https://drive.google.com/open?id=1shHBhFsiTsq2-ZvOpcVhTt4hH_xjdQQW https://drive.google.com/open?id=1u_eT4d7Q1L0j63j-IpPhtZ18KsfIJJuK