Пример #1
0
 def __init__(self):
     self.stack = Stack()  # Create Object Of Stack Class
     self.file_load = File_Load()  # Create Object Of File_Load Class
     try:
         self.transactions = self.file_load.Read_json(
             "Transaction_Stack.json")  # Read JSON
         for i in self.transactions:  # Loop Through All JSON Data
             self.stack.push(i)  # Push All Data In The Stack
     except FileNotFoundError:
         print("File Not Found..")
 def __init__(self):
     """
     Reading old transaction from transaction json file and maintain in stack
     """
     self.stack = Stack()
     with open("Transaction_stack.json") as data:
         try:
             temp = json.load(data)
         except Exception:
             pass
         else:
             for i in temp:
                 self.stack.push(i)
Пример #3
0
def BalanceParanthesis(Val):

    stack = Stack()  # Create Object Of Class Stack
    for i in Val:  # Loop In String For Each Alphabet
        if i is '(' or i is '{' or i is '[':  # Check The Value Of i If It Open Bracket Then Push In Stack
            stack.push(i)
        elif i is ')' and stack.peak() is '(' or i is '}' and stack.peak(
        ) is '{' or i is ']' and stack.peak() is '[':
            stack.pop(
            )  # Else Check The Last Element Of The Stack And ith Element Of String
            # If One Of Them Is True Then Pop The Element Else Continue The Loop
    if stack.Isempty():
        return True
    else:
        return False
class PrimeWithStack:
    def __init__(self):
        """
        Creating object of stack for maintain and store data
        """
        self.stack = Stack()

    def prime_with_stack(self, rng):
        """
        :param rng : Take one input from user as range
        Print prime number between 2 to range
        """
        prime_number = Utility.get_prime_number(rng)
        anagram = Utility.get_anagram(prime_number)
        for i in anagram:
            self.stack.push(i)
        for i in range(self.stack.size()):
            print(self.stack.pop(), end=" ")
Пример #5
0
def updatestack(data):

    stack1 = Stack()
    stack2 = Stack()
    lista = []
    listb = []
    for i in range(5):
        lista.append(stack1.pop())
        listb.append(stack2.pop())

    ind = lista.index(data)
    listb[ind] = listb[ind] + 1

    for i in range(len(lista)):
        stack1.push(lista[i])

    for i in range(len(listb)):
        stack2.push(listb[i])
Пример #6
0
class CalendarWithStack:
    def __init__(self):
        """
            Creating two object of stack for storing day of month
        """
        self.stack1 = Stack()
        self.stack2 = Stack()

    def display(self, month, year):
        """
            :param month: take month parameter and display it
            :param year: take year parameter and display it
        """
        calendar = Calendar()
        print("------------", month, year, "---------------")
        for i in calendar.week:
            print(i, end="    ")
        for i in range(self.stack2.size()):
            temp = self.stack2.pop()
            if i % 7 == 0:
                print()
            if int(temp) == 0:
                print(end="     ")
            elif int(temp) < 10:
                print(temp, end="    ")
            else:
                print(temp, end="   ")

    def calendar_with_stack(self, month, year):
        """

            :param m: m as month parameter for calculating month
            :param y: y as year parameter for calculating year
        """
        queue = CalendarWithQueue()
        queue = queue.calendar_with_queue(month, year)
        for i in range(queue.size()):
            self.stack1.push(queue.dequeue())
        for i in range(self.stack1.size()):
            self.stack2.push(self.stack1.pop())
class TransactionStack:
    def __init__(self):
        """
        Reading old transaction from transaction json file and maintain in stack
        """
        self.stack = Stack()
        with open("Transaction_stack.json") as data:
            try:
                temp = json.load(data)
            except Exception:
                pass
            else:
                for i in temp:
                    self.stack.push(i)

    def transaction_stack(self, transaction, customer_name, company_name,
                          no_of_share, cost, time):
        """
        Taking all data about stock account transaction and maintain in stack
        :param transaction: it is transaction like sell or buy
        :param customer_name: it is customer name
        :param company_name: it is company name
        :param no_of_share: it is no of share
        :param cost: total cost of share
        :param time: it is time of transaction
        """
        new_transaction = {
            "transaction": transaction,
            "customer_name": customer_name,
            "company_name": company_name,
            "no_of_share": no_of_share,
            "cost": cost,
            "time": time
        }
        self.stack.push(new_transaction)

    def save_transaction(self):
        """
        update transaction json file by queue
        """
        temp1 = []
        size = self.stack.size()
        for i in range(size):
            temp1.append(self.stack.pop())
        with open("Transaction_stack.json", 'w') as data:
            json.dump(temp1, data)
Пример #8
0
class BalancedParentheses:
    def __init__(self):
        """
        Creating object of stack class
        """
        self.stack = Stack()

    def balancedParentheses(self, string):
        """
        :param string : take one input:
        :return : return true if string is balanced else false
        """
        for i in string:
            if i is '(':
                self.stack.push(i)
            elif i is ')' and self.stack.peak() is '(':
                self.stack.pop()

        if self.stack.size() is 0:
            return True
        else:
            return False
Пример #9
0
from Week1.Util import get_anagram, get_prime
from util.Stack import Stack
stack = Stack()
primearray = get_prime()  # Prime Number Array
anagrams = get_anagram(primearray)  # Array Of Anagram Numbers

for i in anagrams:
    stack.push(i)  # Push All Anagrams In Stack

l_size = stack.size()  # Calculate Size Of Stack

while l_size >= 0:
    print(stack.pop(), '', end='')  # Print Stack Elements
    l_size -= 1
Пример #10
0
 def __init__(self):
     """
     Creating object of stack class
     """
     self.stack = Stack()
 def __init__(self):
     """
     Creating object of stack for maintain and store data
     """
     self.stack = Stack()
Пример #12
0
    parser.add_argument(
        "-f",
        "--files",
        help="Number of assembly files created. Defaults to 5.",
        default="5")
    parser.add_argument("-s",
                        "--singleInstruction",
                        help="Test Single Instruction",
                        default="")
    args = parser.parse_args()
    version = int(args.version)
    depth = int(args.level)
    immediateProbability = float(args.immediate)
    files = int(args.files)
    singleInstruction = args.singleInstruction
    stack = Stack()
    # while True:
    #     version = int(input("v1 oder v2? 0: v1\t1: v2\n"))
    #     if version == 0 or version == 1:
    #         break
    #     print("Eingabe entw. 0 oder 1.")
    #     continue
    n = 3

    #while True:
    #    tiefe = int(input("Bitte die Tiefe eingeben (int):\n"))
    #    break

    #while True:
    #    probability = float(input("Bitte die Wahrscheinlichkeit für Immediate eingeben (float zw. 0-1):\n"))
    #    if probability > 1.0 or probability < 0.0:
Пример #13
0
    for i in range(5):
        lista.append(stack1.pop())      # pop all element from stack1 in lista
        listb.append(stack2.pop())      # pop all element from stack1 in listb

    index = lista.index(data)             # read index from lista
    listb[index] += 1         # update the value by 1 in listb

    for i in range(len(lista)):         # push all element of lista in stack1
        stack1.push(lista[i])           # push all element of lista in stack1
        stack2.push(listb[i])


if __name__ == '__main__':

    stack1 = Stack()  # Create stack1 Object For Stack A
    stack2 = Stack()  # Create stack2 Object For Stack B
    fill_stack()
    para = input("Enter Paragraph : ").lower()  # Reading Paragraph From User

    for i in para:                      # Loop Through Paragraph
        if i is ' ':
            continue
        if i is 'a' or i is 'e' or i is 'i' or i is 'o' or i is 'u':         # Check If There is Vowel If True
                update(str(i).lower())             # Calling update Function by Passing Vowel as Parameter

    print("\nStack A : ", end=' ')
    for i in range(5):                             # Print Stack A
        print(stack1.pop(), end='  ')
    print("\nStack B : ", end=' ')
    for i in range(5):                             # Print Stack B
Пример #14
0
 def startgame(self):
     self.turn += 1
     self.cards = start()  #get cards
     self.cards = randomize(self.cards)  #shuffle
     self.disposal = Stack()  #create disposal deck for changed cards
     self.deal()
Пример #15
0
class VP(QWidget):
    def __init__(self, parent=None, flags=Qt.WindowFlags()):
        super().__init__(parent=parent, flags=flags)
        self.setWindowTitle("Video Poker")  #Set Window Title
        self.setGeometry(0, 0, 800, 600)  #set size
        self.assignlabels()
        self.assignbuttons()
        self.turn = 0
        self.layouts()
        self.startgame()

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key(
        ) == QtCore.Qt.Key_Escape:  #if person hits escape, then quit
            self.close()
        if QKeyEvent.key(
        ) == QtCore.Qt.Key_Return:  #if hits enter, then cards are drawn
            self.change()

    def assignlabels(self):
        self.title = QLabel(self)  #set title
        self.title.setText("Video Poker")  #set text
        self.title.setAlignment(QtCore.Qt.AlignCenter)  #align
        font = QFont()  #create font
        font.setPointSize(72)  #set size
        font.setFamily("Arial")  #set font
        self.title.setFont(font)  #assign
        self.title.adjustSize()  #make it fit
        self.instructions = QLabel(self)  #set instructions
        self.instructions.setText(
            '''This version is jacks or better. Any hand greater than or equal to a pair of jacks will win. Press h for list of poker hands or p for payout chart.'''
        )
        self.instructions.setAlignment(QtCore.Qt.AlignCenter)
        self.instructions.adjustSize()
        self.layout = QHBoxLayout()
        self.labels = []
        for i in range(5):  #create labels for images of cards
            self.labels.append(QLabel())
        for i in self.labels:  #add to box layout
            self.layout.addWidget(i)

    def assignbuttons(self):
        self.buttons = []  #create checkboxes
        for i in range(5):
            self.buttons.append(QCheckBox("Change", self))  #label them
        self.horizontalbuttons = QHBoxLayout()
        for i in self.buttons:  #add to box layout
            self.horizontalbuttons.addWidget(i)
        self.buttonenter = QPushButton(self)  #create button for drawing
        self.buttonenter.clicked.connect(self.change)
        self.buttonenter.setText("Draw")

    def layouts(self):
        vert = QVBoxLayout()  #main vertical layout
        vert.addWidget(self.title)  #add title
        vert.addWidget(self.instructions)  #add instructions
        vert.addLayout(self.layout)  #add layout of cards
        vert.addLayout(self.horizontalbuttons)  #add layout of buttons
        vert.addSpacing(100)  #add spacing
        vert.addWidget(self.buttonenter)  #add button
        vert.addSpacing(100)
        self.setLayout(vert)

    def startgame(self):
        self.turn += 1
        self.cards = start()  #get cards
        self.cards = randomize(self.cards)  #shuffle
        self.disposal = Stack()  #create disposal deck for changed cards
        self.deal()

    def deal(self):
        self.hidden = []
        for i in range(5):  #get five cards
            self.hidden.append(self.cards.pop())
        c = 0
        for i in self.labels:
            r = requests.get(self.hidden[c].url)  #get image of card
            image = Image.open(BytesIO(r.content))
            try:
                image.save("Temp1" + "." + image.format,
                           image.format)  #save as temp
            except IOError:
                a = 6
            image = Image.open("Temp1." + image.format)  #open
            image = image.resize((80, 100), Image.ANTIALIAS)  #resize tofit
            image.save("Temp1.png")
            self.pixmap = QPixmap("Temp1.png")  #put on pixmap
            i.setPixmap(self.pixmap)  #put on screen
            c += 1

    def change(self):
        self.turn += 1
        for i in range(5):
            if self.buttons[i].isChecked() == True:  #if button is checked
                self.dispose(self.hidden[i])  #dispose card
                self.hidden[i] = self.cards.pop()  #get new card
                r = requests.get(self.hidden[i].url)
                image = Image.open(BytesIO(r.content))  #get new image of card
                try:
                    image.save("Temp1" + "." + image.format, image.format)
                except IOError:
                    a = 6
                image = Image.open("Temp1." + image.format)
                image = image.resize((80, 100), Image.ANTIALIAS)
                image.save("Temp1.png")
                self.pixmap = QPixmap("Temp1.png")
                self.labels[i].setPixmap(self.pixmap)

        self.buttonenter.setDisabled(True)  #disable change button
        self.determine()

    def dispose(self, card):
        self.disposal.push(card)  #put into disposal deck changed cards

    def determine(self):
        temp = []  #get list of values of cards
        for i in self.hidden:
            temp.append(i.value)
        temp.sort(reverse=True)

        temp2 = []  #get list of suits
        for i in self.hidden:
            temp2.append(i.suit)
        j = findout(temp, temp2)  #get poker hand
        self.printresult(j, temp)  #print result
        self.endturn()  #end turn

    def printresult(self, num, list):
        self.word = ""
        options = [
            "royalflush", "straightflush", "four of a kind", "full house",
            "flush", "straight", "three of a kind", "two pair", "pair",
            "high card"
        ]
        if options[num] != "pair" and options[num] != "high card":
            self.word = "You won! You got a " + options[
                num] + "."  #tell result if greater than pair
            return True
        else:
            for i in list:  #prints how many occurrences of each item in list
                if list.count(i) >= 2:  #if at least two there is a pair
                    if i >= 11:
                        self.word = "You won! You got a pair of jacks or better."  #tell person they had greater than jacks if they did
                        return True
            self.word = "You lost. You got less than a pair of jacks."  #if not, tells person they lost
            return False

    def endturn(self):
        results = QMessageBox()
        temp = results.question(self, "Result",
                                self.word + " Want to play again?", results.Yes
                                | results.No)  #message box to continue or not
        if temp == results.Yes:  #if yes
            for i in self.hidden:  #dispose used cards
                self.disposal.push(i)
            self.cards = empty(self.disposal,
                               self.cards)  #add disposal to main deck
            self.cards = randomize(self.cards)  #shuffle
            self.buttonenter.setDisabled(False)  #enable button again to draw
            for i in self.buttons:  #deselect any boxes the person changed last round
                if i.isChecked() == True:
                    i.setChecked(False)
            self.startgame()  #start game again
            self.word = ""
        elif temp == results.No:  #if not quit
            self.close()
Пример #16
0
 def __init__(self):
     """
         Creating two object of stack for storing day of month
     """
     self.stack1 = Stack()
     self.stack2 = Stack()
Пример #17
0
class TransactionStack:
    def __init__(self):
        self.stack = Stack()  # Create Object Of Stack Class
        self.file_load = File_Load()  # Create Object Of File_Load Class
        try:
            self.transactions = self.file_load.Read_json(
                "Transaction_Stack.json")  # Read JSON
            for i in self.transactions:  # Loop Through All JSON Data
                self.stack.push(i)  # Push All Data In The Stack
        except FileNotFoundError:
            print("File Not Found..")

    """
            AddTransaction Method Takes 5 params
            tr_type : Type Of Transaction BUY Or SELL
            company_name : Name Of The Company
            customer_name : Name Of The Customer
            shares : Number Share That Has Been Sell Or Buy
            total_amount : total Amount Of The Transaction

        """

    def AddTransaction(self, tr_type, company_name, customer_name, shares,
                       total_amount):
        cr_time = dt.datetime.now()  # Create DateTime Object
        cr_time = cr_time.strftime(
            "%d/%m/%Y, %H:%M:%S")  # Format The Date And Time

        try:
            # Create And Assign  newtransaction
            newtransaction = {
                "transaction_type": tr_type,
                "company_name": company_name,
                "customer_name": customer_name,
                "no_of_share": shares,
                "total_amount": total_amount,
                "date_time": cr_time
            }

            # Push new Transaction In The Stack
            self.stack.push(newtransaction)
        except:
            print("Undefined Error..")

    """
            Save Transaction Simply Save The Transaction
            In Json File

    """

    def SaveTransaction(self):
        try:
            temp = []  # Declare One temp List
            size = self.stack.size()  # Get The Size Of The Queue
            for i in range(size + 1):  # Loop Through The size Of Queue
                temp.append(
                    self.stack.pop())  # Append All Queue Data To The List
            self.file_load.Write_json(
                temp, "Transaction_Stack.json")  # Save List Data To The json
        except:
            print("Undefined Error..")