def make_data(n, UAV): """make_data: compute matrix distance based on euclidean distance""" S = Class.Sequence(n, None, None) V = [] for i in range(0, n + 2): # インスタンス化 V.append(Class.Node(i)) for i in range(0, n + 1): # 0~n n+1はデポ(0) V[i].coordinate = [30 * random.random() + 1, 30 * random.random() + 1] if i == 0: V[i].next = V[i + 1] else: V[i].prev = V[i - 1] V[i].next = V[i + 1] S.nodes.append(V[i]) V[n + 1].coordinate = V[0].coordinate V[n + 1].prev = V[n] S.first = V[0] S.last = V[n + 1] global dD, dT, tD, tT for i in V: for j in V: for uav in UAV: dD[uav, i.num, j.num] = distance(i.coordinate, j.coordinate) tD[uav, i.num, j.num] = dD[uav, i.num, j.num] / _dSpeed dT[i.num, j.num] = dD[UAV[0], i.num, j.num] * _biasForDist tT[i.num, j.num] = dT[i.num, j.num] / _tSpeed return S, V
def findStrip(graph): # count = 0 stripList = [] tCell = None GCl = graph.gridCellL strip=0#标记当前是否为开始计算strip长度状态 for i in range(len(GCl)): if strip == 0: if GCl[i].holeNot == 1: continue elif GCl[i].holeNot == 0: if (GCl[i].point1.coordinate[1] == graph.xlineList[-1]): stripList.append(Class.strip(GCl[i], GCl[i])) continue else: strip = 1 tCell = GCl[i] continue else: if GCl[i].holeNot == 1: strip = 0 stripList.append(Class.strip(tCell,GCl[i-1])) continue else: if(GCl[i].point1.coordinate[1] == graph.xlineList[-1]): strip = 0 stripList.append(Class.strip(tCell, GCl[i])) continue else: continue return stripList
def getSRoadlist(roadlist): deslist = [] sroadlist = [] #描述相同聚为一类 for data in roadlist: if 'bridge' not in data.getDescription(): if 'name' in data.getDescription(): if data.getDescription()['name'] not in deslist: sroad = RoadClass.SRoad(data, data.getCordinations(), data) sroad.setCordinations(None) sroad.setSon(None) deslist.append(data.getDescription()['name']) sroadlist.append(sroad) else: for item in sroadlist: if 'name' in item.getDescription(): if item.getDescription( )['name'] == data.getDescription()['name']: item.setCordinations( data.getCordinations()) item.setSon(data) else: sroad = RoadClass.SRoad(data, data.getCordinations(), data) sroad.setCordinations(None) sroad.setSon(None) sroadlist.append(sroad) return sroadlist
def getFsegmentlist(roadlist, dis, divang): fcrosslist = GetData.getFCrosslist(roadlist, dis, divang)[0] # 取数据中带有交叉点的路 for itemC in fcrosslist: list1 = [] for itemR in roadlist: if itemC in itemR.cordinations: list1.append(itemR) fsegmentlist = [] count = 0 for item in roadlist: tempList1 = item.divideByJointList(fcrosslist) if GetData.isContinuous(tempList1) is not True: print("警告,道路划分后,不连续!!!!") # print (len(roadList1)) for segmentCordination in tempList1: count += 1 fsegmentlist.append( RoadClass.FSegment(item.id, item.description, segmentCordination)) othercrossinfo = GetData.getFCrosslist(roadlist, dis, divang)[2] for item2 in othercrossinfo: fsegmentlist.append(RoadClass.FSegment( None, None, item2)) ##定义新加的交点路段描述为None,id为None return fsegmentlist
def getFRoadlist(roadlist, dis, divang): froadlist = [] sroadList = GetData.getSRoadlist(roadlist) #将非Des相同划分为FRoad for a in sroadList: if len(a.getSonRoads()) == 1: froad = RoadClass.FRoad(a.getSonRoads()[0], a.getSonRoads()[0].getCordinations(), a.getSonRoads()[0]) froad.setCordinations(None) froad.setSon(None) froadlist.append(froad) doubleroadlist = GetData.getFRealteddata(roadlist, dis, divang)[0] onewaylist = GetData.getFRealteddata(roadlist, dis, divang)[1] # 将划分出的单行道划分为FRoad for b in onewaylist: froad1 = RoadClass.FRoad(b, b.getCordinations(), b) froad1.setCordinations(None) froad1.setSon(None) froadlist.append(froad1) # 将划分出的双行道划分为FRoad for c in doubleroadlist: froad2 = RoadClass.FRoad(c[0], c[0].getCordinations(), c[0]) froad2.setCordinations(None) froad2.setSon(None) froad2.setCordinations(c[1].getCordinations()) froad2.setSon(c[1]) froadlist.append(froad2) return froadlist
def sub_cost(tour): # sub sequence i = tour.nodes[1] j = tour.nodes[2] k = tour.nodes[3] TD = c.Sequence(3, i, k) TD.nodes[2] = j DD = c.Sequence(2, i, k) return total_cost(TD, DD)
def decodeHouseList(codedHouseList): houseList = [] for tuple in codedHouseList: if tuple[4] == 0: houseList.append(Class.Water(tuple[0], tuple[1], tuple[2], tuple[3], 1)) elif tuple[4] == 2: houseList.append(Class.SingleHouse(tuple[0], tuple[1])) elif tuple[4] == 3: houseList.append(Class.Bungalow(tuple[0], tuple[1])) elif tuple[4] == 6: houseList.append(Class.Maison(tuple[0], tuple[1])) return houseList
def addClass(self,courseName,courseNumber,sessionNumber,credits,type,section, professorName,days,lecTime,roomNumber,campus,prereqs): #change parameters courseName & courseNumber to courseCode (basically fusing them together) #Type contains LEC,TUT,LAB/ #incomplete classTime = self.convertTime(lecTime) name = str(courseName)+" "+str(courseNumber) #Ex. Concatenates ENGR + " " + 371 . newClass = Class(name,sessionNumber,type,section, professorName,days,classTime[0],classTime[1],roomNumber,campus,[]) classNameArray = newClass.get_name().split(" ") courseList = self.courseMap.get(courseName) if(len(courseList)==0): self.courseMap.get(courseName).append(Course("Course Code",name,credits,prereqs,[newClass])) else: for i in xrange(0,len(courseList)): if(name == courseList[i].getCourseName()): #Hit found in course list ("ENGR 371" == "ENGR 371"), therefore course exists. #Proceed to appropriate tut or lab, or append new lecture to course if(newClass.get_type() == "LEC"): courseList[i].addClass(newClass) if(newClass.get_type() == "TUT"): #Will appropriate the tutorial to the correct lecture #Compare the first letter of the lecture section to the first of the tut # If they are the same, tutorial is appended to the lecture lectureList = courseList[i].get_lectures() for j in xrange(0,len(lectureList)): if(lectureList[j].get_name()==classNameArray[0]): lectureList[j].addClass(newClass) if(newClass.get_type() == "LAB"): lectureList = courseList[i].get_lectures() for j in xrange(0,len(lectureList)): lectureName = lectureList[j].get_name() if(lectureName == classNameArray[0]): if(lectureList[j].hasTutorial()==False): #Lecture doesn't have any tutorials, therefore lab is added #This situation doesn't happen often lectureList[j].addClass(newClass) else: tutList = lectureList[j].get_section() for k in xrange(0,len(tutList)): tutName = tutList[k].get_name().split(" ") if(tutName[1] == classNameArray[1]): tutList[k].addClass(newClass) elif(i==(len(courseList)-1)): #create Course and add it to map containing newClass newCourse = Course("Course Code",name,credits,prereqs,[newClass]) self.courseMap.get(courseName).append(newCourse)
def cost(): # minimize this result = 0 for droppedClass in droppedClasses: result += droppedClass.getSize() for room in rooms: for key,Class in room.getClasses().items(): overflow = (Class.getSize() - room.getSize()) * (Class.getLength() + 1) result += max(0, overflow) # add the number of students that don't fit, if any return result '''
def numConflicts(): # meaningful objective function result = 0 for droppedClass in droppedClasses: result += droppedClass.getSize() for room in rooms: for key,Class in room.getClasses().items(): overflow = (Class.getSize() - room.getSize()) * Class.getLength() result += max(0, overflow) # add the number of students that don't fit, if any return result #pre class cost '''
def verplaatser(houseList, goal, itNR, changeNum, maisonStrat): counter = 0 winst = 0 distList = Class.initDistList(houseList) #--------------------1-------------------------# for i in range(itNR): value = Class.valueOfMapFast(houseList, distList) house = getIndex(goal, maisonStrat) #--------------------2--------------------------# oldX = houseList[house].x oldY = houseList[house].y lowerX, higherX = (oldX - changeNum), (oldX + changeNum) lowerY, higherY = (oldY - changeNum), (oldY + changeNum) newX = random.randint(round(lowerX), round(higherX)) newY = random.randint(round(lowerY), round(higherY)) #--------------------3--------------------------# if not checkHouseOutOfBounds(houseList[house], newX, newY): houseList[house].x = newX houseList[house].y = newY Class.update_dist_list(houseList, distList, house - 4) newValue = Class.valueOfMapFast(houseList, distList) if newValue > value and not Class.overlapFinalBoss(houseList): winst += newValue - value value = newValue counter += 1 else: houseList[house].x = oldX houseList[house].y = oldY Class.update_dist_list(houseList, distList, house - 4) print("winst =", winst) print("NR verplaatsingen =", counter) return houseList
def main(): if len(sys.argv) != 5: logging.info( 'please input args: car_path, road_path, cross_path, answerPath') exit(1) car_path = sys.argv[1] road_path = sys.argv[2] cross_path = sys.argv[3] answer_path = sys.argv[4] logging.info("car_path is %s" % (car_path)) logging.info("road_path is %s" % (road_path)) logging.info("cross_path is %s" % (cross_path)) logging.info("answer_path is %s" % (answer_path)) # 导入数据 roads, cars, crosses = Data.load_data(road_path, car_path, cross_path) # 创建模型实例 graph = Class.Graph(roads) cars = Data.sort_speed(cars) # 按速度排序没有起到作用 with open(answer_path, 'w') as f: f.write("#(carId,StartTime,RoadId...)\n") # 车辆调度 answer = Path.plan(graph, cars, answer_path)
def encoder(decodedList): houseList = [] for list in decodedList: if list[2] == 2: single = Class.SingleHouse(list[0],list[1]) houseList.append(single) elif list[2] == 3: bunga = Class.Bungalow(list[0],list[1]) houseList.append(bunga) elif list[2] == 6: maison = Class.Maison(list[0],list[1]) houseList.append(maison) elif list[2] == 0: water = Class.Water(list[0], list[1], list[3], list[4], 0) houseList.append(water) return houseList
def _create_dummy_wrappers(self): assert self.header_decl is None namespace = self._get_cxx_namespace() down = False for ddef in self.blacklist.dummy_classes.values(): if Registry.get_class(ddef.full_name): continue if ddef.namespace != namespace: down = True continue cls = Class.Class(self.root, None, self, ddef) if ddef.header: cls.set_header(ddef.header) self.register_class(cls) self.modified = True if down: for submodule in self.submodules: # noinspection PyProtectedMember submodule._create_dummy_wrappers()
def dumpQ(u): qname, qtype, qclass = u.getQuestion() print 'qname=%s, qtype=%d(%s), qclass=%d(%s)' \ % (qname, qtype, Type.typestr(qtype), qclass, Class.classstr(qclass))
def exprl2alignment(exprl): """ @summary: Converts experiments into alignments @param exprl: The list of experiments to be converted into an alignment objects @type exprl: ListType @author: Vladimir Likic """ if not is_list(exprl): error("the argument is not a list") algts = [] for item in exprl: if not isinstance(item, Experiment): error("list items must be 'Experiment' instances") else: algt = Class.Alignment(item) algts.append(algt) return algts
def update_programing(topic, urls_number): db_handler.delete(topic) link = list() for rows1 in parser.developer_tech(urls_number): link.append("https://www.developer-tech.com/" + rows1) for rows2 in link: db_handler.insert(rows2, topic)
def matriks_rotasi(sumbu, sudut): #0x,1y,2z mtemp = c.Matriks() sudut = sudut * math.pi / 180 mtemp.banyak_baris = 3 mtemp.banyak_kolom = 3 for i in range(3): for j in range(3): mtemp.elemen[i][j] = 0 n = 0 mtemp.elemen[sumbu][sumbu] = 1 for i in range(2): for j in range(2): if (n == 0): mtemp.elemen[(sumbu + i + 1) % 3][(sumbu + j + 1) % 3] = math.cos(sudut) if (n == 1): mtemp.elemen[(sumbu + i + 1) % 3][(sumbu + j + 1) % 3] = -math.sin(sudut) if (n == 2): mtemp.elemen[(sumbu + i + 1) % 3][(sumbu + j + 1) % 3] = math.sin(sudut) if (n == 3): mtemp.elemen[(sumbu + i + 1) % 3][(sumbu + j + 1) % 3] = math.cos(sudut) n = n + 1 return mtemp
def getSamesegment(segmentID, roadlist): samesegment = [] sroadlist = GetData.getSRoadlist(roadlist) crosslist = GetData.getCrosslist(sroadlist) segmentlist = GetData.getsegmentlist(roadlist, crosslist) for data in segmentlist: if data.getID() == segmentID: rbID = data.getbID() cor = data.getCordinations() corlist = [] rblist = [] for item in sroadlist: son = item.getSonRoads() if len(son) == 1: return "该子路段无同名对应子路段" elif rbID in son: for roadid in son: for rd in roadlist: if rd.getID() == roadid: if rd.getID() == rbID: rblist.append(rd.getCordinations()) else: bid = rd.getID() corlist.append(rd.getCordinations()) head = rblist.index(data.getHead()) tail = rblist.index(data.getTail()) samcor = corlist[head:tail] samesegment.append( RoadClass.Segment(bid, data.description, samcor)) return samesegment
def create_agents(N): Agents = [] for i in range(N): estr = random.choice([0, 1]) # scr = 0 pol = random.choice([0, 1, 2, 3, 4, 5, 6, 7]) Agents.append(Cl.Agent(estr, None, pol, [])) return Agents
def actualizar_estrategias(agents): for i in range(len(agents)): st = agents[i].estrategias[-1] pt = agents[i].scores[-1] num_ult_pol = agents[i].politicas[-1] ult_pol = Cl.Politica(num_ult_pol) new_st = ult_pol.politica[(st, pt)] agents[i].estrategias.append(new_st)
def main(): print("----- Furniture Listing Below -----") furniture = Class.OfficeFurniture("Table", "Wood", 64, 32, 32, 100.00) furniture.__str__() furniture = SubClass.Desk("Desk", "Fancy", 38, 38, 32, 250.00, "Left Side", 3) furniture.__str__()
def __init__(self,charName,charRace,charClass): ''' Creates the char and adopts race and class from the other objects ''' self.charName=charName self.charRace=race(charRace) self.charClass=Class(charClass) self.charDescr=""
def findRectangle(graph): count = 0 rectangleL = [] tempList=findStrip(graph) for element in tempList: leftS = stripExtendL(element, graph) rightS = stripExtendR(element, graph) rectangleL.append(Class.rectangle(leftS,rightS)) count = count + 1 return rectangleL
def SA(coolingScheme, t0, tn, houseList, goal, itNR, changeNum, maisonStrat, randomChangeNum=False): counter = 0 winst = 0 all_values = [] distList = Class.initDistList(houseList) #--------------------1-------------------------# for i in range(itNR): value = Class.valueOfMapFast(houseList, distList) house = Hillclimber.getIndex(goal, maisonStrat) #--------------------2--------------------------# oldX = houseList[house].x oldY = houseList[house].y if randomChangeNum: lowerX, higherX = (oldX - random.randint(1, changeNum)), ( oldX + random.randint(1, changeNum)) lowerY, higherY = (oldY - random.randint(1, changeNum)), ( oldY + random.randint(1, changeNum)) else: lowerX, higherX = (oldX - changeNum), (oldX + changeNum) lowerY, higherY = (oldY - changeNum), (oldY + changeNum) newX = random.randint(round(lowerX), round(higherX)) newY = random.randint(round(lowerY), round(higherY)) #--------------------3--------------------------# if not Hillclimber.checkHouseOutOfBounds(houseList[house], newX, newY): houseList[house].x = newX houseList[house].y = newY Class.update_dist_list(houseList, distList, house - 4) newValue = Class.valueOfMapFast(houseList, distList) if (newValue > value or coolingScheme( i, newValue - value, itNR, t0, tn)) and not Class.overlapFinalBoss(houseList): #winst += newValue - value #counter += 1 all_values.append(newValue) else: houseList[house].x = oldX houseList[house].y = oldY Class.update_dist_list(houseList, distList, house - 4) all_values.append(value) else: all_values.append(value) #print("winst =", winst) #print("NR verplaatsingen =", counter) return all_values, houseList
def getBuilding(data): buildinglist = [] for item in data.features: if len(item['geometry']) > 0: # 保证有数据 if 'building' in item['properties']: # if item['properties']['building'] == 'yes': buildinglist.append( RoadClass.Building(item['properties'], item['geometry']['coordinates'])) return buildinglist
def main(): try: import Class global mssql mssql = Class.MSSQL() except Exception as e: print("Connect to the database unsuccessful:", e) else: print("Connect to the database successful!") return mssql
def get_sites_by_topic(topic): connection = sqlite3.connect("Sites.db") courser = connection.cursor() courser.execute("SELECT * FROM Websites WHERE Topic = '" + topic + "'") raw_sites = courser.fetchall() articles = [] for raw_site in raw_sites: site = Class.Article(raw_site[0], raw_site[1], raw_sites[2]) articles.append(site) connection.commit() return articles
def main(host, user, password, database, default_table='baum_test'): try: import Class global table_name table_name = default_table global mssql mssql = Class.MSSQL(host, user, password, database) except Exception as e: print("Connect to the database unsuccessful:", e) else: print("Connect to the database successful!") return mssql
def readHeader(header): file = open(header, "r") parsed_line = {} find_class = False for line in file.readlines(): class_name = getClassName(line) if class_name: main_class = Class(header, class_name) find_class = True dic_method = parseLine(line) if dic_method and find_class: main_class.additem(Method(dic_method, main_class.name)) if find_class: print("*" + "-" * 50 + "*") main_class.display() file.close()
def Get_Merchants(): list = [] main_list_url = "https://www.c5game.com/dota.html" html = rs.get(main_list_url).content soup = BS(html) pattern = re.compile( '''.*?<p class="name"><a href="(.*?)"><span class=" .*? ">(.*?)</span></a></p><p class="info"><span class=".*?">Price:<span class="price">¥ (.*?)</span></span><span class="num">(.*?)piece on selling.*?''' ) for i in soup.select(".selling"): info = re.findall(pattern, str(i).replace("\n", ""))[0] list.append(Class.Merchant(info[0], info[1], info[2], info[3])) return list
def dumpRR(u): name, type, klass, ttl, rdlength = u.getRRheader() typename = Type.typestr(type) print 'name=%s, type=%d(%s), class=%d(%s), ttl=%d' \ % (name, type, typename, klass, Class.classstr(klass), ttl) mname = 'get%sdata' % typename if hasattr(u, mname): print ' formatted rdata:', getattr(u, mname)() else: print ' binary rdata:', u.getbytes(rdlength)
def ogrenci_ekle(): os.system('cls' if os.name == 'nt' else 'clear') print( "\n Necmettin Erbakan Üniversitesi Öğrenci Bilgi Sistemi - Öğrenci ekle" ) ad_soyad = input("\n\n Öğrenci adı, soyadı : ") tc_no = input("\n\n Öğrenci T.C no : ") okul_no = input("\n\n Öğrenci okul no : ") bolum = input("\n\n Öğrenci Bölümü : ") ders_sayi = input("\n\n Öğrenci aldığı ders sayısı : ") ders = [] if int(ders_sayi) > 0: az = 1 for i in range(0, int(ders_sayi)): print("\n\n --- Ders Ekle {} ---".format(az)) ders_adi = input("\n\n Ders adi : ") ders_kodu = input("\n\n Ders kodu : ") ders_final_oran = input("\n\n Ders final oranı (örn: 0.6) : ") ders_vize_oran = input("\n\n Ders vize oranı (örn: 0.4) : ") ders.append( Class.Dersler(ders_adi, ders_kodu, ders_vize_oran, ders_final_oran, -1, -1)) Ogrenciler.append( Class.Ogrenci(ad_soyad, tc_no, okul_no, int(ders_sayi), bolum, ders)) input( "\n\n Ogrenci başarıyla eklenmiştir... Ana menü için Entere basınız." )
def enter(): global ship global fisher global float global fish global bg global Objects global ui global game_time global Locals ui = Class.UI() bg = Class.FixedTileBackground() Locals = [ Object_Class.LOCAL(i) for i in range(bg.local - bg.max_vortex_id) ] Objects = [Object_Class.STONE(i) for i in range(bg.max_stone_id)] Voretx = [ Object_Class.VORTEX(i) for i in range(0, bg.max_vortex_id - bg.max_stone_id) ] Objects = Objects + Voretx ship = Ship_Class.SHIP() fisher = Fisher_Class.FISHER(bg) float = Float_Class.FLOAT(fisher) fish = Fish_Class.FISH() bg.set_center_object(ship) ship.set_background(bg) fish.set_background(bg) float.set_background(bg) for Object in Objects: Object.set_background(bg) for local in Locals: local.set_background(bg) game_time = time.clock() pass
def extractFileData(self, path): curClass = Class.Class() for line in fileinput.input([path]): if line.startswith('.class '): if self.pkgpath not in line: continue curClass.setPackage(self.extractPackage(line)) curClass.setName(self.extractClassName(line)) elif line.startswith('.super '): if (self.pkgpath in line): curClass.setParent(self.extractClassName(line)) matches = re.findall("Landroid/app/(.*?)Activity", line) curClass.isController = (len(matches) > 0) elif (line.startswith('.field')): fieldName = line[line.rfind(" ") + 1:line.rfind(":")] curClass.addField(fieldName) if (' public ' in line or ' protected ' in line): curClass.addPublicField(fieldName) elif (line.startswith('.method ')): if ('<init>' in line): curMethod = Method.Method('constructor') else: match = re.findall(".method (.*?)\(", line)[0].split(" ") l = len(re.findall(".method (.*?)\(", line)[0].split(" ")) if l == 3: curMethod = Method.Method(str(match[2])) elif l == 2: curMethod = Method.Method(str(match[1])) elif l == 1: curMethod = Method.Method(str(match[0])) curMethod = Method.Method("Generic") curClass.addMethod(curMethod) elif (";->" in line): if (self.usesField(curClass, line)): #for LCOM fieldName = line[line.rfind(";->") + 3:line.rfind(":")] curMethod.addFieldUsed(fieldName) if fieldName in curClass.getPublicFields(): self.apd = self.apd + 1 else: #for CBO if not curClass.isController and self.refsNonJavaClass( line): objName = line[line.index("L"):line.index(";->")] if not objName == curClass.getName( ) and not self.inSameTree(curClass, objName): curClass.addCoupledObject(objName) self.classes.append(curClass)
def map(self): import User User.init_db() import Campus Campus.init() import Class Class.init() import ClassRoom ClassRoom.init() import Course Course.init() import Cursus Cursus.init() import Event Event.init() import Period Period.init() import Planning Planning.init() import Settings Settings.init() import University University.init()
def storeRR(self,u): r={} r['name'],r['type'],r['class'],r['ttl'],r['rdlength'] = u.getRRheader() r['typename'] = Type.typestr(r['type']) r['classstr'] = Class.classstr(r['class']) #print 'name=%s, type=%d(%s), class=%d(%s), ttl=%d' \ # % (name, # type, typename, # klass, Class.classstr(class), # ttl) mname = 'get%sdata' % r['typename'] if hasattr(u, mname): r['data']=getattr(u, mname)() else: r['data']=u.getbytes(r['rdlength']) return r
def storeQ(self,u): q={} q['qname'], q['qtype'], q['qclass'] = u.getQuestion() q['qtypestr']=Type.typestr(q['qtype']) q['qclassstr']=Class.classstr(q['qclass']) return q
#!/bin/python3.5 import sys sys.path.append('../class') import Class stone = Class.stone("pedone", 0x01, "file.grafic", "withe", "front", 0x02) stone.display() print (stone.move_stone())
class character(object): ''' Represents a Character with a race and a class ''' def __init__(self,charName,charRace,charClass): ''' Creates the char and adopts race and class from the other objects ''' self.charName=charName self.charRace=race(charRace) self.charClass=Class(charClass) self.charDescr="" def getName(self): ''' Returns Character's Name ''' return self.charName def getRace(self): ''' Returns Character's Race ''' return self.charRace.getName() def getClass(self): ''' Returns Character's Class ''' return self.charClass.getName() def setCharDescr(self,charDescr): ''' Sets Characters Description ''' assert type(charDescr)==str, "Description must be a string" if self.charDescr=="": self.charDescr=charDescr else: print "There is already a Character Descriptio use the update method" def updateCharDescr(self,charDescr): ''' Updates Character's Name ''' assert type(charDescr)==str, "StoryLine must be A string" self.charDescr=charDescr def getCharDescr(self): return self.charDescr def getRaceStory(self): return self.charRace.getStory() def getClassDescr(self): return self.charClass.getDescr() def __str__(self): return str(self.getName())+" "+"is a"+" "+str(self.getRace())+" "+str(self.getClass())+"."
swap((slotOrder1[slotIndex], roomOrder1[roomIndex]), (slotOrder2[slotIndex], roomOrder2[roomIndex])) else: currentCost = newCost # take it if(currentCost < currentMin): currentMin = currentCost currentMinVector = copy.deepcopy(schedule) ''' # modify temp temp *= tempLoss # heartbeat # print(schedule) # printSchedule(rooms) print(currentCost, " : ", temp) t1 = time.time() printSchedule(rooms) print(currentCost) print("num conflicts: " + str(numConflicts())) print("num dropped classes: " + str(len(droppedClasses))) print("time: " + str(t1-t0)) for Class in droppedClasses: print(str(Class.getSize()) + " : " + str(Class.getLength())) print("Lowest value reached (for debugging/testing):") print(currentMin) print("DONE!")
#!/usr/bin/env python #! -*- coding: utf-8 -*- import math print math.sin(0) #导入模块会相应地执行其中的代码,同时模块只有在第一次导入的过程中才会被执行 import sys;sys.path.append('/Users/wangshaoyu/python/learn');import Class; nested=[[1,2],[3,4],[5,6]] #如何调用模块中的方法,使用module.way print list(Class.flatten(nested)) #__name__在主程序中__name__的值是__main__,而在模块中,这个名字是模块名如Class就是 Class print __name__ #可以格式化的输出,如果数据结构过大,不能一行打印完,可以使用pprint模块中的pprint函数替代普通的print语句, import pprint ;pprint.pprint(sys.path) #解释器在列表中查找需要的模块,一开始sys.path就应该包含正确的目录,有两种方法可以保证系统搜索到你的目录: #第一种方法是将你的代码放到合适的根目录的位置,第二种方法是告诉解释器去哪里查找需要的模块。 #标准的实现方法是在PYTHONPATH环境变量中包含模块所在的目录 #模块的三种导入方式 #import drawing 这一条语句之后,__init__模块的内容是可用的, #import drawing.colors 这一条语句之后,可以通过全名drawing.colors来使用, #from drawing import shapes 这一条语句之后,可以通过短名来使用 shapes import copy #print dir(copy) #可以使用dir来查看模块中所有的函数、类、变量 print [n for n in dir(copy) if not n.startswith('_')] #copy 包中可以使用的所有特性__all__ print copy.__all__ #help(copy.copy) #查看模块文档 print copy.__doc__ #快速查找到源代码的路径 print copy.__file__
def load_class(name): #load class function creates a new class object and then loads all applicable students c = Class(name) #instantiate class object c.students = list_users_array(name) # assign array of student names as strings to class object's 'students' attribute return c #return class object with all applicable users - used in Console.py
prog.close() newProg = [] mainBlock,mainClassBlock = Global.generate("main",code) quote = False func = False clas = False switch = False Loop = False Do = False mainCode = [] for lineNum,line in enumerate(code): if lineNum==mainClassBlock[0]: clas = True funcNames = Class.generate("function names",code[lineNum+2:],Global.newClass().findName(line)) elif lineNum==mainClassBlock[1]: newProg += [line for line in mainCode] clas = False elif lineNum==mainBlock[0]: func = True elif lineNum==mainBlock[1]: func = False else: if line[len(line)-1]=='\n': line = line[:len(line)-1] if quote: pass elif switch: if line.lstrip()=="{": pass elif line.lstrip()=="}":