穷举4阶幻方

rex posted @ Jul 10, 2010 07:48:16 AM in 离散数学 with tags python 幻方 , 1679 readers

思路:

  1. 对于第一行的第1个元素,是1~16;第2个要选此之外的,只有15个可选。第三个只有14个可选。第四个,只有一个选择,即平均数减去1,2,3。
  2. 第2,3行的最后一个同理。
  3. 第4行每一个元素均由其同列元素决定。
  4. 这些“被决定”的值不得小于0,以免出现负数。�除

代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#author:         rex
#blog:           http://iregex.org
#filename        hf.py
#created:        2010-07-09 20:34

n=4
avg=n*(n*n+1)/2
N=n*n

#sum of a list
def s(li):
    sum=0
    for i in li:
        sum+=i
    return sum==avg

#return the difference of tow sets, and convert to list
def ls(ln, li):
    return list(set(li)-set(ln)) 


li=[i for i in range(1,N+1)]
c=[i for i in range(1,N+1)]

#format
def f(li):
    print '''%02d %02d %02d %02d'''% tuple(li[0:4])
    print '''%02d %02d %02d %02d'''% tuple(li[4:8])
    print '''%02d %02d %02d %02d'''% tuple(li[8:12])
    print '''%02d %02d %02d %02d'''% tuple(li[12:16])
    print

   
for c[0] in li:
    for c[1] in ls(c[:1],li):
        for c[2] in ls(c[:2],li):
            c[3]=avg-c[0]-c[1]-c[2] 
            if c[3]>0 and c[3] not in c[0:3]:
                for c[4] in ls(c[:4],li):
                    for c[5] in ls(c[:5],li):
                        for c[6] in ls(c[:6],li):
                            c[7] =avg-c[4]-c[5]-c[6] 
                            if c[7]>0 and c[7] not in c[:7]:
                                for c[8] in ls(c[:8],li):
                                    for c[9] in ls(c[:9],li):
                                        for c[10] in ls(c[:10],li):
                                            c[11] =avg-c[8]-c[9]-c[10] 
                                            if c[11]>0 and c[11] not in c[:11]:
                                                c[12]=avg-c[0]-c[4]-c[8]
                                                c[13]=avg-c[1]-c[5]-c[9]
                                                c[14]=avg-c[2]-c[6]-c[10]
                                                c[15]=avg-c[3]-c[7]-c[11]
                                                if c[14]>0 and c[12]>0 and c[13]>0 and c[15]>0 and s([c[x] for x in [0,5,10,15]])\
                                                    and s([c[x] for x in [3,6,9,12]])\
                                                    and c[12] not in c[:12]\
                                                    and c[13] not in c[:13]\
                                                    and c[14] not in c[:14]\
                                                    and c[15] not in c[:15]:
                                                    f(c)

 程序运行较慢。输出前N组: 

01 02 15 16
12 14 03 05
13 07 10 04
08 11 06 09

01 02 15 16
13 14 03 04
12 07 10 05
08 11 06 09

01 02 16 15
13 14 04 03
12 07 09 06
08 11 05 10

01 03 14 16
10 13 04 07
15 06 11 02
08 12 05 09

01 03 14 16
12 13 04 05
15 08 09 02
06 10 07 11

01 03 14 16
15 13 04 02
10 06 11 07
08 12 05 09

01 03 14 16
15 13 04 02
12 08 09 05
06 10 07 11

01 03 16 14
08 15 02 09
13 06 11 04
12 10 05 07

01 03 16 14
12 15 02 05
13 10 07 04
08 06 09 11

01 03 16 14
13 15 02 04
08 06 11 09
12 10 05 07

01 03 16 14
13 15 02 04
12 10 07 05
08 06 09 11

 

 

best CBD gummies said:
Apr 29, 2020 04:15:42 PM

Can I simply say what a relief to seek out somebody who actually knows what theyre speaking about on the internet. You definitely know the way to bring a problem to mild and make it important. More folks have to read this and understand this aspect of the story. I cant believe youre no more common since you positively have the gift.

best CBD oil for pai said:
May 04, 2020 07:23:35 PM

bike racks could really help you secure your bike when you leave it ~

shahmeerkhan said:
Jul 02, 2020 12:33:29 PM

Ya I even have used the acai berry supplement .It is terribly effective and it does’nt take too much time to point out the result. cement tile

poker online terbaik said:
Jul 08, 2020 12:08:42 AM

Hey there,  You’ve done an excellent job. I’ll definitely digg it and personally recommend to my friends. I am sure they’ll be benefited from this site. 코인카지노

shahmeerkhan said:
Jul 29, 2020 02:32:25 AM

Youre so cool! I dont suppose Ive read something such as this before. So nice to search out somebody with authentic applying for grants this subject. realy i appreciate you for starting this up. this fabulous website are some things that’s needed on the internet, somebody after some bit originality. helpful purpose of bringing new things to your web! fence post pounder

Immobilien Mannheim said:
Aug 24, 2020 03:17:14 AM

It is really good post, but I don’t see everything completely clear, especially for someone not involved with that topic. Anyway very interesting in my experience.

asharseo said:
Sep 07, 2020 10:05:51 PM

Useful info. Fortunate me I discovered your site unintentionally, and I’m shocked why this coincidence did not happened in advance! I bookmarked it. judi dadu online

grooming shop softwa said:
Sep 17, 2020 07:58:25 PM

It’s not no problem finding knowledgeable people with this topic

asharseo said:
Sep 23, 2020 06:31:09 PM

Thank you a bunch for sharing this with all folks you actually recognise what you are speaking about! Bookmarked. Please also consult with my website =). We may have a hyperlink trade agreement among us! amazon treasure truck

clavon clementi said:
Sep 27, 2020 08:17:13 PM

of the many dog breeds that we have, my personal favorite is the bull terrier coz they are really cute..

агент по недвижимост said:
Oct 03, 2020 08:32:44 PM

of the many dog breeds that we have, my personal favorite is the bull terrier coz they are really cute..

trackershop-uk said:
Oct 04, 2020 10:05:49 PM

I see something genuinely special in this website .

https://www.fairvote said:
Oct 08, 2020 02:41:07 PM

I must admit this post is very wonderful . Thanks once again for the push!

Robinjack said:
Oct 14, 2020 08:13:37 PM

Thanks for the useful information on credit repair on this blog. Things i would advice people should be to give up the mentality that they’ll buy currently and pay later. Being a society most people tend to make this happen for many factors. This includes getaways, furniture, and also items we wish. However, you’ll want to separate your own wants from all the needs. When you are working to raise your credit score you really have to make some sacrifices. For example you can shop online to save cash or you can check out second hand suppliers instead of high priced department stores intended for clothing. city towers

Digital ALi said:
Nov 02, 2020 03:29:47 PM

Useful info. Fortunate me I discovered your site unintentionally, and I’m shocked why this coincidence did not happened in advance! I bookmarked it.. buy twitter views cheap

Digital ALi said:
Nov 02, 2020 08:23:23 PM

I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers buy free Cialis over the counter with free shipping

Digital ALi said:
Nov 05, 2020 04:07:58 PM

You understand your projects stand out of the crowd. There is something unique about them. It seems to me all of them are brilliant. w-123movies.com

Anonymous said:
Nov 10, 2020 08:57:35 PM

Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing... подарък за жена

Anonymous said:
Nov 11, 2020 01:36:39 AM

It should be noted that whilst ordering papers for sale at paper writing service, you can get unkind attitude. In case you feel that the bureau is trying to cheat you, don't buy term paper from it. 우리카지노

Anonymous said:
Nov 11, 2020 01:42:45 AM

Your blogs further more each else volume is so entertaining further serviceable It appoints me befall retreat encore. I will instantly grab your rss feed to stay informed of any updates. смс услуги

Anonymous said:
Nov 11, 2020 01:54:08 AM

It is somewhat fantastic, and yet check out the advice at this treat. сироп банан

Anonymous said:
Nov 11, 2020 01:59:59 AM

Cool you inscribe, the info is really salubrious further fascinating, I'll give you a connect to my scene.  тениски

Anonymous said:
Nov 11, 2020 02:06:19 AM

Cool you write, the information is very good and interesting, I'll give you a link to my site.  мебели софия

Anonymous said:
Nov 11, 2020 02:15:34 AM

I invite you to the page where     see how much we have in common. хотели поморие

Anonymous said:
Nov 12, 2020 01:18:21 PM

You possess lifted an essential offspring..Blesss for using..I would want to study better latest transactions from this blog..preserve posting.. принтери

Anonymous said:
Nov 12, 2020 01:24:29 PM

Below you will understand what is important, the idea provides one of the links with an exciting site: червени чанти

Anonymous said:
Nov 12, 2020 01:28:53 PM

This is very appealing, however , it is very important that will mouse click on the connection: курсове по английски език варна

Anonymous said:
Nov 12, 2020 01:33:24 PM

Welcome to the party of my life      here you will learn everything about me. микропигментация София

Anonymous said:
Nov 12, 2020 01:38:32 PM

I invite you to the page where     see how much we have in common. Жанина Борисова

Robinjack said:
Dec 23, 2020 05:37:41 PM

Splendid post. I discover new things upon different weblogs daily. Couple of stimulating to see content using their company authors and turn out to be acquainted with a small something their particular. I’d think to use some inside the information on my blog need to do not thoughts. Obviously I’ll provides a link back up in internet site. Thank you sharing. room reservation software open source

Robinjack said:
Feb 20, 2021 11:36:02 PM

Ok oui et pas vraiment. Assurément parce que il se peut qu’on rencontre certaines sources qui probablement citent de semblables cote. Non car il ne suffit pas de copier ce qu’on peut lire avec plusieurs site web autres avant de le transposer tant clairement event booking software

amelia said:
Mar 23, 2021 09:25:51 PM

This is an awesome rousing article.I am practically satisfied with your great work.You put truly exceptionally supportive data. Keep it up. Continue blogging. Hoping to perusing your next post.  http://dir.whatuseek.com/Science/Environment/Air_Quality/Products_and_Services/Equipment_and_Supplies?page=2

Toxic Abuse Recovery said:
Apr 21, 2021 11:22:20 PM

Excellent post. I was always checking this blog, and I’m impressed! Extremely useful info specially the last part, I care for such information a lot. I was exploring this particular info for a long time. Thanks to this blog my exploration has ended. https://www.bindubabu.com/

Healing and recovery said:
Apr 22, 2021 11:06:48 PM

Excellent post. I was always checking this blog, and I’m impressed! Extremely useful info specially the last part, I care for such information a lot. I was exploring this particular info for a long time. Thanks to this blog my exploration has ended.

luxury hotels in hal said:
Apr 24, 2021 04:24:59 PM

Good artcile, but it would be better if in future you can share more about this subject. Keep posting.

Bartender Hire Londo said:
Apr 25, 2021 05:15:03 PM

Good website! I truly love how it is easy on my eyes it is. I am wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS which may do the trick? Have a great day!https://barbrothersevents.co.uk/wedding-bar-hire

reflective heat tran said:
Apr 26, 2021 07:23:19 PM

There are numerous dissertation websites on-line because you additionally obtain obviously stated inside your web site.https://seaarttrim.com/

Black said:
Apr 27, 2021 04:23:48 PM

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too.http://www.coachfelyne.com/

diastasis recti post said:
Apr 29, 2021 10:29:48 PM

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice writing http://www.fit4motherhood.com/

Subliminals said:
Apr 30, 2021 01:40:46 AM

Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work.https://www.soulsymphony.de/

Unterbewusstsein Pro said:
May 03, 2021 11:23:41 PM

Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work.

Unterbewusstsein said:
May 05, 2021 01:30:46 AM

Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work.https://www.soulsymphony.de/

Bike holidays france said:
May 05, 2021 01:34:58 AM

There are numerous dissertation websites on-line because you additionally obtain obviously stated inside your web site.https://www.capricornegites.com/

Hair mask coconut an said:
May 05, 2021 01:43:03 AM

I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much.http://www.myglitterbox.co.uk/

umziehen München said:
May 05, 2021 01:48:21 AM

Hi there! Nice material, do keep me posted when you post something like this again! I will visit this blog leaps and bounds for more quality posts like it. Thanks...https://www.umzugskompass.de/umzug-muenchen/

Umzugsunternehmen said:
May 05, 2021 01:54:37 AM

Hi there! Nice material, do keep me posted when you post something like this again! I will visit this blog leaps and bounds for more quality posts like it. Thanks...https://www.umzugskompass.de

patterned htv said:
May 05, 2021 02:01:00 AM

Good artcile, but it would be better if in future you can share more about this subject. Keep posting.https://www.seaarttrim.com

types of microbiolog said:
May 05, 2021 02:04:58 AM

Good website! I truly love how it is easy on my eyes it is. I am wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS which may do the trick? Have a great day ! https://www.vkonte.com/

Shayari Mizaaj said:
May 05, 2021 03:51:04 AM

There are numerous dissertation websites on-line because you additionally obtain obviously stated inside your web site.https://shayarimizaaj.com

car stereo bluetooth said:
May 18, 2021 03:20:06 PM

Cool you write, the information is very good and interesting, I'll give you a link to my site.

alex said:
May 23, 2021 07:10:12 PM

Wohh exactly what I was looking for, appreciate it for posting . writing guide

work scheduling soft said:
May 25, 2021 11:04:03 PM

I like your website.. great shades & motif. Performed people design and style this fabulous website yourself or even have people rely on someone else to make it work for you personally? Plz interact when I!|m looking to pattern by myself blog site plus would want to find out wherever u received this particular through. thank you

alex said:
Jun 03, 2021 08:37:14 PM

Great wordpress blog here.. It’s hard to find quality writing like yours these days. I really appreciate people like you! take care togel online

jack said:
Jun 11, 2021 12:00:45 AM

Finally, got what I was looking for!! I’ve really enjoying every small bit of this. Ecstatic I stumbled into this post! and also I’ve bookmarked to look at unique information for your blog post. аппарат для lpg массажа

Buy TikTok Likes said:
Jun 12, 2021 02:52:27 PM

As I web-site possessor I believe the content matter here is rattling wonderful , appreciate it for your efforts. You should keep it up forever! Good Luck.

พนันออนไลน์ เว็บไหนด said:
Jun 20, 2021 08:47:04 PM

Sometimes the easier to simply take one step back again and also recognize that few people gives your beliefs

sbh.group said:
Jun 30, 2021 09:18:13 PM

We have the requisite expertise to address challenges that occur during the construction process quickly and efficiently. <a href="https://sbh.group/">https://sbh.group/</a>

drcabinet said:
Jul 01, 2021 12:11:43 AM

Frequently used hotel rooms must need hotel cabinet repair. Its furniture must always look good because it is part of the lobby.

Unterbewusstsein said:
Jul 03, 2021 03:49:27 PM

Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. Thanks. https://www.soulsymphony.de/

healer said:
Jul 03, 2021 05:12:26 PM

Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you.https://portlandmindbodysoul.com/

reikiforhorses said:
Jul 03, 2021 05:17:16 PM

Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work.https://naturalhealingforanimals.com/

seo service company said:
Jul 03, 2021 05:22:42 PM

i am always looking for some free stuffs over the internet. there are also some companies which gives free samples.https://digitalitfixer.com/seo-services/

happy fathers day qu said:
Jul 03, 2021 05:28:46 PM

There are numerous dissertation websites on-line because you additionally obtain obviously stated inside your web site.https://goodnightwishesmessages.com/

motogp leather suit said:
Jul 03, 2021 05:35:39 PM

you are really a good webmaster. The site loading speed is incredible. It seems that you are doing any unique trick. Furthermore, The contents are masterwork. you have done a excellent job on this topic!https://www.thejackleathers.com/product/alex-rins-suzuki-motogp-2019-suit/

motogp suit price said:
Jul 06, 2021 09:26:55 PM

Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you.

ATM machine free pla said:
Jul 12, 2021 01:04:15 AM

Free ATM Placement – Why not get a free ATM then? Free ATM placement services are the traditional route for businesses. For high traffic locations, Free ATM placements are beneficial to both Los Angeles ATM Machine Co. and business owner. A high traffic location is given a free ATM with free installation as well. Because everything is free for the business, Los Angeles ATM Machine Co. usually only asks for a percentage of the surcharge. Los Angeles ATM Machine Co. is responsible for everything in return for the surcharge. The location owner only provides the location and electricity, and gets a check or direct deposit from all the ATM surcharges.

Faddy said:
Jul 14, 2021 09:56:50 PM

I am definitely enjoying your website. You definitely have some great insight and great stories. delta 8 products

jack said:
Jul 15, 2021 04:21:49 PM

Hello there, just became alert to your blog through Google, and found that it’s really informative. I’m going to watch out for brussels. I will be grateful if you continue this in future. A lot of people will be benefited from your writing. Cheers! 먹튀검증

WWW said:
Jul 15, 2021 08:36:47 PM

he he i love catfights that is why i love Amanda Bynes. i think that she is a very humble woman too::CBD gummies reviewed by CFAH.org

jack said:
Jul 16, 2021 01:32:42 AM

This design is incredible! You most certainly know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Excellent job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool! 토토사이트

n95 said:
Jul 18, 2021 09:40:32 PM

This is the good guidelines specially for you to those people new at all to blogosphere, simple along with exact information… Cheers pertaining to expressing this. Absolutely essential go through content. n95

no excuses runner said:
Jul 28, 2021 06:26:29 PM

Water and Waste Plumbing are your Local Plumber Darwin. We are certified plumbers and proudly offer an array of plumbing services at affordable prices. hot water system installation

no excuses runner said:
Jul 28, 2021 08:01:16 PM

Winner of Best of Yolo County 2020 and Best of Weedmaps Kind Farma is Davis Californias Premier medical and recreational Cannabis dispensary. kind farms

online casino 2019 said:
Jul 29, 2021 05:29:48 PM

Neue Spiele sind eine aufregende Ergänzung für jedes Casino und manchmal mit großartigen Aktionen und Angeboten verbunden, wie z. B. Bonus-Spins und Aufladungen von Gratisgeldern. Ich fand dieses großartige Online Casino mit einigen großartigen Spielen namens online casino 2019. Sie sind wirklich einen Besuch wert.

WWW said:
Aug 01, 2021 03:38:45 PM

well, monetizing websites and stuffs should be great. making money on the internet is a great way to earn money“https://coolors.co/u/william_butler

asdzxc said:
Aug 09, 2021 01:30:59 AM

Enamel Badges provides a massive range of custom enamel badges in the UK. we offer soft and hard enamel badges, die struck badges, and printed badges. custom pin badges

jack said:
Aug 16, 2021 07:29:01 PM

My brother recommended I might like this web site. He was entirely right. This post truly made my day. You can not imagine just how much time I had spent for this information! Thanks! UFABET

Mobile auto detailin said:
Aug 20, 2021 12:37:18 AM

Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work.

thelovepets.us said:
Aug 21, 2021 06:26:16 PM

Going to graduate school was a positive decision for me. I enjoyed the coursework, the presentations, the fellow students, and the professors. And since my company reimbursed 100% of the tuition, the only cost that I had to pay on my own was for books and supplies. Otherwise, I received a free master’s degree. All that I had to invest was my time.

AP Inter 1st & 2nd Y said:
Aug 23, 2021 07:11:54 PM

AP Inter Model Paper for Jr AP Inter 1st & 2nd Year Model Paper 2022, BIEAP Sr, Jr Inter Previous Question Paper 2022, AP Inter 1st & 2nd Year Exam Model Question Paper 2022, BIEAP Sr, Jr Inter Mock Test Paper 2022, AP Inter 1st & 2nd Year Practical Exam Question Paper 2022 at AP Inter 1st & 2nd Year Question Paper. BIEAP Inter 1st & 2nd Year Model Paper 2022 Available Students you can Download in Pdf format from this web page below given links. BIEAP Regular and Private Students Prepare their Exam from these Sample Papers, Students have to Register for Appearing in Public Exam 2022.

Robinjack said:
Aug 24, 2021 08:37:00 PM

Youre so cool! I dont suppose Ive read anything similar to this prior to. So nice to seek out somebody by original ideas on this subject. realy thank you for starting this up. this web site can be something that is needed over the internet, an individual after a little originality. beneficial purpose of bringing new things towards the web! book desk

تفسير الاحلام said:
Aug 28, 2021 07:09:51 PM

I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end. I would like to read newer posts and to share my thoughts with you.

SEO dofollow backlin said:
Sep 03, 2021 09:12:49 PM

YOU, only have to click here, on our web site to learn how you can be successful in the internet marketing business. <a href="https://www.fiverr.com/backlinks_tree/provide-100-blog-comment-and-quality-backlinks">high authority blog comments</a>

Robinjack said:
Sep 09, 2021 09:19:24 PM

Hi, I just discovered your web site via Bing. Your viewpoint is truly relevant to my life right now, and I’m really happy I discovered your website. bvi sailboat charters

joker slot said:
Sep 12, 2021 08:48:15 PM

Hiya, I’m really glad I’ve found this information. Today bloggers publish only about gossips and internet and this is really irritating. A good website with interesting content, that’s what I need. Thanks for keeping this web site, I’ll be visiting it. Do you do newsletters? Can’t find it. Business services

types of cryptocurre said:
Sep 17, 2021 07:29:19 PM

I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts.

sad broken heart quo said:
Sep 19, 2021 06:08:03 PM

Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors.

WWW said:
Sep 23, 2021 04:38:54 PM

How are You? I have been searching for great doing Web Design Glasgow, do You know any? See You!instamama.net

dream said:
Sep 25, 2021 03:42:26 PM

This is also a very good post which I really
enjoyed reading. It is not every day that I have the possibility to see
something like this.

manga said:
Sep 25, 2021 07:02:57 PM

This is also a very good post which I really
enjoyed reading. It is not every day that I have the possibility to see
something like this.

Robinjack said:
Sep 26, 2021 10:34:09 PM

Midtown Modern by GuocoLand and Hong Leong. Hotline 61009266. Get Discounts, Direct Developer Price, Brochure, Floor Plan & Price List. New Launch at Tan Quee Lan Street. Midtown Modern


Login *


loading captcha image...
(type the code from the image)
or Ctrl+Enter