示例#1
0
    def maxProfit(self, prices, maxint=10000):
        if not prices: return 0
        profit = [[[0 for _ in xrange(2)] for _ in xrange(3)]
                  for _ in xrange(len(prices))]
        profit[0][0][0] = 0
        profit[0][0][1] = -prices[0]
        profit[0][1][0] = -maxint
        profit[0][1][1] = -maxint
        profit[0][2][0] = -maxint
        profit[0][2][1] = -maxint
        for i in range(1, len(prices)):
            profit[i][0][0] = profit[i - 1][0][0]
            profit[i][0][1] = max(profit[i - 1][0][1],
                                  profit[i][0][0] - prices[i])

            profit[i][1][0] = max(profit[i - 1][1][0],
                                  profit[i][0][1] + prices[i])
            profit[i][1][1] = max(profit[i - 1][1][1],
                                  profit[i][1][0] - prices[i])

            profit[i][2][0] = max(profit[i - 1][2][0],
                                  profit[i - 1][1][1] + prices[i])
        end = len(prices) - 1

        return max(profit[end][0][0], profit[end][1][0], profit[end][2][0])
示例#2
0
def cell_list():
    lst = []
    for i in xrange(map_sizex):
        lst.append([])
        for g in xrange(map_sizey): lst[i].append(
            (board.map[i][g].location[0] * imgs[2], board.map[i][g].location[1] * imgs[2]))
    return lst
示例#3
0
def countingSundays():
    sundayCounter = 0
    for year in xrange(1901, 2001):
        for month in xrange(1,13):
            if datetime.date(year, month, 1).weekday() == 6:
                sundayCounter += 1
    return sundayCounter
 def update_montecarlo(self, border, screen):
     if border:
         for i in xrange(map_sizex):
             for g in xrange(map_sizey):
                 cell = self.map[i][g]
                 cell.energia = cell.energiatobe
                 loc = cell.location
                 if cell.eneriga > 1:
                     screen.blit(colors2[1],
                                 (loc[0] * imgs[-1], loc[1] * imgs[-1]))
                 else:
                     screen.blit(colors2[2],
                                 (loc[0] * imgs[-1], loc[1] * imgs[-1]))
     else:
         for i in xrange(1, map_sizex - 1):
             for g in xrange(1, map_sizey - 1):
                 cell = self.map[i][g]
                 cell.energia = cell.energiatobe
                 loc = cell.location
                 if cell.eneriga > 1:
                     screen.blit(colors2[1],
                                 (loc[0] * imgs[-1], loc[1] * imgs[-1]))
                 else:
                     screen.blit(colors2[2],
                                 (loc[0] * imgs[-1], loc[1] * imgs[-1]))
示例#5
0
def update(dt):
    # Collision detect
    for i in xrange(len(game_objects)):
        for j in xrange(i + 1, len(game_objects)):
            obj_1 = game_objects[i]
            obj_2 = game_objects[j]
            if not obj_1.is_dead() and not obj_2.is_dead():
                if obj_1.collides_with(obj_2):
                    obj_1.handle_collision_with(obj_2)
                    obj_2.handle_collision_with(obj_1)

    # Added game objects
    to_add = []

    # Update game_objects
    for obj in game_objects:
        obj.update(dt)
        to_add.extend(obj.new_objects)
        obj.new_objects = []

    # Remove dead objects
    for to_remove in [obj for obj in game_objects if obj.is_dead()]:
        to_remove.delete()
        game_objects.remove(to_remove)
        if to_remove.name == 'Asteroid':
            # update_score(dt)
            global num_asteroids
            num_asteroids -= 1
        elif to_remove.name == 'Player Bullet':
            player_ship.remove_shoot()
        print(to_remove.name)

    # Add object
    game_objects.extend(to_add)
 def filljednorodne(self, iloscx, iloscy):
     intervalx = int(map_sizex - 2 / iloscx)
     intervaly = int(map_sizey - 2 / iloscy)
     tmp = 0
     for i in xrange(1, map_sizex - 1, intervalx):
         for j in xrange(1, map_sizey - 1, intervaly):
             self.map[i][j].ziarno = tmp
             tmp += 1
示例#7
0
def quadraticPrimes(limitNum):
    bestValue = (-limitNum * 2, -limitNum * 2, 0)
    for a in xrange(-limitNum, limitNum + 1):
        for b in xrange(-limitNum, limitNum + 1):
            n = howManyPrimes(a, b)
            if n > bestValue[2]:
                bestValue = (a, b, n)
    return bestValue
示例#8
0
 def fillOscilator(self):
     for i in xrange(map_sizex):
         self.map.append([])
         for g in xrange(map_sizey):
             self.map[i].insert(g, Cell((i, g)))
     self.map[4][4].alive = True
     self.map[5][4].alive = True
     self.map[6][4].alive = True
示例#9
0
def namesScores(listNames):
    sumOfNameScores = 0
    sortedNameList = sorted(listOfNames)
    for i in xrange(1, len(sortedNameList) + 1):
        tempSum = 0
        for j in xrange(0, len(sortedNameList[i - 1])):
            tempSum += getNumVal(sortedNameList[i - 1][j])
        sumOfNameScores += i * tempSum
    return sumOfNameScores
示例#10
0
 def draw(self):
     for i in xrange(map_sizex):
         for g in xrange(map_sizey):
             cell = self.map[i][g]
             loc = cell.location
             if cell.alive:
                 screen.blit(alive, (loc[0] * imgs[2], loc[1] * imgs[2]))
             else:
                 screen.blit(dead, (loc[0] * imgs[2], loc[1] * imgs[2]))
示例#11
0
def isTruncatable(num):
    for i in xrange(len(num)):
        tNum = num[i:]
        if sympy.isprime(int(tNum)) == False:
            return False
    for i in xrange(len(num)):
        tNum = num[:len(num) - i]
        if sympy.isprime(int(tNum)) == False:
            return False
    return True
 def update_frame(self, border):
     if border:
         for i in xrange(map_sizex):
             for g in xrange(map_sizey):
                 cell = self.map[i][g]
                 self.get_cells(cell, v3.get())
     else:
         for i in xrange(1, map_sizex - 1):
             for g in xrange(1, map_sizey - 1):
                 cell = self.map[i][g]
                 self.get_cells(cell, v3.get())
 def update_frame_montecarlo(self, border):
     if border:
         for i in xrange(map_sizex):
             for g in xrange(map_sizey):
                 cell = self.map[i][g]
                 self.calculateEnergy(cell)
     else:
         for i in xrange(1, map_sizex - 1):
             for g in xrange(1, map_sizey - 1):
                 cell = self.map[i][g]
                 self.calculateEnergy(cell)
示例#14
0
def digitCancellingFractions():
    count = 0
    prodOfDenominator = 1
    for x in xrange(11,100):
        for y in xrange(11,100):
            if count == 4:
                break
            if isCuriousFraction(x,y) != 1:
                count += 1
                prodOfDenominator *= isCuriousFraction(x,y)
    return prodOfDenominator
示例#15
0
 def update(self):
     for i in xrange(map_sizex):
         for g in xrange(map_sizey):
             cell = self.map[i][g]
             loc = cell.location
             if cell.to_be is not None:
                 cell.alive = cell.to_be
             if self.map[i][g].alive:
                 screen.blit(alive, (loc[0] * imgs[2], loc[1] * imgs[2]))
             else:
                 screen.blit(dead, (loc[0] * imgs[2], loc[1] * imgs[2]))
             cell.to_be = None
示例#16
0
    def render(self, img_rgb):
        #img_rgb = cv2.imread(img_rgb)
        ob2 = PreprocessorWithAspect(800, 1000)
        img_rgb = ob2.preprocess(img_rgb)
        numDownSamples = 1  # number of downscaling steps
        numBilateralFilters = 50  # number of bilateral filtering steps

        # -- STEP 1 --
        # downsample image using Gaussian pyramid
        img_color = img_rgb
        for _ in xrange(numDownSamples):
            img_color = cv2.pyrDown(img_color)
        # cv2.imshow("downcolor",img_color)
        # cv2.waitKey(0)
        # repeatedly apply small bilateral filter instead of applying
        # one large filter
        for _ in xrange(numBilateralFilters):
            img_color = cv2.bilateralFilter(img_color, 9, 9, 7)
        # cv2.imshow("bilateral filter",img_color)
        # cv2.waitKey(0)
        # upsample image to original size
        for _ in xrange(numDownSamples):
            img_color = cv2.pyrUp(img_color)
        # cv2.imshow("upscaling",img_color)
        # cv2.waitKey(0)
        # -- STEPS 2 and 3 --
        # convert to grayscale and apply median blur
        img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
        img_blur = cv2.medianBlur(img_gray, 3)
        # cv2.imshow("grayscale+median blur",img_color)
        # cv2.waitKey(0)
        # -- STEP 4 --
        # detect and enhance edges
        img_edge = cv2.adaptiveThreshold(img_blur, 255,
                                         cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                         cv2.THRESH_BINARY, 11, 9)
        #img_edge=cv2.medianBlur(img_edge,3)

        # cv2.imshow("edge",img_edge)
        # cv2.waitKey(0)

        # -- STEP 5 --
        # convert back to color so that it can be bit-ANDed with color image
        (x, y, z) = img_color.shape
        ob1 = PreprocessorWithAspect(y, x)
        img_edge = ob1.preprocess(img_edge)
        img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
        cv2.imwrite("edge.png", img_edge)
        # cv2.imshow("step 5", img_edge)
        # cv2.waitKey(0)
        # img_edge = cv2.resize(img_edge,(i for i in img_color.shape[:2]))
        # print img_edge.shape, img_color.shape
        return cv2.bitwise_and(img_color, img_edge)
示例#17
0
 def fill(self, ran):
     for i in xrange(map_sizex):
         self.map.append([])
         for g in xrange(map_sizey):
             if ran:
                 a = random.randint(0, 4)
                 if a == 0:
                     self.map[i].insert(g, Cell((i, g), True))
                 else:
                     self.map[i].insert(g, Cell((i, g)))
             else:
                 self.map[i].insert(g, Cell((i, g)))
 def draw(self, screen):
     for i in xrange(map_sizex):
         for g in xrange(map_sizey):
             cell = self.map[i][g]
             loc = cell.location
             if cell.ziarno > 1 and cell.ziarno % 9 == 0:
                 cell.ziarno += 1
             if cell.alive:
                 screen.blit(colors[cell.ziarno % 9],
                             (loc[0] * imgs[-1], loc[1] * imgs[-1]))
             else:
                 screen.blit(colors[cell.ziarno % 9],
                             (loc[0] * imgs[-1], loc[1] * imgs[-1]))
def main():
    """Initialize instance of 'GroupTester', expects additional command line
    arguments indicating first and last pipeline pair id's, test each pipeline
    pair.
    """
    args = get_command_line_args()
    use_dist = True if args['use_dist'] == "y" else False
    tester = GroupTester(uri=args['uri'], use_dist=use_dist)
    start_index = int(args['start_index'])
    end_index = int(args['end_index'])
    fail_counter = 0
    for i in xrange(start_index, end_index + 1):
        if args['ignore_time'] == 'n' and strftime("%H", gmtime()) == "11":
            break
        else:
            if fail_counter < 2:
                if try_pipeline(i, tester):
                    fail_counter = 0
                else:
                    fail_counter += 1
            else:
                exit(
                    datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S") +
                    "UTC - Failed to aggregate two sequential group_pipeline. Exiting. Sorry!"
                )
示例#20
0
def hexdump(src):
    leng = 16
    result = []
    digits = 4 if isinstance(src,unicode) else 2
    for i in xrange(0,len(src),leng):
        s = src[i:i+leng]
        hexa = b''.join()
示例#21
0
def lexicographicPermutation(n, numth):
    if n > 9 or n < 0:
        return 0
    digits = []
    for i in xrange(n + 1):
        digits.append(str(i))
    if math.factorial(n + 1) < numth:
        return 0
    if n == 1:
        if numth == 1: return 0
        else: return 1
    count = 1
    while count < numth:
        i = n
        while digits[i - 1] >= digits[i]:
            i = i - 1
        j = n + 1
        while (digits[j - 1] <= digits[i - 1]):
            j = j - 1
        digits = swapPositions(digits, i - 1, j - 1)
        i += 1
        j = n + 1
        while i < j:
            digits = swapPositions(digits, i - 1, j - 1)
            i += 1
            j -= 1
        count += 1
    return convert(digits)
示例#22
0
 def findAndFillGaps(self):  #抓取空白时间处理下事务
     # if no message is received, we take the chance to do a little cleanup
     for i in xrange(1, self.highestInstance):
         if self.getInstanceValue(i) == None:
             print(u"填充空白", i)
             self.newProposal(0, i)
     self.lasttime = time.time()
 def update(self, border, screen):
     if border:
         for i in xrange(map_sizex):
             for g in xrange(map_sizey):
                 cell = self.map[i][g]
                 cell.ziarno = cell.ziarnotobe
                 loc = cell.location
                 screen.blit(colors[cell.ziarno % 9],
                             (loc[0] * imgs[-1], loc[1] * imgs[-1]))
     else:
         for i in xrange(1, map_sizex - 1):
             for g in xrange(1, map_sizey - 1):
                 cell = self.map[i][g]
                 cell.ziarno = cell.ziarnotobe
                 loc = cell.location
                 screen.blit(colors[cell.ziarno % 9],
                             (loc[0] * imgs[-1], loc[1] * imgs[-1]))
 def get_time_frame_for_lookup(self, year_month):
     start_date = self.get_date_with_data(year_month)
     for hours in xrange(1, 100):
         end_time = start_date + timedelta(hours=hours)
         time_filter = {"$gte": start_date, "$lt": end_time}
         if self.collection.count({self.time_field_name: time_filter}) > 0:
             return start_date, end_time
     raise InvalidTime
示例#25
0
def checkIfSumOfDigits(number, n):
    sum = 0
    lenOfNum = len(str(number))
    for i in xrange(lenOfNum):
        sum += float(str(number)[i])**n
    if int(sum) == number:
        return int(sum)
    else:
        return 0
 def _delete_join_stages(self, pipeline_list):
     """Delete the join and unwind stages from every pipeline, delete the pipeline with
     only a match and a join stage.
     """
     del pipeline_list[1]
     for i in xrange(1, len(pipeline_list)):
         del pipeline_list[i][1]
         if "$unwind" in pipeline_list[i][1]:
             del pipeline_list[i][1]
示例#27
0
def sumOfDivisors(n):
    sqrtNum = math.sqrt(n)
    sumOfDivisors = 1
    if n == sqrtNum * sqrtNum:
        sqrtNum -= 1
    for i in xrange(2, int(sqrtNum)):
        if n % i == 0:
            sumOfDivisors += i + (n / i)
    return sumOfDivisors
示例#28
0
    def fillStatic(self):
        for i in xrange(map_sizex):
            self.map.append([])
            for g in xrange(map_sizey):
                self.map[i].insert(g, Cell((i, g)))
        self.map[4][4].alive = True
        self.map[5][4].alive = True
        self.map[4][5].alive = True
        self.map[5][5].alive = True

        self.map[15][15].alive = True
        self.map[15][16].alive = True
        self.map[16][14].alive = True
        self.map[16][17].alive = True
        self.map[17][14].alive = True
        self.map[17][17].alive = True
        self.map[18][15].alive = True
        self.map[18][16].alive = True
示例#29
0
def coinSums(n):
    if n > 10 or n < 1: return 0
    coins = {1: 1, 2: 2, 3: 5, 4: 10, 5: 20, 6: 50, 7: 100, 8: 200}
    pound = n * 100
    numOfWays = [1] + [0] * pound
    for coin in coins.values():
        for i in xrange(coin, pound + 1):
            numOfWays[i] += numOfWays[i - coin]
    return numOfWays[pound]
 def get_date_with_data(self, year_month):
     year = year_month["_id"]["year"]
     month = year_month["_id"]["month"]
     for day in xrange(1, monthrange(year, month)[1] + 1):
         start_date = datetime(year, month, day)
         end_date = start_date + timedelta(days=1)
         time_filter = {"$gte": start_date, "$lt": end_date}
         if self.collection.count({self.time_field_name: time_filter}) > 0:
             return start_date
     raise InvalidTime