笔试第二道题
题目意思,给定数n,输入n个字符串,n个字符串可能存在相同的,统计每个字符串出现的个数,并降序排序。个数相同则按照字符串字典序排序(小的在前)
今天看了下字典的知识,发现上次的写的代码有些累赘,没必要再开一个set,直接用字典存储。
lst = []
dct = {}
t = int(input('请输入字符串的数目'))
while t:
t -= 1
lst.append(input())
for word in lst:
if word in dct:
dct[word] = dct[word] + 1
else:
dct[word] = 1
x = list(dct.keys())
y = list(dct.values())
for i in range(len(x)):
for j in range(len(y) - 1):
if y[j] < y[j + 1] or (y[j] == y[j + 1] and x[j] < x[j + 1]):
tmp = y[j]
y[j] = y[j + 1]
y[j + 1] = tmp
tmp1 = x[j]
x[j] = x[j + 1]
x[j + 1] = tmp1
print(x, y)
# 存储不相同的字符串
# lst1 = list(set(lst))
# 创建一个字符串和字符串个数的字典
# dct = dict(zip(lst1, [0] * len(lst1)))
#
# for s in lst:
# dct[s] += 1
今天大致看了一下别人的思路,得到如下代码
直接把字符串存在列表,借助set去重,借助dict得到每个字母出现的次数。
lst = []
t = int(input('请输入字符串的数目'))
while t:
t -= 1
lst.append(input())
# 存储不相同的字符串
lst1 = list(set(lst))
# 创建一个字符串和字符串个数的字典
dct = dict(zip(lst1, [0] * len(lst1)))
for s in lst:
dct[s] += 1
x = list(dct.keys())
y = list(dct.values())
for i in range(len(x)):
for j in range(len(y) - 1):
if y[j] < y[j + 1] or (y[j] == y[j + 1] and x[j] < x[j + 1]):
tmp = y[j]
y[j] = y[j + 1]
y[j + 1] = tmp
tmp1 = x[j]
x[j] = x[j + 1]
x[j + 1] = tmp1
print(x, y)
拿到题觉着很简单,我觉着就是一道
结构体排序,但是一直没能过,不知道原因
#include<bits/stdc++.h>
using namespace std;
typedef struct {
string sid;
int num;
}node;
node per[11000];
bool cmp(node a,node b)
{
if(a.num==b.num) return a.sid<b.sid;
return a.num>b.num;
}
int main()
{
int T,cnt=0;
int book=0;
cin>>T;
while(T--)
{
string ss;
cin>>ss;
book=0;
for(int i=0;i<cnt;i++)
{
if(per[i].sid==ss){
per[i].num++;
book=1;
break;
}
}
if(book==0){
per[cnt].sid=ss;
per[cnt].num=1;
cnt++;
}
}
sort(per,per+cnt,cmp);
for(int i=0;i<cnt;i++){
cout<<per[i].sid<<" "<<per[i].num;
if(i!=cnt-1) {cout<<endl;}
}
return 0;
}
笔试第一道题
题目的大概意思就是让你设计一个合格的输入模式。当时过了,但是要考虑的因素有些多,花了些时间
import sys
for line in sys.stdin:
t = line.split()
flag = 1
if (t[0] >= 'a' and t[0] <= 'z') or t[0] == 'NOT':
flag = 1
else:
flag = 0
if not ('a' <= t[len(t) - 1] <= 'z'):
flag = 0
for i in range(1, len(t)):
if t[i] == 'AND':
if not ('a' <= t[i - 1] <= 'z'):
flag = 0
break
elif t[i] == 'NOT':
if not (t[i - 1] == 'OR' or t[i - 1] == 'AND'):
flag = 0
break
elif t[i] == 'OR':
if not ('a' <= t[i - 1] <= 'z'):
flag = 0
break
elif 'a' <= t[i] <= 'z':
if not (t[i - 1] == 'AND' or t[i - 1] == 'NOT' or t[i - 1] == 'OR'):
flag = 0
break
else:
flag = 0
break
print(flag)