鱼C论坛

 找回密码
 立即注册
查看: 3021|回复: 13

题目42:这个英语词列表里共有多少个三角形词?

[复制链接]
发表于 2015-5-2 12:11:29 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 欧拉计划 于 2015-5-2 12:20 编辑
Coded triangle numbers

The BaiduShurufa_2015-5-2_11-43-53.png term of the sequence of triangle numbers is given by, BaiduShurufa_2015-5-2_11-44-28.png ; so the first ten triangle numbers are:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is BaiduShurufa_2015-5-2_11-53-34.png   If the word value is a triangle number then we shall call the word a triangle word.

Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?

题目:

三角形数序列中第 n 项的定义是: BaiduShurufa_2015-5-2_11-44-28.png ;此前十个三角形数是:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

通过将一个单词中每个字母在字母表中的位置值加起来:我们可以将一个单词转换为一个数。例如,单词 SKY 的值为 BaiduShurufa_2015-5-2_11-53-34.png 如果单词的值是一个三角形数,我们称这个单词为三角形单词。

p042_words.txt (15.96 KB, 下载次数: 47) (右键另存为)是一个 16K 的文本文件,包含将近两千个常用英语单词。在这个文件中,一共有多少个三角形词?

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

使用道具 举报

发表于 2016-8-30 13:58:52 | 显示全部楼层
不是很懂题目意思。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-9-7 12:49:38 | 显示全部楼层
  1. dic = {
  2.       'A':1,
  3.       'B':2,
  4.       'C':3,
  5.       'D':4,
  6.       'E':5,
  7.       'F':6,
  8.       'G':7,
  9.       'H':8,
  10.       'I':9,
  11.       'J':10,
  12.       'K':11,
  13.       'L':12,
  14.       'M':13,
  15.       'N':14,
  16.       'O':15,
  17.       'P':16,
  18.       'Q':17,
  19.       'R':18,
  20.       'S':19,
  21.       'T':20,
  22.       'U':21,
  23.       'V':22,
  24.       'W':23,
  25.       'X':24,
  26.       'Y':25,
  27.       'Z':26}

  28. def San():
  29.       list1 = []
  30.       for i in range(10000):
  31.             list1.append(i*(i+1)/2)
  32.       return list1
  33. list1 = []
  34. f = open('word.txt')
  35. for word in f:
  36.       str_1 = ''
  37.       for each in word:
  38.             if each != '"':
  39.                   str_1 += each
  40.       list1.append(str_1)
  41. count = 0
  42. list2 = []
  43. for each in list1:
  44.       for i in each:
  45.             if i == ',':
  46.                   list2.append(count)
  47.                   count = 0
  48.             else:
  49.                   count += dic[i]
  50. list2.append(count)

  51. list3 = San()
  52. total = 0
  53. for each in list2:
  54.       if each in list3:
  55.             total += 1
  56. print(total)
复制代码

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

使用道具 举报

发表于 2016-10-8 11:31:40 | 显示全部楼层
  1. count = 0 #用于记数
  2. num = lambda s: sum(int(ord(i))-64 for i in s) #计算每个单词的值
  3. list0 = [0.5*i*(i+1) for i in range(100)] #生成一个三角数的list
  4. with open("p042_words.txt","r") as f:
  5.     text = f.read()
  6. for x in text.replace(""","").split(","): #对文本处理,生成单词列表
  7.     if num(x) in list0:
  8.         count += 1
  9. print(count)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-1-15 11:43:16 | 显示全部楼层
  1. # encoding:utf-8
  2. # 查找三角形单词个数
  3. from time import time
  4. def euler042():
  5.     l_trinum = [int(i * (i + 1) / 2) for i in range(30)]
  6.     d_abc = {'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}
  7.     count = 0
  8.     with open('p042_words.txt') as f:
  9.         l_text = f.read().replace('"', '').split(',')
  10.     for each in l_text:
  11.         w_n = 0
  12.         for t in [w for w in list(each)]:
  13.             w_n += d_abc.get(t)
  14.         if w_n in l_trinum:
  15.             count += 1
  16.     print(count)   
  17. if __name__ == '__main__':
  18.     start = time()
  19.     euler042()
  20.     print('cost %.6f sec' % (time() - start))
复制代码

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

使用道具 举报

发表于 2017-6-12 22:44:37 | 显示全部楼层
%% Problem42.m
%最后编辑时间:2017-06-12 22:10 版本1.0
%找出转换值为三角形数值得单词数
% Problem42所用时间为0.17588秒
% Problem42的答案为162
  1. %% Problem42.m
  2. %最后编辑时间:2017-06-12 22:10 版本1.0
  3. %找出转换值为三角形数值得单词数
  4. % Problem42所用时间为0.17588秒
  5. % Problem42的答案为162
  6. function Output = Problem42()
  7. tic
  8. Output = 0;
  9. Data = importdata('p042_words.txt');
  10. Data = cell2mat(Data);

  11. Qua = 0;             %引号个数
  12. QuaLoca = [];        %引号位置
  13. for ii = 1:length(Data)
  14.     if strcmp(Data(ii),'"') == 1
  15.         Qua = Qua + 1;
  16.         QuaLoca = [QuaLoca,ii];
  17.     end
  18. end

  19. Words = cell(1, Qua /2);
  20. for jj = 1:length(Words)
  21.     Words{jj} = Data(QuaLoca(jj*2-1)+1 : QuaLoca(jj*2)-1); %提取两个引号之间的字母
  22.     if  IsTriNum(Words{jj}) == 1;
  23.         Output = Output + 1;
  24.     end
  25. end

  26. toc

  27. disp('此代码使用matlab编程')
  28. disp(['Problem42所用时间为',num2str(toc),'秒'])
  29. disp(['Problem42的答案为',num2str(Output)])
  30. end
  31. %% 输入一个字母判定其是否为判定它是否为三角形数
  32. function Output = IsTriNum(Input)
  33. if nargin == 0
  34. Input = 'JK';
  35. end
  36. Letter = ['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'];


  37. InputScore = 0;
  38. for ii = 1:length(Input)
  39.     for jj = 1:26
  40.         if strcmp(Input(ii),Letter(jj))
  41.             InputScore = InputScore + jj;
  42.             break
  43.         end
  44.     end
  45. end

  46. n = floor(sqrt(InputScore * 2));

  47. if InputScore * 2 == n*(n+1)
  48.     Output = 1;
  49. else
  50.     Output = 0;
  51. end
  52. end
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-9-30 10:54:03 | 显示全部楼层
用的matlab
结果是:
>> Untitled

count =

   162

时间已过 0.007360 秒。
>>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-29 14:55:29 | 显示全部楼层

  1. def t(n):
  2.     return n*(n+1)//2

  3. path = r"E:\Python EX\Euler Project\p042_words.txt"
  4. with open(path, "r") as f:
  5.     words = f.read()
  6. wordsList = words.strip('"').split('","')

  7. wordsValueList = []
  8. for each in wordsList:
  9.     sum = 0
  10.     for i in range(len(each)):
  11.         sum += (ord(each[i])-ord("A")+1)
  12.     wordsValueList.append(sum)

  13. triNumList = []
  14. for i in range(1, 100):
  15.     if t(i) <= max(wordsValueList):
  16.         triNumList.append(t(i))
  17.     else:
  18.         break

  19. finalWordsList = []
  20. for each in wordsList:
  21.     sum = 0
  22.     for i in range(len(each)):
  23.         sum += (ord(each[i])-ord("A")+1)
  24.     if sum in triNumList:
  25.         finalWordsList.append(each)

  26. print(len(finalWordsList))
复制代码

162.....写的感觉有点重复~~~太丑了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-14 15:06:52 | 显示全部楼层
本帖最后由 永恒的蓝色梦想 于 2020-7-2 18:39 编辑

共有:162 个
用时:0.1404009 秒

  1. import math
  2. import functools
  3. import time


  4. def trangle_num(num):
  5.     if int(math.sqrt(8*num + 1)) == math.sqrt(8*num + 1):
  6.         return True


  7. def cal_result():
  8.     count = 0
  9.     with open(r"C:\Users\wangyongzhao\Desktop\p042_words.txt") as f:
  10.         for each_word in [each.split('"')[1] for each in f.read().split(",")]:
  11.             if trangle_num(functools.reduce(lambda x, y: x + y, [ord(i) - 64 for i in each_word])):
  12.                 count += 1
  13.     return count

  14. print("共有:{} 个\n用时:{} 秒".format(cal_result(), time.process_time()))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-11 17:29:32 | 显示全部楼层
162

Process returned 0 (0x0)   execution time : 0.054 s
Press any key to continue.
又可以利用Excel VBA处理源文件使之易于输入
  1. Public Sub PE42()
  2.     Open "C:\Users\zcfcf\Desktop\words.txt" For Input As #1
  3.     Dim s As String
  4.     Dim cnt As Integer
  5.     cnt = 1
  6.     Do Until EOF(1)
  7.         Input #1, s
  8.         Range("a" & CStr(cnt)).Value = s
  9.         cnt = cnt + 1
  10.     Loop
  11.     Close #1
  12. End Sub
复制代码

接着利用ASCII码天然的编码特性计算单词的值,并加以统计
  1. #include<iostream>
  2. #include<cstdio>
  3. #include<string>
  4. using namespace std;

  5. const int a[] = {1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136,
  6.                 153, 171, 190, 210, 231, 253, 276, 300, 325, 351};

  7. int calc(const string & s){
  8.   int res = 0;

  9.   for (int i = 0;i < s.length();i++)
  10.     res += s[i] - 'A' + 1;

  11.   return res;
  12. }

  13. int main(){
  14.   freopen("i.in","r",stdin);
  15.   string s;
  16.   int cnt = 0;

  17.   while(cin >> s){
  18.     int t = calc(s);
  19.     for (int i = 0;a[i] <= 351;i++)
  20.       if (t == a[i])  { cnt++;    break; }
  21.   }

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

使用道具 举报

发表于 2021-1-11 15:54:56 From FishC Mobile | 显示全部楼层
本帖最后由 永恒的蓝色梦想 于 2021-3-6 10:40 编辑
  1. #include<iostream>
  2. #include<fstream>
  3. #include<cmath>



  4. int main() {
  5.     using namespace std;
  6.     ios::sync_with_stdio(false);

  7.     ifstream file("p042_words.txt");
  8.     unsigned int val, count = 0;
  9.     char ch;


  10.     while (file) {
  11.         if (file.get() == '"') {
  12.             if (file) {
  13.                 for (val = 0; (ch = file.get()) != '"'; val += ch - 'A' + 1);
  14.                 count += !fmod(sqrt((val << 3) | 1), 1.0);
  15.             }
  16.             else {
  17.                 break;
  18.             }
  19.         }
  20.     }


  21.     file.close();
  22.     cout << count << endl;
  23.     return 0;
  24. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-3-20 12:17:55 | 显示全部楼层
  1. #include <stdio.h>
  2. #include <math.h>

  3. int check_trinum(int);
  4. int check_trinum(int num)//判断是否为三角形数
  5. {
  6.         int i, j, k;
  7.         j = sqrt(2 * num);
  8.         for (i = j; i >= 1; i--)
  9.         {
  10.                 k = i * (i + 1) / 2;
  11.                 if (k == num)
  12.                 {
  13.                         return 1;
  14.                 }
  15.         }
  16.         return 0;
  17.        
  18. }
  19. main()
  20. {
  21.         FILE *fp;
  22.         int i = 0, j, k, n, count = 0;
  23.         char ch, word[3000][20];
  24.         fp = fopen("words.txt", "r");
  25.         while (!feof(fp))//将文件中名字写入字符串数组word中
  26.         {
  27.                 ch = fgetc(fp);

  28.                 if (ch == '"')
  29.                 {
  30.                         j = 0;
  31.                         continue;
  32.                 }
  33.                 else if (ch == '\n')
  34.                 {
  35.                         continue;
  36.                 }
  37.                 else
  38.                 {
  39.                         if (ch == ',')
  40.                         {
  41.                                 i++;
  42.                         }
  43.                         else if (ch >= 'A' && ch <= 'Z')
  44.                         {
  45.                                 word[i][j] = ch;
  46.                                 word[i][j + 1] = '\0';
  47.                                 j++;
  48.                         }
  49.                 }       
  50.         }
  51.         fclose(fp);
  52.         k = i;
  53.         for (i = 0; i <= k; i++)
  54.         {
  55.                 n = 0;
  56.                 for (j = 0; word[i][j] != '\0'; j++)
  57.                 {
  58.                         n += (word[i][j] - 64);//因为'A'的acsii码为65,所以减去64就是字母在字母表的位置
  59.                 }
  60.                 if (check_trinum(n))
  61.                 {
  62.                         count++;//记录三角形词的个数
  63.                 }
  64.         }
  65.         printf("%d", count);
  66. }
复制代码


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

使用道具 举报

发表于 2021-10-21 19:25:26 | 显示全部楼层
#共有多少个三角形词
'''
角形数序列中第 n 项的定义是:Tn = 1/2n(n+1);此前十个三角形数是:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
'''
from time import *
#生成n项三角形数序列
def creat_triangle_numlist(n):
    triangle_numlist = []
    for i in range(1, n+1):
        triangle_numlist.append((i * (i+1)) // 2)
    return triangle_numlist

def get_letter_value(letter):
    letter_dic = {'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}
    return letter_dic[letter]

#处理文件获得文本
with open("c:\\Users\\Administrator\\Desktop\\word.txt") as f:
    word_str = f.read()

start = time()
#处理字符串
word_list = word_str.split(',')

#计算多少三角形词
count = 0
each_sum = 0
word_value = []
for each in word_list:
    each = each.replace('"', '')
    for i in each:
        each_sum += get_letter_value(i)
    word_value.append(each_sum)
    each_sum = 0
#print(max(word_value)) 129160
#'''

triangle = creat_triangle_numlist(1000)
result = []
for each in word_value:
    if each in triangle:
        result.append(each)
        count += 1
    else:
        continue
end = time()
print(count)
print("用时%4f秒" % (end-start))
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-10-24 19:55:56 | 显示全部楼层
  1. import time as t
  2. import numpy as np

  3. start = t.perf_counter()


  4. def is_triangle_number(tn):
  5.     n = int(np.sqrt(2 * tn))
  6.     if 2 * tn == n * (n + 1):
  7.         return True
  8.     else:
  9.         return False


  10. names = np.loadtxt("C:/Users/wuhw/Desktop/p042_words.txt", dtype=str, delimiter=',')
  11. name_list = []
  12. count_nums = 0
  13. for name in names:
  14.     name_list.append(name.strip('"'))
  15. for each in name_list:
  16.     name_value = sum([ord(i) - 64 for i in each])
  17.     if is_triangle_number(name_value):
  18.         count_nums += 1

  19. print(count_nums)
  20. print("It costs %f s" % (t.perf_counter() - start))
复制代码



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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-28 04:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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