python 怎样实现n一千阶魔方阵

魔方阵:每一行、每一列和对角线之和均相等。
程序如下:
1 #include &stdio.h&
2 #include &stdlib.h&
3 int main()
//输出魔方阵
int i,j,k,p,n,a[15][15];
p=1;//用于判断输入的数字是否符合条件
while(p==1){
printf("enter n (n=1--15):");
scanf("%d",&n);
if((n!=0)&& (n&=15) && (n%2!=0))
for(i=1;i&=n;i++)
for(j=1;j&=n;j++)
a[i][j]=0;
j=n/2 + 1;
a[1][j]=1;
for(k=2;k&=n*n;k++){
//确立数放置的位置
if((i&1) && (j&n)){
if(i&1) i=n;
if(j&n) j=1;
if(a[i][j]==0){
a[i][j]=k;
}else{//位置上已有数
a[i][j]=k;
//输出魔方阵
for(i=1;i&=n;i++){
for(j=1;j&=n;j++)
printf("%5d",a[i][j]);
printf("\n");
system("pause");
阅读(...) 评论()一、冒泡排序
算法描述:
属于交换排序的一种。
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
针对所有的元素重复以上的步骤,除了最后一个。
持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
(引用自维基百科。)
算法实现:
class BubbleSort(object):
def __init__(self, lst):
self.lst = list(lst)
def fun(self):
for i in range(len(self.lst)-1, 0, -1):
for n in xrange(i):
if self.lst[n+1] & self.lst[n]:
self.lst[n], self.lst[n+1] = self.lst[n+1], self.lst[n]
return self.lst
def fun2(self):
while n & len(self.lst):
for j in xrange(len(self.lst)-1):
if self.lst[j+1] & self.lst[j]:
self.lst[j], self.lst[j+1] = self.lst[j+1], self.lst[j]
return self.lst
if __name__ == '__main__':
lst = [1, 0, 2, 0, 1, 2, 1, 1, 0, 0, 2]
s = BubbleSort(lst)
print s.fun()
print s.fun2()
用了两种方式实现,分别是fun和fun2。
二、选择排序
算法描述:
首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
(来自维基百科)
算法实现:
class SelectSort(object):
def __init__(self, lst):
self.lst = list(lst)
def fun(self):
for n in range(len(self.lst)):
res.append(min(self.lst))
# 在新建res列表中加入已知列表的最小数
self.lst.pop(self.lst.index(min(self.lst)))
# 删掉已知列表最小数
return res
if __name__ == '__main__':
lst = [1, 0, 2, 0, 1, 2, 1, 1, 0, 0, 2]
sel = SelectSort(lst)
print sel.fun()
三、插入排序
算法描述:
通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
(来自维基百科)
算法实现:
class InsertSort(object):
def __init__(self, lst):
self.lst = list(lst)
def fun(self):
if len(self.lst) == 1:
return lst
for n in range(1, len(self.lst)):
for m in range(n, 0, -1):
if self.lst[m] & self.lst[m-1]:
self.lst[m], self.lst[m-1] = self.lst[m-1], self.lst[m]
return self.lst
if __name__ == '__main__':
lst = [1, 0, 2, 0, 1, 2, 1, 1, 0, 0, 2]
ins = InsertSort(lst)
print ins.fun()
阅读(...) 评论()python(9)
centos6.7 & & & & python-3.5.2
os.walk(dir) 函数生成一个generator&
用for遍历可以访问dir文件夹下所有的文件或文件夹
#!/usr/bin/env python3
from os.path import isdir,join
def conv(f):
lf=os.listdir(f) #获取f目录下的一级子目录和文件
df=[i for i in lf if isdir(join(f,i))] #一级子目录
ff=list(set(lf)-set(df))
#f目录下的文件
return (f,df,ff)
def walk(f):
yield conv(f)
for e in conv(f)[1]:
tf=join(conv(f)[0],e) #给目录名加上前导路径
yield conv(tf)
for a,b,c in walk(tf):
#遍历子目录的文件和目录
for k in b:
yield conv(join(a,k))
for i in walk('.'):
运行结果:
[willie@localhost .walker]$ python3 ../walk.py
('.', ['a', 'b'], ['d', 'c'])
('./a', ['ac'], ['aa', 'ab'])
('./a/ac', [], ['aca'])
('./b', [], [])
[willie@localhost .walker]$ python3
Python 3.5.2 (default, Dec &7 :49)&
[GCC 4.4.7
(Red Hat 4.4.7-17)] on linux
Type &help&, &copyright&, &credits& or &license& for more information.
&&& import os
&&& for i in os.walk('.'):
... print(i)
('.', ['a', 'b'], ['d', 'c'])
('./a', ['ac'], ['ab', 'aa'])
('./a/ac', [], ['aca'])
('./b', [], [])
百度得 os.walk 的官方源码为:
def walk(top, topdown=True, onerror=None, followlinks=False):
&&&Directory tree generator.
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple
dirpath, dirnames, filenames
dirpath is a string, the path to the directory.
dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).
If optional arg 'topdown' is true or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top down).
If topdown is false, the triple
for a directory is generated after the triples for all of its
subdirectories (directories are generated bottom up).
When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
subdirectories whose name this can be used to prune
the search, or to impose a specific order of visiting.
dirnames when topdown is false is ineffective, since the directories in
dirnames have already been generated by the time dirnames itself is
generated.
By default errors from the os.listdir() call are ignored.
optional arg 'onerror' is specified, it
will be called with one argument, an os.error instance.
report the error to continue with the walk, or raise the exception
to abort the walk.
Note that the filename is available as the
filename attribute of the exception object.
By default, os.walk does not follow symbolic links to subdirectories on
systems that support them.
In order to get this functionality, set the
optional argument 'followlinks' to true.
if you pass a relative pathname for top, don't change the
current working directory between resumptions of walk.
walk never
changes the current directory, and assumes that the client doesn't
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print root, &consumes&,
print sum([getsize(join(root, name)) for name in files]),
print &bytes in&, len(files), &non-directory files&
if 'CVS' in dirs:
dirs.remove('CVS')
# don't visit CVS directories
islink, join, isdir = path.islink, path.join, path.isdir
# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains.
os.path.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit.
That logic is copied here.
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = listdir(top)
except error, err:
if onerror is not None:
onerror(err)
dirs, nondirs = [], []
for name in names:
if isdir(join(top, name)):
dirs.append(name)
nondirs.append(name)
if topdown:
yield top, dirs, nondirs
for name in dirs:
new_path = join(top, name)
if followlinks or not islink(new_path):
for x in walk(new_path, topdown, onerror, followlinks):
if not topdown:
yield top, dirs, nondirs
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:4864次
排名:千里之外
原创:21篇
(4)(2)(1)(3)(6)(3)(4)

我要回帖

更多关于 一千阶魔方 的文章

 

随机推荐