hackerrank python 3 string operation, resume function for 8 different strings - python

There are 6 test cases and 5 are getting passed based on python 3 on a string operations problem, but 1 test case is failing since inception.
Pls help me out. The question is as follows:
8 Strings are given in a function.
Remove spaces from both end of strings: first, second, parent, city
Capitalize : first, second, parent
Print Strings with a space : first, second, parent, city
Check if string : 'phone' only contains digits
Check if phone number starts with value in string 'start' and print the result(True or False)
Print : total no. of times 'strfind' appears in the strings : first, second, parent, city
Print : list generated by using split function on 'string1'
Find position of 'strfind' in 'city'
My Code is as follows: Let me know what wrong I have done. 5/6 test cases are passed only 1 test case failed for unknown reason. :(
def resume(first, second, parent, city, phone, start, strfind, string1):
first = first.strip()
second = second.strip()
parent = parent.strip()
city = city.strip()
first = first.capitalize()
second = second.capitalize()
parent = parent.capitalize()
print(first + " " + second + " " + parent + " " +city)
print(phone.isdigit())
print(phone[0]==start[0])
res = first + second + parent + city
res_count = res.count(strfind)
print(res_count)
print(string1.split())
print(city.find(strfind))

Not too sure without being given details on the test case. However, number 5 may be incorrect as you are only checking if the first values of the strings are the same. This is not the same as checking if "phone number starts with value in string 'start'". I recommend using the following code instead:
print(phone.startswith(start))
In addition number 6 seems like it could cause some mismatches with overlapping strings. Instead I would suggest using:
print(first.count(strfind) + second.count(strfind) + parent.count(strfind) + city.count(strfind))

first = first.strip()
second = second.strip()
parent = parent.strip()
city = city.strip()
first = first.capitalize()
second = second.capitalize()
parent = parent.capitalize()
print(first + " " + second + " " + parent + " " +city)
print(phone.isnumeric())
print(phone.startswith(start))
res = first + second + parent + city
res_count = res.count(strfind)
print(res_count)
print(string1.split())
print(city.find(strfind))

Related

Hi, I'm trying to connect two nodes from different classes and for some reason it's giving me this error ->neo4j.exceptions.CypherSyntaxError: {code:

'''
This is the function that connects 2 nodes from different classes, the nodes exist
'''
def Lives_inRelationship(name,num):
session = graphdb.session()
session.run("MATCH (" + name + ":person {name:'" + name + "'}), ("+num+":Apartment {number:'" + num + "'})"
"MERGE (" + name + ")-[:Lives_in]->(" + num + ")")
Lives_inRelationship("Chandler","19")
'''the exception'''
neo4j.exceptions.CypherSyntaxError: {code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input '19': expected "(", "allShortestPaths" or "shortestPath" (line 1, column 45 (offset: 44))
"MATCH (Chandler:person {name:'Chandler'}), (19:Apartment {number:'19'})MERGE (Chandler)-[:Lives_in]->(19)"
^}
Probably the ‘19’ identifier. try to insert an underscore. So ‘_19’ in the MATCH and the MERGE for the rel.
All the label names, relationship names, alias names should not start with number. In your query, we see for Apartment label alias name given as 19. So, it is giving error. Please see below reference for information on naming conventions
https://neo4j.com/docs/developer-manual/current/cypher/syntax/naming/

How to overcome a ValueError when working with multiple if conditions?

I'm trying to make a script that can identify if a folder name is a project or not. To do this I want to use multiple if conditions. But I struggle with the resulting ValueError that comes from checking, for example, the first letter of a folder name and if it is a Number. If it's a String i want to skip the folder and make it check the next one. Thank you all in advance for your help.
Cheers, Benn
I tried While and except ValueError: but haven't been successful with it.
# Correct name to a project "YYMM_ProjectName" = "1908_Sample_Project"
projectnames = ['190511_Waldfee', 'Mountain_Shooting_Test', '1806_Coffe_Prime_Now', '180410_Fotos', '191110', '1901_Rollercoaster_Vision_Ride', 'Musicvideo_LA', '1_Project_Win', '19_Wrong_Project', '1903_di_2', '1907_DL_2', '3401_CAR_Wagon']
# Check conditions
for projectname in projectnames:
if int(str(projectname[0])) < 3 and int(projectname[1]) > 5 and ((int(projectname[2]) * 10) + int(projectname[3])) <= 12 and str(projectname[4]) == "_" and projectname[5].isupper():
print('Real Project')
print('%s is a real Project' % projectname)
# print("Skipped Folders")
ValueError: invalid literal for int() with base 10: 'E'
From what I understand from all the ifs...you may actually be better off using a regex match. You're parsing through each character, and expecting each individual one to be within a very limited character range.
I haven't tested this pattern string, so it may be incorrect or need to be tweaked for your needs.
import re
projectnames = ['1911_Waldfee', "1908_Project_Test", "1912_WinterProject", "1702_Stockfootage", "1805_Branded_Content"]
p = ''.join(["^", # Start of string being matched
"[0-2]", # First character a number 0 through 2 (less than 3)
"[6-9]", # Second character a number 6 through 9 (single digit greater than 5)
"(0(?=[0-9])|1(?=[0-2]))", # (lookahead) A 0 followed only by any number 0 through 9 **OR** A 1 followed only by any number 0 through 2
"((?<=0)[1-9]|(?<=1)[0-2])", # (lookbehind) Match 1-9 if the preceding character was a 0, match 0-2 if the preceding was a 1
"_", # Next char is a "_"
"[A-Z]", #Next char (only) is an upper A through Z
".*$" # Match anything until end of string
])
for projectname in projectnames:
if re.match(p, projectname):
#print('Real Project')
print('%s is a real Project' % projectname)
# print("Skipped Folders")
EDIT: ========================
You can step-by-step test the pattern using the following...
projectname = "2612_UPPER"
p = "^[0-2].*$" # The first character is between 0 through 2, and anything else afterwards
if re.match(p, projectname): print(projectname)
# If you get a print, the first character match is right.
# Now do the next
p = "^[0-2][6-9].*$" # The first character is between 0 through 2, the second between 6 and 9, and anything else afterwards
if re.match(p, projectname): print(projectname)
# If you get a print, the first and second character match is right.
# continue with the third, fourth, etc.
This is something that just gets the work done and may not be the most efficient way to do this.
Given your list of projects,
projectnames = [
'190511_Waldfee',
'Mountain_Shooting_Test',
'1806_Coffe_Prime_Now',
'180410_Fotos',
'191110',
'1901_Rollercoaster_Vision_Ride',
'Musicvideo_LA',
'1_Project_Win',
'19_Wrong_Project',
'1903_di_2',
'1907_DL_2',
'3401_CAR_Wagon'
]
I see that there are a limited number of valid YYMM strings (24 of them to be more precise). So I first create a list of these 24 valid YYMMs.
nineteen = list(range(1900, 1913))
eighteen = list(range(1800, 1813))
YYMM = nineteen + eighteen # A list of all 24 valid dates
Then I modify your for loop a little bit using a try-except-else block,
for projectname in projectnames:
try:
first_4_digits = int(projectname[:4]) # Make sure the first 4 are digits.
except ValueError:
pass # Pass silently
else:
if (first_4_digits in YYMM
and projectname[4] == "_"
and projectname[5].isupper()):
# if all conditions are true
print("%s is a real project." % projectname)
One solution would be to make a quick function that catches an error and returns false:
def isInt(elem):
try:
int(elem)
return True
except ValueError:
return False
...
if all(isInt(e) for e in projectname[:3]) and int(str(projectname[0])) < 3 and ...:
...
Or you could use something like str.isdigit() as a check first, rather than writing your own function, to avoid triggering the ValueError in the first place.
Though if I were you I would reconsider why you need such a long and verbose if statement in the first place. There might be a more efficient way to implement this feature.
You could write a small parser (might be a bit over the top, admittedly):
from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor
from parsimonious.exceptions import ParseError
projectnames = ['190511_Waldfee', 'Mountain_Shooting_Test', '1806_Coffe_Prime_Now', '180410_Fotos', '191110', '1901_Rollercoaster_Vision_Ride', 'Musicvideo_LA', '1_Project_Win', '19_Wrong_Project', '1903_di_2', '1907_DL_2', '3401_CAR_Wagon']
class ProjectVisitor(NodeVisitor):
grammar = Grammar(
r"""
expr = first second third fourth fifth rest
first = ~"[0-2]"
second = ~"[6-9]"
third = ~"\d{2}"
fourth = "_"
fifth = ~"[A-Z]"
rest = ~".*"
"""
)
def generic_visit(self, node, visited_children):
return visited_children or node
def visit_third(self, node, visited_children):
x, y = int(node.text[0]), int(node.text[1])
if not (x * 10 + y) <= 12:
raise ParseError
# loop over them
pv = ProjectVisitor()
for projectname in projectnames:
try:
pv.parse(projectname)
print("Valid project name: {}".format(projectname))
except ParseError:
pass
This yields
Valid project name: 1806_Coffe_Prime_Now
Valid project name: 1901_Rollercoaster_Vision_Ride
Valid project name: 1907_DL_2

What am I doing wrong with this?

first of all, i'm very new at programming and starting my courses in college, i'm still trying to get the hang of it, please be nice. // i'm doing homework and it's this thing about calculating my age in the year of 2050, i've followed the instructions and everything and i get a syntax error in the print("I will be") line, can anyone tell me why and what am i doing wrong?
YEAR = "2050"
myCurrentAge = "18"
currentYear = "2019"
print("myCurrentAge is" + str(myCurrentAge)
myNewAge = myCurrentAge + (YEAR - currentYear)
print("I will be" + str(myNewAge) + "in YEAR.")
stop
First, as #ObsidianAge pointed out, your print("myCurrentAge is" + str(myCurrentAge) line is missing the second closing parenthesis, it should be like this print("myCurrentAge is" + str(myCurrentAge)).
Next is the error that you are talking about. You are calculating here myNewAge = myCurrentAge + (YEAR - currentYear) a bunch of string variables. You need to parse first your variables into int like this :
myNewAge = int(myCurrentAge) + (int(YEAR) - int(currentYear))
#then print,
print("I will be " + str(myNewAge) + " in YEAR" + YEAR)
To solve the confusion in the comments and I saw that you are following this answer's suggestion so here's the entire code:
# int variables
YEAR = 2050
myCurrentAge = 18
currentYear = 2019
# printing current age
print( "myCurrentAge is " + str(myCurrentAge))
# computing new age, no need to parse them to int since they already are
myNewAge = myCurrentAge + (YEAR - currentYear)
# then printing, parsing your then int vars to str to match the entire string line
print("I will be " + str(myNewAge) + " in YEAR " + str(YEAR))
Also, after you fix the bracket thing mentioned by #ObsidianAge, you will have to fix another thing.
All your variables are Strings right now since you have declared them within double-quotes. To be able to do what you intend to do, you will need to convert them to integers.
I'd recommend assigning them integer values in the very beginning by removing the quotes. With your current code, it will just concatenate all your variable strings together when you use the + operator. So your new declarations will look like this:
YEAR = 2050
myCurrentAge = 18
currentYear = 2019

Python Printing Elements from a dictionary produces error

I created this block of code for usernames which is read using a loop.
users = {
'aeinstein': {
'first':'albert',
'last':'einstein',
'location':'princeton'
},
'mcurie': {
'first':'marie',
'last':'curie',
'location':'paris',
}
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'], user_info['last']
location = user_info['location']
print("\tFull name:" + full_name.title())
print("\tLocation:" + location.title())
Now, if you observe the following line in the for loop
full_name = user_info['first'], user_info['last']
I expect1 this to append the value albert einstein and marie curie, but this produces the error
print("\tFull name:" + full_name.title())
AttributeError: 'tuple' object has no attribute 'title'
but why is my method wrong and the following therefore correct...
full_name = user_info['first'] + " " + user_info['last']
to produce the following result
Username: aeinstein
Full name:Albert Einstein
Location:Princeton
Username: mcurie
Full name:Marie Curie
Location:Paris
1From the comments: so when you do say print("hello", "world") this type of string concatenation works right but not in the example that I have shown?
The expression user_info['first'], user_info['last'] creates a tuple of two elements (in this case the elements are strings). Tuple object does not have the title method but if you concatenate with the plus operator like you do user_info['first'] + " " + user_info['last'], you create a String and not a tuple so you can use the title method
By adding the , operator in user_info['first'], user_info['last'] you are telling Python that you are giving it a tuple of two strings. By using the + operator, you are simply concatenating the two strings into one string.
full_name = user_info['first'], user_info['last']
I expect this to append the value albert einstein and marie curie […]
Your expectation is wrong.
but why is my method wrong and the following therefore correct...
full_name = user_info['first'] + " " + user_info['last']
Because + is the concatenation operator for strings, and , is not.
As replied by several others you need to use
full_name = user_info['first']+" "+ user_info['last']
OR
full_name = "%s %s" %(user_info['first'],user_info['last'])

Highlight every match with Solr 6, Python 3 and pysolr

I have this Solr index that contains a large numer of quite long text files, indexed with the text_sv schema. I want to print out every single snippet for each indexed document. However, I only retrieve a few ones, even though I have tried to smanipulate the various settings as specified in the documentation.
Here is the code section:
results = solr.search(search_string, rows = result_limit, sort = order,
**{
'hl':'true',
'hl.fragsize': 100,
'hl.fl': 'fulltext',
'hl.maxAnalyzedChars': -1,
'hl.snippets': 100,
})
resultcounter = 0
for result in results:
resultcounter += 1
fulltexturl = '<a href="http://localhost/source/\
' + result['filename'] + '">' + result['filename'][:-4] + '</a>'
year = str(result['year'])
number = str(result['number'])
highlights = results.highlighting
print("Saw {0} result(s).".format(len(results)))
print('<p>' + str(resultcounter) + '. <b>År:</b> ' + year + ', <b>Nummer\
: </b>' + number +' ,<b>Fulltext:</b> ' + fulltexturl + '. <b>\
</b> träffar.<br></p>')
inSOUresults = 1
for idnumber, h in highlights.items():
for key, value in h.items():
for v in value:
print('<p>' + str(inSOUresults) + ". " + v + "</p>")
inSOUresults += 1
What am I doing wrong?
You probably want a very large (or 0) value for the hl.fragments parameter (from the Highlighting wiki page):
With the original Highlighter, if you have a use case where you need to highlight the complete text of a field and need to highlight every instance of the search term(s) you can set hl.fragsize to a very high value (whatever it takes to include all the text for the largest value for that field), for example &hl.fragsize=50000.
However, if you want to change fragsize to a value greater than 51200 to return long document texts with highlighting, you will need to pass the same value to hl.maxAnalyzedChars parameter too. These two parameters go hand in hand and changing just the hl.fragsize would not be sufficient for highlighting in very large fields.

Categories