I had to hand in a python project for my school and I completely skipped it, so I'm a week late. I'm not sure if anyone can help me with this, but I know that is so easy for some people so it would be great to have someone help me because I have to hand it in as soon as possible.
The subject (translated from french to english so maybe some errrors): https://docs.google.com/document/d/17S_vqe7oqFsBjpP5ACIS5371a4t9eiOpxnPuMwlnj5Q/edit?usp=sharing
I already make part 1.
--> I need help on part 2, I already made the dec_to_bin function which return correctly binary but i don't know how to use a class to made that function like i had to do:
def dec_to_bin(n):
if n >= 1:
dec_to_bin(n // 2)
print(n % 2, end = '')
if __name__ == '__main__':
dec_val = 123456
dec_to_bin(dec_val)
My 2 previous class :
class Cellule:
def __init__(self, valeur, precedent=None, suivant=None):
self.valeur = valeur
self.precedent = precedent
self.suivant = suivant
class File:
def __init__(self):
self.longueur = 0
self.debut = None
self.fin = None
def estVide(self):
return self.longueur == 0
def enfiler(self, valeur):
if self.longueur == 0:
self.debut = self.fin = Cellule(valeur)
else:
self.fin = Cellule(valeur, self.fin)
self.fin.precedent.suivant = self.fin
self.longueur += 1
def defiler(self):
if self.longueur > 0:
valeur = self.debut.valeur
if self.longueur > 1:
self.debut = self.debut.suivant
self.debut.precedent = None
else:
self.debut = self.fin = None
self.longueur -= 1
return valeur
def __str__(self):
ch = "\nFile actuelle:\n"
cellule = self.debut
while cellule != None:
ch += str(cellule.valeur) + " "
cellule = cellule.suivant
return ch
and
class Cellule:
def __init__(self, valeur, suivant=None):
self.valeur = valeur
self.suivant = suivant
class Pile:
def __init__(self):
self.taille = 0
self.sommet = None
def estVide(self):
return self.taille == 0
def empiler(self, valeur):
self.sommet = Cellule(valeur, self.sommet)
self.taille += 1
def depiler(self):
if self.taille > 0:
valeur = self.sommet.valeur
self.sommet = self.sommet.suivant
self.taille -= 1
return valeur
def lsommet(self):
return self.sommet.valeur
def __str__(self):
ch = "\nEtat de la pile:\n"
sommet = self.sommet
while sommet != None:
ch += "|\t" + str(sommet.valeur) + "\t|" + "\n"
sommet = sommet.suivant
return ch
Related
I know this is gonna be long questions, so sorry. I'm very thankful if anyone can solve my problem.
I Have code to scoring and labeling text sentiment like this:
import re
from collections import OrderedDict
import numpy as np
class sentistrength:
def __init__(self, config=dict()):
self.negasi = [line.replace('\n','') for line in open("/content/negatingword.txt").read().splitlines()]
#create sentiment words dictionary
self.sentiwords_txt = [line.replace('\n','').split(":") for line in open("/content/sentiwords_modif.txt").read().splitlines()]
self.sentiwords_dict = OrderedDict()
for term in self.sentiwords_txt:
self.sentiwords_dict[term[0]] = int(term[1])
#create boosterwords dictionary
self.boosterwords_txt = [line.replace('\n','').split(":") for line in open("boosterwords_id.txt").read().splitlines()]
self.boosterwords_dict = OrderedDict()
for term in self.boosterwords_txt:
self.boosterwords_dict[term[0]] = int(term[1])
self.negation_conf = config["negation"]
self.booster_conf = config["booster"]
self.mean_conf = False
def senti(self,term):
try:
return self.sentiwords_dict[term]
except:
return 0
def booster(self, term):
try:
return self.boosterwords_dict[term]
except:
return 0
def cek_negationword(self, prev_term, prev_term2):
#jika kata sebelumnya (index-1) adalah kata negasi, negasikan nilai -+nya
if prev_term in self.negasi or prev_term2+" "+prev_term in self.negasi:
# print prev_term
self.score = -abs(self.score) if self.score>0 else abs(self.score)
def cek_boosterword(self,term):
booster_score = self.booster(term)
if booster_score !=0 and self.score>0: self.score += booster_score
if booster_score !=0 and self.score<0: self.score -= booster_score
def cek_consecutive_term(self, prev_term):
if self.prev_score>0 and self.score >=3: self.score+=1
if self.prev_score<0 and self.score <=-3: self.score-=1
def plural_to_singular(self, term):
return re.sub(r'([A-Za-z]+)\-\1', r'\1',term)
def classify(self):
result = "neutral"
try:
if self.mean_conf:
mean_p = np.mean(self.mean_pos)
mean_n = np.mean(self.mean_neg)
print(mean_p, mean_n)
if mean_p > mean_n:
result = "positive"
elif mean_p < mean_n and not self.is_tanya:
result = "negative"
elif mean_p < mean_n and self.is_tanya:
result = "neutral"
else:
if abs(self.sentences_max_pos) > abs(self.sentences_max_neg):
result = "positive"
elif abs(self.sentences_max_pos) < abs(self.sentences_max_neg):
result = "negative"
elif abs(self.sentences_max_pos) == abs(self.sentences_max_neg):
result = "neutral"
except:
print("error ",self.sentences_max_pos, self.sentences_max_neg)
return result
def cek_neutral_term(self,terms,i):
if terms[i-1] in self.neutral_term or terms[i+1] in self.neutral_term: self.score=1
def main(self,sentence):
self.neutral_term = ['jika','kalau']
sentences = sentence.split('.')
self.sentences_max_neg = -1
self.sentences_max_pos = 1
self.sentences_score = []
self.sentences_text = []
for sentence in sentences:
self.max_neg = -1
self.max_pos = 1
self.mean_neg = [1]
self.mean_pos = [1]
self.sentence_score=[]
terms = sentence.split()
# terms = re.split(r'[\s,.]',sentence)
terms_length = len(terms)
self.is_tanya = False
self.sentence_text = ''
# print self.max_pos, self.max_neg
#SEMUA KALIMAT YANG MEMILIKI TANDA SERU MEMILIKI +ve minimal 2
self.prev_score = 0
self.pre_max_pos = []
self.pre_max_neg = []
for i,term in enumerate(terms):
# repeated_term = ''
is_extra_char = False
plural = ''
self.score = 0
# if re.search(r'[A-Za-z\-.]+',term):
# print term
if re.search(r'([A-Za-z])\1{3,}',term):
is_extra_char = True
# repeated_term =term
if re.search(r'([A-Za-z]+)\-\1',term):
plural = term
term = self.plural_to_singular(term)
#GET SENTI SCORE#
self.score = self.senti(term)
# print "senti score",term, self.score
#NEGATION HANDLER#
if self.negation_conf and self.score !=0 and i>0:self.cek_negationword(terms[i-1],terms[i-2])
# print "negation score",term, self.score
#BOOSTERWORD HANDLER#
if self.booster_conf and self.score !=0 and i>0 and i< (terms_length 1):self.cek_boosterword(terms[i-1])
if self.booster_conf and self.score !=0 and i>=0 and i<(terms_length-1):self.cek_boosterword(terms[i+1])
# print "booster score",term, self.score
# CEK neutral term
if self.score!=0 and i>1 and i<(terms_length-2): self.cek_neutral_term(terms,i)
# if self.score!=0 and i>0 and i<(terms_length-4): self.cek_neutral_term(terms,i)
self.prev_score = self.score
if self.mean_conf and self.score>0: self.mean_pos.append(self.score)
if self.mean_conf and self.score<0: self.mean_neg.append(abs(self.score))
#GET MAX SCORE +ve/-ve
self.max_pos= self.score if self.score > self.max_pos else self.max_pos
self.max_neg= self.score if self.score < self.max_neg else self.max_neg
#insert score info current term
self.pre_max_pos.append(self.max_pos)
self.pre_max_neg.append(self.max_neg)
# print self.pre_max_pos, self.pre_max_neg
if plural !='': term = plural
self.sentence_text += ' {}'.format(term)
if self.score != 0:term = "{} [{}]".format(term, self.score)
self.sentence_score.append(term)
self.sentences_text.append(self.sentence_text)
self.sentences_score.append(" ".join(self.sentence_score))
if self.is_tanya:
self.max_neg = -1
self.sentences_max_pos = self.max_pos if self.max_pos > self.sentences_max_pos else self.sentences_max_pos
self.sentences_max_neg = self.max_neg if self.max_neg < self.sentences_max_neg else self.sentences_max_neg
# print self.sentences_max_pos, self.sentences_max_neg
sentence_result = self.classify()
# print self.sentences_text
return {"classified_text":". ".join(self.sentences_score),"tweet_text":". ".join(self.sentences_text),"sentence_score":self.sentences_score,"max_positive":self.sentences_max_pos,"max_negative":self.sentences_max_neg,"kelas":sentence_result}
config = dict()
config["negation"] = True
config["booster"] = True
senti = sentistrength(config)
print(senti.main("bagus"))
the OUTPUT is like this:
{'classified_text': 'bagus [4]', 'tweet_text': ' bagus', 'sentence_score': ['bagus [4]'], 'max_positive': 4, 'max_negative': -1, 'kelas': 'positive'}
I have thousands of texts that I want to find sentiment labels for. Is there a way to loop print so that it doesn't have to print each text one by one.
And is there a way to get the output to be a dataframe with commas as column separators? So the output look like this:
|'classified_text': 'bagus [4]'| 'tweet_text': ' bagus'| 'sentence_score': ['bagus [4]']
column continuation:
|'max_positive': 4 | 'max_negative': -1 | 'kelas': 'positive'|
Hi there I have a mission: to implement 10 ID numbers according to the exceptions and conditions in the code
i want that the output will be
123456782
123456790
123456808
123456816
123456824
123456832
123456840
123456857
123456865
123456873
and somehow i Can't reach the desired output, anyone can help? :)
import string
letters = string.ascii_letters
digits = string.digits
class NumNotNineLong(Exception):
def __init__(self):
pass
def __str__(self):
return "The number you provided is not nine digits long."
class NotNumber(Exception):
def __init__(self):
pass
def __str__(self):
return "The input you provided is not an integer"
class IDIterator():
increment = 1
def __init__(self,_id):
self._id = _id
def __iter__(self):
return self
def __next__(self):
while check_id_valid(str(self._id)[-9::]) == False:
self._id *= 2
self._id += IDIterator.increment
IDIterator.increment += 1
if check_id_valid(str(self._id)[-9::]):
result = str(self._id)[-9::]
self._id *= 2
self._id += 1
IDIterator.increment = 2
return result
def check_id_valid(id_number):
for letter in str(id_number):
if letter not in string.digits:
raise NotNumber
numbers = [int(i) for i in str(id_number)]
if len(numbers) != 9:
raise NumNotNineLong
set_numbers = []
for i in range(len(numbers)):
if i % 2 == 0:
set_numbers.append(numbers[i])
else:
set_numbers.append(numbers[i] * 2)
true_numbers = []
for num in set_numbers:
if num > 9:
temp = [int(i) for i in str(num)]
true_numbers.append(sum(temp))
else:
true_numbers.append(num)
if sum(true_numbers) % 10 == 0:
return True
else:
return False
def main():
result = IDIterator(123456780)
for _ in range(10):
print(result.__next__())
if __name__ == "__main__":
main()
I am trying to make a sudoku solver that solves boards very quickly. At the moment my solver works on easy boards but never terminates on harder boards. I believe it has something to do with my recursion because easy boards do not require recursion and hard boards do. Any help is appreciated.
import sys
def rowno(i):
return i // 9
def colno(i):
return i % 9
def boxno(i):
return (i // 9 // 3 )*3 + (i // 3) % 3
def isNeighbor(i, j):
if rowno(i) == rowno(j) or colno(i) == colno(j) or boxno(i) == boxno(j):
return True
else:
return False
def getFileName():
if sys.platform == "win32":
filename = input("Filename? ")
else:
filename = sys.argv[-1]
return filename
solutionlist = []
class Board(object):
def __init__(self, puzzle):
self.puzzle = puzzle
self.board = [Cell(int(value), idx) for idx, value in enumerate(puzzle)]
self.change = False
def printAll(self):
print [cell.candidates for cell in self.board]
#return str(" ")
def update(self):
self.change = False
l = [cell for cell in self.board if len(cell.candidates) == 1]
for i in l:
for j in xrange(81):
if isNeighbor(i.dex, j) and i.dex != j:
old = self.board[j].candidates
self.board[j].delCandidate(i.value)
if len(old) != len(self.board[j].candidates):
self.change = True
def toString(self):
str1 = ''.join(str(e.value) for e in self.board)
return str1
def solved(self):
for cell in self.board:
if len(cell.candidates) != 1:
return False
return True
def solve(self):
self.change = True
while self.change == True:
self.update()
if self.solved():
solutionlist.append(self.board)
return
l = [cell for cell in self.board if len(cell.candidates) > 1]
for i in l:
for j in i.candidates:
newBoard = Board(self.toString())
curLen = 12
curCell = -1
for u in l:
if len(u.candidates)<curLen:
curLen=len(u.candidates)
curCell = u.dex
for c in newBoard.board[curCell].candidates:
newBoard.board[curCell].candidates = [int(c)]
newBoard.board[curCell].value = int(c)
newBoard.solve()
return
def __repr__(self):
l = [cell.value for cell in self.board]
return str(l)
class Cell(object):
def __init__(self, value, dex):
self.value = value
self.dex = dex
if value == 0:
self.candidates = [1,2,3,4,5,6,7,8,9]
else:
self.candidates = [int(value)]
def __str__(self):
return str(self.value)
def delCandidate(self, value):
# deletes value from candidate list
#return self.candidate.remove(value);
self.candidates = [x for x in self.candidates if x != value]
if len(self.candidates) == 1:
self.value = self.candidates[0]
easy = "700583006006001405052006083300200958500078060648010300060802500003150072215600030"
twosol = "000805200800000401705040009000100702040000000006430000030900000010006080000000000"
hard = "040090008000000070060000120030020000005839060080600700050170600000043000003000200"
#easy solution: 794583216836721495152496783371264958529378164648915327967832541483159672215647839
b = Board(hard)
print b
b.solve()
print "end of the line"
for i in solutionlist:
print [cell.value for cell in i]
print "\n"
One major issue is the line for i in l: in the solve method. Since you're recursing, you only need to fill in one cell - the recursion will take care of the rest. So instead of for i in l:, just recurse on the one cell that is the best candidate (curCell):
l = [cell for cell in self.board if len(cell.candidates) > 1]
if len(l) > 0:
newBoard = Board(self.toString())
curLen = 12
curCell = -1
for u in l:
if len(u.candidates)<curLen:
curLen=len(u.candidates)
curCell = u.dex
for c in newBoard.board[curCell].candidates:
newBoard.board[curCell].candidates = [int(c)]
newBoard.board[curCell].value = int(c)
newBoard.solve()
from Tkinter import *
class Calc():
def_init_(self):
self.total = 0
self.current = ""
self.new_num = True
self.op_pending = False
self.op = ""
self.eq_flag = False
def num_press(self, num):
temp = text_box.get()
self.eq_flag = False
temp2 = str(num)
if self.new_num == True:
self.current = temp2
self.new_num = False
else:
if temp2 == '.':
if temp2 in temp:
return
self.current = temp + temp2
text_box.delete(0, END)
text_box.insert(0, self.current)
def calc_total(self):
if self.op_pending == True:
self.do_sum()
self.op_pending = False
def do_sum(self):
self.current = float(self.current)
if self.op == "add":
self.total += self.current
if self.op == "minus":
self.total -= self.current
if self.op == "times":
self.total *= self.current
if self.op == "divide":
self.total /= self.current
text_box.delete(0, END)
text_box.insert(0, self.total)
self.new_num = True
def operation(self, op):
if self.op_pending == True:
self.do_sum()
self.op = op
else:
self.op_pending = True
if self.eq_flag == False:
self.total = float(text_box.get())
else:
self.total = self.current
self.new_sum = True
self.op = op
self.eq_flag = False
def cancel(self):
text_box.delete(0, END)
text_box.insert(0, "0")
self.new_num = True
def all_cancel(self):
self.cancel()
self.total = 0
def sign(self):
self.current = -(float(text_box.get()))
text_box.delete(0, END)
text_box.insert(0, self.current())
numbers = "789456123"
i = 0
bttn= []
for k in range(1,4):
for k in range(3):
bttn.append(Button(calc, text = numbers[i]))
bttn[i].grid(row = j, column = k, pady = 5)
bttn[i]["command"] = lambda x = numbers[i]: sum1.num_press(x)
i += 1
I did try Python 3.3 and 2.7 both say the syntax error after 'def_init_(self):'
Is there any fix or something that? Thanks in advance
def_init_(self):
Add a space between def and the function name. And make sure they're double underscores if you want to specify the special initialization method.
def __init__(self):
Your program will then be syntactically correct (although it still won't run because calc isn't defined in the global scope)
Somehow the linebreaks are not working as they should.
This is what I get:
Expected:
O meu u2 2 post
http://www.yahoo.com
1 Gosto, 0 Nao gosto
<BLANKLINE>
O meu u2 post
http://www.altavista.com
1 Gosto, 0 Nao gosto
Got:
'O meu u2 2 post\nhttp://www.yahoo.com\n1 Gosto, 0 Nao Gosto\n\nO meu u2\nhttp://www.yahoo.com\n1 Gosto, 0 Nao Gosto'
This is the code used in the function.
The important parts should be the str and showRecentComments functions
class Comments():
def __init__(self, u=None, text='', link=None):
self.u = u
self.text = text
self.link = link
self.topo = None
self.fim = None
def __str__(self):
actual = self.topo
s = ''
if actual == None:
return None
while actual != None:
if actual.seg == None:
s += str(actual)
actual = actual.seg
else:
s += str(actual) + '\n' + '\n'
actual = actual.seg
return s
def add(self,comment):
if self.topo == None:
self.topo = comment
self.fim = comment
else:
comment.seg = self.topo
self.topo.ant = comment
self.topo = comment
def remove(self,comment):
actual = self.topo
if (self.topo == self.fim) and (self.topo == comment):
self.topo = None
self.fim = None
while actual!=None:
if actual == comment:
if self.topo==comment:
actual.seg.ant = None
self.topo = actual.seg
elif self.fim==comment:
actual.ant.seg = None
self.fim = actual.ant
else:
actual.seg.ant = actual.ant
actual.ant.seg = actual.seg
break
else:
actual = actual.seg
def countLike(self):
count = 0
actual = self.topo
while actual != None:
if len(actual.likeList) >= 1:
count += 1
actual = actual.seg
else:
actual = actual.seg
return count
def showRecentComments(self,n):
count = 1
actual = self.topo
sC = ''
if actual == None:
return None
while actual != None:
if count < n:
sC += str(actual) + '\n' + '\n'
count += 1
actual = actual.seg
elif count == n:
sC += str(actual)
count += 1
actual = actual.seg
elif count > n:
break
return sC
Regards, Nelson Gregório
It looks like you're looking at the representation of the string, which will show you the newline characters as \n. If you print or write to e.g. stdout (sys.stdout.write(s)) the string instead, the newlines will be expanded.