I'm trying create a lambda Sorted by age, but it's not sorting, would appreciate if someone spots the error. Thank you
I made a class and a menu to input employees with name and age, objective is to print the list sorted by age
Here I show the code I have so far
class employee:
def __init__(self, name, age):
self.name = name
self.age = age
i = 0
list = []
def show():
k = 0
while k < len(list):
list2 =[
{'Name': list[k].name,
'Age' : list[k].age}]
_sorted = sorted(list2, key=lambda x: x['Age'], reverse=True)
print(_sorted)
k += 1
while i == 0:
print("Menu")
print("1. Register")
print("2. Show")
print("3. Exit")
option = int(input())
if option == 1:
print("Register")
n = str(input("Ingrese el nombre del empleado: "))
e = int(input("Ingrese la edad del empleado: "))
emp = employee(n, e)
list.append(emp)
print("Empleado guardado con éxito!")
elif option == 2:
print("Mostrar")
mostar()
elif option == 3:
exit()
else:
print("Option inválid")
I've made some minor changes to make the program run:
class employee:
def __init__(self, name, age):
self.name = name
self.age = age
def show(lst): # <--- make function with parameter, don't use global values
for emp in sorted(lst, key=lambda x: x.age, reverse=True): # <--- iterate over sorted list
print(emp.name, emp.age) # <-- print name, age
lst = []
while True: # <-- you don't need `i` variable here, just break when you want to exit
print("Menu")
print("1. Register")
print("2. Show")
print("3. Exit")
option = int(input())
if option == 1:
print("Register")
n = str(input("Ingrese el nombre del empleado: "))
e = int(input("Ingrese la edad del empleado: "))
emp = employee(n, e)
lst.append(emp)
print("Empleado guardado con éxito!")
elif option == 2:
print("Mostrar")
show(lst) # <--- use show(), not mostrar()
elif option == 3:
break # <--- to exit, break
else:
print("Option inválid")
Related
Counting of available objects of the class 'class_name' when changing the variable of the class 'status'.
Tell me how to write a function for counting 'cat_counter' available objects of the class 'class_name' when changing the variable of the class 'status'.
The function only works to increase the counter.
I can't prescribe a condition so that when the variable 'status' != 'normal' the cat counter was decreasing.
from random import random
class Cat:
"""Initialization Cat class"""
counter = 0
def __init__(self, name, color):
self.name = name
self.color = color
self.weight = int(1500 + 3000 * random())
self.minimal_weight = 1000
self.maximal_weight = 9000
self.status = 'normal'
Cat.counter += 1
def cat_counter(self):
if self.cat_status != 'normal':
Cat.counter -= 1
return Cat.counter
def cat_display_parameters(self):
"""Display cat's parameters"""
print(f'name: {self.name}, color: {self.color}, weight: {self.weight}, status: {Cat.cat_status(self)}')
def cat_status(self):
"""Setup cat's status throw weight"""
if self.minimal_weight <= self.weight <= self.maximal_weight:
self.status = 'normal'
elif self.weight <= self.minimal_weight:
self.status = 'dead'
elif self.weight >= self.maximal_weight:
self.status = 'exploited'
return self.status
def cat_meow(self):
"""Cat do meow!"""
meow_weight = 100
if Cat.cat_status(self) == 'normal':
self.weight = self.weight - meow_weight
print(f'Cat with name {self.name} do MEOW!')
else:
print(f'Something wrong with {self.name} cat. Cant do meow.')
def cat_feed(self):
"""Cat do feed"""
feed_weight = 1000
if Cat.cat_status(self) == 'normal':
self.weight = self.weight + feed_weight
print(f'Cat with name {self.name} do MEOW!')
else:
print(f'Something wrong with {self.name} cat. Cant do feed.')
def meow_to_die(self):
"""meow to die"""
while self.weight > self.minimal_weight and Cat.cat_status(self) == 'normal':
Cat.cat_meow(self)
def feed_to_exploid(self):
"""feed to exploit"""
while self.weight < self.maximal_weight and Cat.cat_status(self) == 'normal':
Cat.cat_feed(self)
"""Testing cat_one"""
cat_one = Cat('Cat_one', 'color_one')
cat_one.cat_display_parameters()
print('Number of cats:', Cat.counter)
"""Let's do meow to die cat_one"""
cat_one.meow_to_die()
cat_one.cat_display_parameters()
cat_two = Cat('Name_two', 'color_two')
cat_two.cat_display_parameters()
print('Number of cats:', Cat.counter)
"""Let's feed to explode cat_two"""
cat_two.feed_to_exploid()
cat_two.cat_display_parameters()
cat_three = Cat('Name_three', 'color_three')
cat_three.cat_display_parameters()
print('Number of cats:', Cat.counter)
I tried the counter inside the class.
I tried to solve it via #classmethod.
I'm trying to change the prefix of quotation's sequence in Odoo.
I want that the prefix change by a boolean but i don't have any result.
Here is my code :
class prefix_change(models.Model):
_inherit = 'sale.order'
prefix_choice = fields.Boolean(string="Set to OL", default=False)
def _get_sequence(self, xml_id='quotation.seq'):
user = self.env.user
sequence = self.env['ir.sequence'].with_company(user.company_id).next_by_code(xml_id)
if not sequence:
return _('New')
try:
prefix, suffix = sequence.split('-')
except Exception as e:
logging.error(repr(e))
return _('New')
if not self.prefix_choice :
prefix = "BE"
else:
prefix = "OL"
return "%s-%s-%s" % (prefix, suffix)
Thanks by advance....
Answer W.R.T create and write call:
#api.model
def create(self, values):
res = super(prefix_change, self).create(values)
name = res.name
if res.prefix_choice:
name = res.name.replace('SO', 'OL')
else:
name = res.name.replace('SO', 'BE')
res.name = name
return res
def write(self, values):
res = super(prefix_change, self).write(values)
if 'prefix_choice' in values and values.get('prefix_choice'):
#update code accordingly if needed
if 'BE' in self.name:
self.name = self.name.replace('BE', 'OL')
if 'prefix_choice' in values and not values.get('prefix_choice'):
if 'OL' in self.name:
self.name = self.name.replace('OL', 'BE')
return res
Please check and let me know if it works for you.
So I am working on a project where we are making a small compiler program but before I can move on to the other parts I am having troubles with getting the lexical analyzer to output anything after '\BEGIN' afterwards I debugged it and it seems the value is stuck in a loop where the condition is saying the next character is always a newline. Is it because I haven't added the pattern matching yet to the defined tokens?
Here is the code
import java.util
//import com.sun.javafx.fxml.expression.Expression.Parser.Token
/*Lexical analyzer will be responsible for the following:
- finds the lexemes
- Checks each given character determining the tokens
* */
class MyLexicalAnalyzer extends LexicalAnalyzer {
//Array full of the keywords
//val SpecialCharacters = List(']', '#', '*', '+', '\\', '[', '(',')', "![", '=')
val TEXT = "[a-z] | _ | 0-9 | [A-Z]:"
private var sourceLine: String = null
private val lexeme: Array[Char] = new Array[Char](999)
private var nextChar: Char = 0
private var lexLength: Int = 0
private var position: Int = 0
private val lexems: util.List[String] = new util.ArrayList[String]
def start(line: String): Unit = {
initializeLexems()
sourceLine = line
position = 0
getChar()
getNextToken()
}
// A helper method to determine if the current character is a space.
private def isSpace(c: Char) = c == ' '
//Defined and intialized tokens
def initializeLexems(): Any = {
lexems.add("\\BEGIN")
lexems.add("\\END")
lexems.add("\\PARAB")
lexems.add("\\DEF[")
lexems.add("\\USE[")
lexems.add("\\PARAE")
lexems.add("\\TITLE[")
lexems.add("]")
lexems.add("[")
lexems.add("\\")
lexems.add("(")
lexems.add(")")
lexems.add("![")
lexems.add("=")
lexems.add("+")
lexems.add("#")
}
//val pattern = new regex("''").r
def getNextToken() ={
lexLength = 0
// Ignore spaces and add the first character to the token
getNonBlank()
addChar()
getChar()
// Continue gathering characters for the token
while ( {
(nextChar != '\n') && (nextChar != ' ')
}) {
addChar()
getChar()
}
// Convert the gathered character array token into a String
val newToken: String = new String(lexeme)
if (lookup(newToken.substring(0, lexLength)))
MyCompiler.setCurrentToken(newToken.substring(0,lexLength))
}
// A helper method to get the next non-blank character.
private def getNonBlank(): Unit = {
while ( {
isSpace(nextChar)
}) getChar()
}
/*
Method of function that adds the current character to the token
after checking to make sure that length of the token isn't too
long, a lexical error in this case.
*/
def addChar(){
if (lexLength <= 998) {
lexeme({
lexLength += 1; lexLength - 1
}) = nextChar
lexeme(lexLength) = 0
}
else
System.out.println("LEXICAL ERROR - The found lexeme is too long!")
if (!isSpace(nextChar))
while ( {
!isSpace(nextChar)
})
getChar()
lexLength = 0
getNonBlank()
addChar()
}
//Reading from the file its obtaining the tokens
def getChar() {
if (position < sourceLine.length)
nextChar = sourceLine.charAt ( {
position += 1;
position - 1
})
else nextChar = '\n'
def lookup(candidateToken: String): Boolean ={
if (!(lexems.contains(candidateToken))) {
System.out.println("LEXICAL ERROR - '" + candidateToken + "' is not recognized.")
return false
}
return true
}
}
else nextChar = '\n'<- this is where the condition goes after rendering the first character '\BEGIN' then just keeps outputting in the debug console as listed below.
This is what the debug console it outputting after '\BEGIN' is read through
Can anyone please let me know why that is? This happens after I keep stepping into it many times as well.
Here is the driver class that uses the lexical analyzer
import scala.io.Source
object MyCompiler {
//check the arguments
//check file extensions
//initialization
//get first token
//call start state
var currentToken : String = ""
def main(args: Array[String]): Unit = {
val filename = args(0)
//check if an input file provided
if(args.length == 0) {
//usage error
println("USAGE ERROR: Must provide an input file. ")
System.exit(0)
}
if(!checkFileExtension(args(0))) {
println("USAGE ERROR: Extension name is invalid make sure its .gtx ")
System.exit(0)
}
val Scanner = new MyLexicalAnalyzer
val Parser = new MySyntaxAnalyzer
//getCurrentToken(Scanner.getNextToken())
//Parser.gittex()
for (line <- Source.fromFile(filename).getLines()){
Scanner.start(line)
println()
}
//.......
//If it gets here, it is compiled
//post processing
}
//checks the file extension if valid and ends with .gtx
def checkFileExtension(filename : String) : Boolean = filename.endsWith(".gtx")
def getCurrentToken() : String = this.currentToken
def setCurrentToken(t : String ) : Unit = this.currentToken = t
}
The code is operating as it is supposed to. The first line contains only the string \BEGIN so the lexical analyser is treating the end of the first line as an '\n' as shown in this method:
def getChar() {
if (position < sourceLine.length)
nextChar = sourceLine.charAt ( {
position += 1;
position - 1
})
else nextChar = '\n'
However, the comment directly above that method does not describe what the method actually does. This could be a hint as to where your confusion lies. If the comment says it should read from the file, but it is not reading from the file, maybe that's what you've forgotten to implement.
I am reading a file that contain 277272 lines with Int triples (s,p,o) like:
10,44,22
10,47,12
15,38,3
15,41,30
16,38,5
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48
From this file I create a Random access file object in order to navigate trough this file. However I want to extract some specific values that are in the first column, an example can be that I want to extract the values of the row that contains 16 in the first column, then I choose a pointer that is in the half, something like:
var lengthfile = (file.length().asInstanceOf[Int])
var initpointer = lengthfile/2
Then I analize if the first value is 16, if not I did a procedure to move the pointer to the nextlines, or as in this case in the back lines. Once I detect that the first value is 16, I need to know if it was in the first row, the sceond or the last one. The functions that I present here are to get the first value of the line where I have the pointer, and to know the first value from the next line.
def firstvalue(pf: Int, file:RandomAccessFile): List[Int] ={
//val file = new RandomAccessFile(filename, "r")
var pointer = pf
var flag = true
var fline = Option("a")
if (pointer <= file.length()-1){
file.seek(pointer)
fline = Option(file.readLine)
}
else {
pointer = file.length().toInt-12
file.seek(pointer)
fline = Option(file.readLine)
}
while (flag)
{
if (fline.get != "")
{
if (pointer == 0)
{
file.seek(pointer)
fline = Option(file.readLine)
pointer -= 1
flag = false
}
else{
pointer -= 1
file.seek(pointer)
fline = Option(file.readLine)
}
}
else if (fline.get == ""){
flag = false
}
}
pointer += 1
file.seek(pointer)
val line = Option(file.readLine)
val spl = line.get.split(',')
val p = spl.apply(0).toInt
//file.close()
val l = pointer :: p :: Nil
l
}
//def nextvalue(pf: Int, filename:String): List[Int] = {
//val file = new RandomAccessFile(filename, "r")
def nextvalue(pf: Int, file:RandomAccessFile): List[Int] = {
//val file = new RandomAccessFile(filename, "r")
var pointer = pf
var p = 0
var flag = true
var lastline = false
var fline = Option ("a")
if (pointer <= file.length()-1){
file.seek(pointer)
fline = Option(file.readLine)
}
//fline = Option(file.readLine)
while (flag){
if (fline.get != "")
{
if (fline == None)
{
flag = false
lastline = true
}
else{
pointer = file.getFilePointer.toInt
fline = Option(file.readLine)
flag = false
}
}
else if (fline.get == ""){
fline = Option(file.readLine)
flag = false
}
}
if (lastline == false)
{
//file.close()
if (fline != None){
val spl = fline.get.split(',')
p = spl.apply(0).toInt
}
}
val l = pointer :: p :: Nil
l
}
However I have a prformance problem, because I am reading character by character, I am trying to fix that during a lot of days, and I don't have a solution. I don't know If perhaps the file object have a function to read back lines, or something that allows to me improve this code? How can I improve this code?
Source
.fromFile(file)
.getLines
.zipWithIndex
.filter(_._1.startsWith("16,"))
Will give you all lines, that start with "16", along with their indices in the file. That should be faster then seeking back and forth ...
If I create a segmented row field like so:
<<< SegmentedRow<String>(){ row in
row.title = "Sex"
row.tag = "sex"
row.selectorTitle = "Select your sex"
row.options = ["Male","Female"]
}
How do I match the options to a specific value? For example if a user select Male, then is there a way to get M instead of Male in code, but still shows Male to the User?
Or if I have a list of countries for example:
<<< PushRow<String>(){ row in
row.title = "Passport Issuing Country"
row.tag = "passportIssuingCountry"
row.selectorTitle = "Passport Issuing Country"
row.options = ["AUSTRALIA","AUSTRIA","BELGIUM"]
}
can I assign each Country name to a country code, like AUSTRALIA will return AU, AUSTRIA will return AT, etc.
Right now, there's no way to hold an internal value for an option - but this is what you can do:
1. Create an enum with all available options
enum Sex: Int {
case NotKnown = 0
case Male = 1
case Female = 2
case NotApplicable = 9
static let all = [NotKnown, Male, Female, NotApplicable]
static let strings = ["Unknown", "Male", "Female", "Not Applicable"]
func string() -> String {
let index = Sex.all.index(of: self) ?? 0
return Sex.strings[index]
}
static func fromString(string: String) -> Sex {
if let index = Sex.strings.index(of: string) {
return Sex.all[index]
}
return Sex.NotKnown
}
}
2. Create your row with all the options you want to expose
<<< SegmentedRow<String>(){ row in
row.title = "Sex"
row.tag = "sex"
row.selectorTitle = "Select your sex"
row.options = [Sex.Female.string(), Sex.Male.string()]
}
3. Read the value
let row: SegmentedRow<String>? = self.form.rowBy(tag: "sex")
if let value = row?.value {
// Returns "Female"
print(value)
// Returns 2
print(Sex.fromString(string: value).rawValue)
}
The user sees and selects Strings, but you get an enum-value that you for example can save in your database as an integer (see: ISO/IEC 5218).
https://en.wikipedia.org/wiki/ISO/IEC_5218