鱼C论坛

 找回密码
 立即注册
查看: 30835|回复: 21

题目22:文件中所有名字的得分之和是多少?

[复制链接]
发表于 2015-4-23 16:23:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 永恒的蓝色梦想 于 2020-7-31 10:42 编辑
Names scores

Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?

题目:

文件 names.txt 是一个 46K 大小的文本文件,包含 5000 多个英文名字。利用这个文件,首先将文件中的
名字按照字母排序,然后计算每个名字的字母值,最后将字母值与这个名字在名字列表中的位置相乘,得到这个名字的得分。

例如将名字列表按照字母排序后, COLIN 这个名字是列表中的第 938 个,它的字母值是 3 + 15 + 12 + 9 + 14 = 53。

所以 COLIN 这个名字的得分就是 938 × 53 = 49714.

文件中所有名字的得分总和是多少?

评分

参与人数 1贡献 +3 收起 理由
cwhsmile + 3 平均0.08秒

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2016-8-29 10:16:11 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-8-29 10:19:01 | 显示全部楼层
  1. f = open('names.txt')
  2. dic = {
  3.       'A':1,
  4.       'B':2,
  5.       'C':3,
  6.       'D':4,
  7.       'E':5,
  8.       'F':6,
  9.       'G':7,
  10.       'H':8,
  11.       'I':9,
  12.       'J':10,
  13.       'K':11,
  14.       'L':12,
  15.       'M':13,
  16.       'N':14,
  17.       'O':15,
  18.       'P':16,
  19.       'Q':17,
  20.       'R':18,
  21.       'S':19,
  22.       'T':20,
  23.       'U':21,
  24.       'V':22,
  25.       'W':23,
  26.       'X':24,
  27.       'Y':25,
  28.       'Z':26}
  29. list1 = []
  30. name = ''
  31. for each in f:
  32.       for i in each:
  33.             if i ==',':
  34.                   list1.append(name)
  35.                   name = ''
  36.             else:
  37.                   if i !='"':
  38.                         name += i
  39.       list1.append(name)  
  40. list2=[]
  41. while True:
  42.       length = len(list1)
  43.       first = list1[0]
  44.       for i in range(1,length):
  45.             if len(first) > len(list1[i]):
  46.                   temp = len(list1[i])
  47.             else:
  48.                   temp = len(first)
  49.             for n in range(temp):
  50.                   if dic[first[n]] > dic[list1[i][n]]:
  51.                         first = list1[i]
  52.                         break
  53.                   elif dic[first[n]] < dic[list1[i][n]]:
  54.                         first = first
  55.                         break
  56.                   elif dic[first[n]] == dic[list1[i][n]]:
  57.                         if n == temp - 1:
  58.                               if len(first) < len(list1[i]):
  59.                                     first = first
  60.                                     break
  61.                               else:
  62.                                     first = list1[i]
  63.                                     break
  64.                         continue
  65.       list2.append(first)
  66.       list1.remove(first)
  67.       if not len(list1):
  68.             break
  69. total = 0
  70. for each in list2:
  71.       count = 0
  72.       for i in each:
  73.             count +=dic[i]
  74.       total += count * (list2.index(each)+1)
  75. print(total)
复制代码


答案是871198282
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-10-11 23:09:49 | 显示全部楼层
本帖最后由 永恒的蓝色梦想 于 2020-6-6 08:48 编辑
  1. 871198282
  2. [Finished in 0.4s]

  3. Name = ["MARY","PATRICIA",...,"PORTER","LEIF","JERAMY","BUCK","WILLIAN","VINCENZO","SHON","LYNWOOD","JERE","HAI","ELDEN","DORSEY","DARELL","BRODERICK","ALONSO"]
  4. ABC = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
  5. Name.sort()
  6. total = 0
  7. for (k,each) in enumerate(Name, start = 1):
  8.         score = 0
  9.         for l in range(len(each)):
  10.                 for (i,words) in enumerate(ABC, start = 1):
  11.                         if each[l] == words:
  12.                                 score += i
  13.         score *= k
  14.         total += score
  15. print total
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-1-21 13:38:05 | 显示全部楼层
本帖最后由 渡风 于 2017-1-21 13:43 编辑

此代码使用matlab编程
Problem22所用时间为0.89201秒
Problem22的答案为871198282
文本跟楼上的链接一样,哎,不能贴上文件
  1. %% 题目22:文件中所有英文总得分是多少        
  2. %读取数据
  3. function Ouput=Problem22(Input)
  4. tic
  5. if nargin==0
  6. Input=importdata('Name.txt');
  7. end
  8. B=char(Input);
  9. C=strrep(B,'"','');%字符串替换,将"带替为’
  10. C=[',',C,','];
  11. Num=0;%逗号的数量,Num-1为名字的个数
  12. Set=[];
  13. for ii=1:length(C)
  14.     if C(ii)==','
  15.         Temp=[Set,ii];%将','的位置记录下来
  16.         Set=Temp;
  17.         Num=Num+1;
  18.     end
  19. end
  20. Name{1,Num-1}=[];%记录字符串
  21. for jj=1:Num-1
  22.     Name{jj}=C(Set(jj)+1:Set(jj+1)-1);%将字符串分类
  23. end
  24. %% 数据处理
  25. Name=sort(Name);%对名字进行排序
  26. Score=zeros(1,Num-1);
  27. for jj=1:Num-1
  28.     Score(jj)=Letter_Score(Name{jj});
  29. end
  30. Result=Score.*(1:Num-1);
  31. Output=sum(Result);
  32. toc
  33. disp('此代码使用matlab编程')
  34. disp(['Problem22所用时间为',num2str(toc),'秒'])
  35. disp(['Problem22的答案为',num2str(Output)])
  36. end
  37. %% 子程序
  38. %输入一个字母字符串,得到其相应的分数,A得1,B得2...Z得26
  39. function Output=Letter_Score(Input)
  40. if nargin==0
  41. Input='ABCD';
  42. end
  43. lett={'a','b','c','d','e','f','g','h','i','j','k','l',...
  44.     'M','N','o','p','q','r','s','t','u','v','w','x','y','z'};%a-z
  45. Lett={'A','B','C','D','E','F','G','H','I','J','K','L',...
  46.     'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};%A-Z
  47. Score=0;
  48. L=length(Input);
  49. for ii=1:L
  50.     Temp=Input(ii);
  51.     for jj=1:26
  52.         if Temp==Lett{jj}||Temp==lett{jj}
  53.             Score=Score+jj;
  54.         end
  55.     end
  56. end
  57. Output=Score;
  58. end

  59.             
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-3-7 17:49:19 | 显示全部楼层
871198282
used:0.02100110s


  1. import time
  2. start=time.time()
  3. f=open("p022_names.txt",'r')
  4. name_lists=f.read().replace(""","").split(",")
  5. f.close()
  6. name_lists.sort()
  7. sum=0
  8. for index,i in enumerate(name_lists):
  9.     subsum=0
  10.     for char in i:
  11.         subsum+=ord(char)-64
  12.     sum+=(index+1)*subsum
  13. print (sum)
  14. print("used:%.8fs" % (time.time()-start))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2017-3-9 00:26:39 | 显示全部楼层
  1. # 读文件,大写/小写 排序,我注释了大写版本
  2. with open('022_data.txt','r') as f:
  3.     names = f.read().split(",")
  4.     # names = sorted([n.replace('"','').upper() for n in names])
  5.     names = sorted([n.replace('"','').lower() for n in names])

  6. # ASCII码自己百度一下就可以了
  7. def mark(a):
  8.     # return int(ord(a) - 64)
  9.     return int(ord(a) - 96)

  10. sum_mark = 0
  11. for i,name in enumerate(names):
  12.     name_mark = sum([mark(i) for i in name])
  13.     sum_mark += name_mark * (i+1)
  14. print('答案是: ' + str(sum_mark))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-3-22 15:22:54 | 显示全部楼层
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class Problem22 {

        public static void main(String[] args) {
                File file=new File("resources/txt/problem22.txt");
                BufferedReader reader=null;
                if(file.isFile()&&file.exists()){
                        try {
                                InputStreamReader read=new InputStreamReader(new FileInputStream(file), "UTF-8");
                                reader=new BufferedReader(read);
                                String lineText="";
                                String result="";
                                while((lineText=reader.readLine())!=null){
                                        result=lineText;
                                }
                                String arr[]=result.replaceAll("\"", "").split(",");
                                long sum=0;
                                for(int pos=0;pos<arr.length;pos++){
                                        long perResult=0;
                                        int[] cs= arr[pos].chars().toArray();
                                        for(int i:cs){
                                                perResult+=i-64;
                                        }
                                        perResult=perResult*(pos+1);
                                        sum+=perResult;
                                }                               
                                System.out.println(sum);
                                System.out.println(arr[0]);
                                System.out.println(arr[arr.length-1]);
                        } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                        } catch (FileNotFoundException e) {
                                e.printStackTrace();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }finally {
                               
                        }
                }else{
                        System.out.println("文件problem22.txt不存在或类型错误!");
                }
        }
}


输出结果
850081394
MARY
ALONSO


文档是欧拉计划上下载的,不知道哪里出了问题,感觉没问题
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-5-23 15:34:03 | 显示全部楼层
  1. f = open("names.txt","r")
  2. name = f.read().replace(""","").split(",")
  3. name.sort()    #排序列表
  4. jisu = num =0
  5. nm=1
  6. for i in name:
  7.     for j in i:
  8.         num += (ord(j)-64)
  9.      jisu += num*nm
  10.      num =0
  11.      nm+=1
  12. print(jisu)
复制代码

列表元素从1开始计算的
计算结果:871198282
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-6 11:25:01 | 显示全部楼层
进击的小蜗牛 发表于 2017-5-23 15:34
列表元素从1开始计算的
计算结果:871198282

因为还没有做排序
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-7-30 17:26:25 | 显示全部楼层
来一个剑走偏锋~
先用excel vba处理数据格式
  1. Option Explicit

  2. Public Sub PE22()
  3.     Open "pe22.txt" For Input As #1
  4.     Dim s As String
  5.     Dim cnt As Integer
  6.     cnt = 1
  7.     Do Until EOF(1)
  8.         Input #1, s
  9.         Range("a" & CStr(cnt)).Value = s
  10.         cnt = cnt + 1
  11.     Loop
  12.     Close #1
  13. End Sub
复制代码

对a列升序排序后,将结果复制到in.txt中
  1. #include<sstream>
  2. #include<iostream>
  3. #include<cstdio>
  4. #include<cstdlib>
  5. #include<cmath>
  6. #include<ctime>
  7. #include<cstring>
  8. #include<string>
  9. #include<vector>
  10. #include<set>
  11. #include<map>
  12. #include<algorithm>
  13. #include<queue>
  14. #include<stack>
  15. #include<list>
  16. #define ICRS(i,ini,end) for (int i = ini;i < end;i++)//increase,i.e.ICS(i,0,n)
  17. #define DCRS(i,ini,end) for (int i = ini - 1;i >= end;i--)//decrease,i.e.DCS(i,n,0)
  18. #define MEM(x,y) memset(x,y,sizeof(x))
  19. #define LOCAL
  20. #define TEST
  21. using namespace std;
  22. typedef long long ll;
  23. const int M = 100 + 10;
  24. const int INF = 1e9;
  25. const double EPS = 1e-6;
  26. int pts(const string & s){
  27.   int sum = 0;
  28.   ICRS(i,0,s.length())  sum += s[i] - 'A' + 1;
  29.   return sum;
  30. }

  31. int main(){
  32.         #ifdef LOCAL
  33.                 freopen("i.in","r",stdin);
  34.         #endif // LOCAL
  35.   int cnt = 0;
  36.   int sum = 0;
  37.   string s;
  38.   while(cin >> s){
  39.     sum += pts(s) * ++cnt;
  40.   }
  41.   cout << sum;
  42.         return 0;
  43. }
复制代码

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +5 收起 理由
永恒的蓝色梦想 + 5 + 5 + 5

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-7-30 17:27:43 | 显示全部楼层
debuggerzh 发表于 2020-7-30 17:26
来一个剑走偏锋~
先用excel vba处理数据格式

pe22.txt即为欧拉计划源文档
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-7-30 18:08:07 | 显示全部楼层
debuggerzh 发表于 2020-7-30 17:26
来一个剑走偏锋~
先用excel vba处理数据格式

好多头文件啊
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-7-31 10:23:03 | 显示全部楼层

竞赛题模板hhh
用万能头也行
  1. #include<bits/stdc++.h>
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-7-31 10:31:40 | 显示全部楼层
debuggerzh 发表于 2020-7-31 10:23
竞赛题模板hhh
用万能头也行

哈哈哈,我这里用不了万能头

你是这道题解封后的第一个回答者,给你评个分
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-7-31 11:18:28 | 显示全部楼层
本帖最后由 永恒的蓝色梦想 于 2020-9-12 13:11 编辑
  1. #include<iostream>
  2. #include<fstream>
  3. #include<string>
  4. #include<algorithm>
  5. #include<vector>
  6. using namespace std;



  7. template<class File, class Container>
  8. void read(File& file, Container& container)noexcept {
  9.     string str;


  10. label:
  11.     if (file) {
  12.         if (file.get() == '"') {
  13.             if (getline(file, str, '"')) {
  14.                 container.push_back(str);
  15.                 goto label;
  16.             }
  17.         }
  18.         else {
  19.             goto label;
  20.         }
  21.     }
  22. }



  23. int main() {
  24.     ios::sync_with_stdio(false);

  25.     ifstream file("p022_names.txt");
  26.     vector<string>names;
  27.     size_t index = 0;
  28.     unsigned long long sum = 0;
  29.     unsigned short temp;


  30.     read(file, names);
  31.     sort(names.begin(), names.end());


  32.     while (index < names.size()) {
  33.         temp = 0;

  34.         for (char ch : names[index]) {
  35.             temp += ch - 64;
  36.         }

  37.         index++;
  38.         
  39.         sum += temp * index;
  40.     }


  41.     cout << sum << endl;
  42.     return 0;
  43. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-7-31 15:25:32 | 显示全部楼层
本帖最后由 永恒的蓝色梦想 于 2020-7-31 15:28 编辑

Python 一行:
  1. print(sum(index * sum(ord(char) - 64 for char in name) for index, name in enumerate(sorted(eval(open("p022_names.txt").read())), 1)))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-7-31 16:52:21 | 显示全部楼层
永恒的蓝色梦想 发表于 2020-7-31 10:31
哈哈哈,我这里用不了万能头

你是这道题解封后的第一个回答者,给你评个分

感谢~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-3-9 20:09:43 | 显示全部楼层
本帖最后由 a1351468657 于 2021-3-10 11:45 编辑
  1. f = open('names.txt', 'r')

  2. temp = f.read().replace('"', '')
  3. name = temp.split(',')
  4. name.sort()

  5. f.close()
  6. sum1 = 0
  7. len1 = len(name)
  8. for i in range(len1):
  9.     length = len(name[i])
  10.     count = 0
  11.     for j in range(length):
  12.         count += ord(name[i][j]) - 64
  13.     sum1 += count * (i + 1)

  14. print(sum1)
复制代码


我用C语言想了一下午怎么排序,然后想出来了,发现数据量太大,能力有限。直接转用Python, 5分钟不到出来了。。。。
希望哪位大佬用C语言写出来能@我一下,谢谢!


睡了一觉,突然想到甲鱼老师在带你学C带你飞中教的快速排序算法,然后复制了一下(自己只知道原理但是代码实现还是有点困难),最后排序完成,成功解决最难的一步,排好序就好算多了。
若有问题,希望大佬指导一下!

  1. #include <stdio.h>
  2. #include <string.h>


  3. void quick_sort(char array[][20], int left, int right);

  4. void quick_sort(char array[][20], int left, int right)
  5. {
  6.         int i = left, j = right;
  7.         char temp[20];
  8.         char pivot[20];
  9.         strcpy(pivot, array[((left + right) / 2)]);

  10.         // 基准点设置为中间元素,你也可以选择其它元素作为基准点
  11.        

  12.         while (i <= j)
  13.         {
  14.                 // 找到左边大于等于基准点的元素
  15.                 while (strcmp(array[i], pivot) < 0)
  16.                 {
  17.                         i++;
  18.                 }
  19.                 // 找到右边小于等于基准点的元素
  20.                 while (strcmp(array[j], pivot) > 0)
  21.                 {
  22.                         j--;
  23.                 }
  24.                 // 如果左边下标小于右边,则互换元素
  25.                 if (i <= j)
  26.                 {
  27.                         strcpy(temp, array[i]);
  28.                         strcpy(array[i], array[j]);
  29.                         strcpy(array[j], temp);
  30.                
  31.                        
  32.                         i++;
  33.                         j--;
  34.                 }
  35.         }

  36.         if (left < j)
  37.         {
  38.                 quick_sort(array, left, j);
  39.         }

  40.         if (i < right)
  41.         {
  42.                 quick_sort(array, i, right);
  43.         }

  44. }



  45. int main()
  46. {
  47.         FILE *fp;
  48.         fp = fopen("names.txt", "r");
  49.        
  50.         char ch, name[6000][20];
  51.         int i = 0, j = 0, k, sum = 0;
  52.        
  53.         while (!feof(fp))//将文件中名字写入字符串数组name中
  54.         {
  55.                 ch = fgetc(fp);

  56.                 if (ch == '"')
  57.                 {
  58.                         j = 0;
  59.                         goto Label;
  60.                 }
  61.                 if (ch == '\n')
  62.                 {
  63.                         goto Label;
  64.                 }
  65.                 else
  66.                 {
  67.                         if (ch == ',')
  68.                         {
  69.                                 i++;
  70.                         }
  71.                         else
  72.                         {
  73.                                 name[i][j] = ch;
  74.                                 name[i][j + 1] = '\0';
  75.                                 j++;
  76.                         }
  77.                 }
  78.         Label:continue;
  79.         }
  80.         fclose(fp);
  81.         k = i - 1;
  82.         quick_sort(name, 0, k);
  83.        
  84.         for (i = 0; i <= k; i++)
  85.         {
  86.                 for (j = 0; name[i][j] != '\0'; j++)
  87.                 {
  88.                         sum += (name[i][j] - 64) * (i + 1);
  89.                 }
  90.         }

  91.         printf("%d", sum);
  92.         return 0;
  93. }
复制代码


答案:871198282;
秒出的;
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-10-15 14:58:59 | 显示全部楼层
#文件中所有名字的得分之和
with open("C:\\Users\\Administrator\\Desktop\\names.txt") as f:
    s = f.read()
s = s.split(',')
s.sort()
d = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, \
     'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10, \
     'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, \
     'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20, \
     'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26}
each_name_letter = 0
each_name_score = 0
name_score = 0
i = 0
while True:
    for j in s[i]:
        if j != '"':
            each_name_letter += d[j]
    each_name_score = each_name_letter * (i+1)
    name_score += each_name_score
    i += 1
    each_name_letter = 0
    each_name_score = 0
    if i == len(s):
        break
print(name_score)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-28 21:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表