the python code is printing this
___
____
____
____
_
instead of this
____
____
____
____
this is the code some of it doesn't do anything because it has been commented out so just ignore the associated variables
X = 0 #majic number
L = 0 #lines
i = 0 #list intilising varble thing
x = 175 #cordinates are x and y
y = 0 #dont set x&y above 175
Del = x + 1
X = y*176
x = x+X
stuff = []
for L in range(0,7):
for i in range(0,7):
i + 1
stuff.insert(i,"_")
stuff.insert(i,"\n")
i + 1
'''stuff.pop(Del)
stuff.insert(x,"q")'''
print(*stuff, sep='')
in the current settings it supposed to print a 8*8 board. i have fiddled around with the position of the i + 1 but it didn't seem to make a difference.
if someone knows how to get in a alternating pattern that would be great.
when i did that i just got abbbbaaa. i should of mentioned this early but the end goal is to create a game of chess in the terminal.
Just use the increminting operator '+='. i + 1 means nothing in your code and wont have any effect if you removed it. It should be as follows:
for L in range(0,7):
for i in range(0,7):
i += 1
stuff.insert(i,"_")
stuff.insert(i,"\n")
for works very differently in Python than it does in, say, C.
Also, in Python, you only very rarely need to use indices, especially since using iterators is more efficient.
I think you were trying to achieve this with your example:
#!/usr/bin/env python3
x = 3
y = 2
stuff = []
for L in range(y):
for i in range(x):
stuff.append('_')
stuff.append('\n')
# the list now looks like this:
# stuff = ['_', '_', '_', '\n', '_', '_', '_', '\n']
# It contains y*x strings, each length 1.
# This is something like "char **stuff" in C.
output = ''.join(stuff) # this creates '___\n___\n'
print(output)
Note that the variables i and L are actually never used, we are just using the number of items represented by each range to iterate over.
Or if you don't care about the strings being stored in a list and just want to print the rectangle:
#!/usr/bin/env python3
x = 3
y = 2
for L in range(y):
print('_' * x) # by default, print appends '\n' to the end.
'_' * x just repeats the string '_' x times, creating another string, '___'
Related
Hi everyone I have a problem that I have difficulty resolve in Python. this the statement
Have the function ChessChallenge(str) read str which will be a string consisting of the location of a space on a standard 8x8 chess board with no pieces on the board along with another space on the chess board. The structure of str will be the following: "(x y)(a b)" where (x y) represents the position you are currently on with x and y ranging from 1 to 8 and (a b) represents some other space on the chess board with a and b also ranging from 1 to 8 where a > x and b > y. Your program should determine how many ways there are of traveling from (x y) on the board to (a b) moving only up and to the right. For example: if str is (1 1)(2 2) then your program should output 2 because there are only two possible ways to travel from space (1 1) on a chessboard to space (2 2) while making only moves up and to the right.
If you have a solution please, let me know
Okay, that is my code
def Substr(s):
arr = []
for i in s:
if i.isdigit():
arr.append(int(i))
return arr
def Steps(sourceX, sourceY, destX, destY):
SourceX = sourceX
SourceY = sourceY
DestX = destX
DestY = destY
i = 0
j = 0
while( (SourceX != DestX) or (SourceY != DestY) ):
#Go up
if(SourceX < DestX):
SourceX+=1
i+=1
#Go right
if(SourceY < DestY):
SourceY+=1
i+=1
return i+j
def ChessChallenge(strParam):
arr = Substr(strParam)
SourceX = arr[0]
SourceY = arr[1]
DestX = arr[2]
DestY = arr[3]
# code goes here
return Steps(SourceX, SourceY, DestX, DestY)
# keep this function call here
print ChessChallenge(raw_input())
input: "(2 2)(4 3)"
Output: 3
Input: "(1 1)(3 3)"
Output: 6
phrase = input("enter the equation you want diferentiated:")#3x^2+2x^1+-4x^4
new_phrase = phrase.split("+")#splits phrase at the + operator
print(len(new_phrase))
for item in new_phrase:
c = (new_phrase>new_phrase.index("^"))#actul differentiation part c is the power of whatever (this is where python has a problem) line 6
y = (new_phrase<(new_phrase.index("^")-1))# y is the number before x
print(float(c)*float(y)+"^"+float(c)-1)# this is the final differentiated answer
#however it keeps saying ^ is not in the list how can I fix this?
Using Python 3.8.1
The actual main code is starting at for item. This is where the problem occurs, as the input is supposed to be 3x^2+2x^1+-4x^4, or something like, that but Python cannot seem to find where the power to sign "^" in the list thus the rest of the code from the " c =" does not work.
I have created a working version from your code. Mainly the problem was the type inconsistency. Furthermore I have added several comments to the code for the better understanding and it contains several prints for the debugging.
Code:
phrase = input("Enter the equation you want differentiated: ").lower() # 3x^2+2x^1+-4x^4
new_phrase = phrase.split("+") # splits phrase at the + operator
print("Elements: {}".format(new_phrase)) # Print elements of differential
for item in new_phrase:
print("Tested element: {}".format(item))
c = float(item.split("^")[-1]) # Get after part of "^" character
y = float(item.split("^")[0].replace("x", "")) # Get before part of "^" character (withour "x")
print("c={} ; y={}".format(c, y))
print(
"Result: {}^{}".format(float(c) * float(y), float(c) - 1)
) # this is the final differentiated answer
Output:
>>> python3 test.py
Enter the equation you want differentiated: 3x^2+2x^1+-4x^4
Elements: ['3x^2', '2x^1', '-4x^4']
Tested element: 3x^2
c=2.0 ; y=3.0
Result: 6.0^1.0
Tested element: 2x^1
c=1.0 ; y=2.0
Result: 2.0^0.0
Tested element: -4x^4
c=4.0 ; y=-4.0
Result: -16.0^3.0
Here is some Python script that can differentiate algebraic expressions based on your code.
phrase = input("enter the equation you want diferentiated:")#3x^2+2x^1+-4x^4
# Splits phrase at the + operator
split_phrase = phrase.split("+")
# Placeholder for the differentiated phrase
new_phrase = ""
for item in split_phrase:
# Exponent - index of ^ - 1
c = int(item[item.index("^") + 1:])
#Coefficient - from 0 to index of x - 1
y = int(item[0:item.index("x")])
#Reconstructs the algebraic expression
new_phrase += str(c*y) + "x^" + str(c-1)
# Adds a plus sign if it is not the last item
if split_phrase.index(item) != len(split_phrase) - 1:
new_phrase += "+"
there is a syntax error that says that i am returning outside the function
I tried all the possible solutions that people used on the same problem with there code and i still get the same error
the error is in line 32 in the line return result
Problem Introduction
In this problem, we ask a simple question: how many times one string occurs as a substring of another? Recall that di erent occurrences of a substring can overlap with each other. For example, ATA occurs three times in CGATATATCCATAG.
Problem Description
Task. Find all occurrences of a pattern in a string.
Input Format. Strings πππ‘π‘πππ and πΊπππππ.
Constraints. 1 β€ |πππ‘π‘πππ| β€ 106; 1 β€ |πΊπππππ| β€ 106; both strings are over A, C, G, T.
Sample 1.
Input:
Output:
1 12
4 1.5 2
4 4 24
TACG GT
Explanation:
The pattern is longer than the text and hence has no occurrences in the text.
Sample 2.
Input:
Output:
02
Explanation:
The pattern appears at positions 1 and 3 (and these two occurrences overlap each other).
Sample 3.
Input:
Output:
139
Explanation:
The pattern appears at positions 1, 3, and 9 in the text.
ATA ATATA
ATAT
GATATATGCATATACTT
# python3
import sys
def compute_prefix_function(pattern):
s = [0] * len(pattern)
border = 0
for i in range(1, len(pattern)):
while (border > 0) and (pattern[i] != pattern[border]):
border = s[border - 1]
if pattern[i] == pattern[border]:
border = border + 1
else:
border = 0
s[i] = border
return s
def find_pattern(pattern, text):
S = pattern + '$' + text
s = compute_prefix_function(S)
result = []
p = len(pattern)
for i in range(p + 1, len(S)):
if s[i] == p:
result.append(i - 2 * p)
return result
if __name__ == '__main__':
pattern = sys.stdin.readline().strip()
text = sys.stdin.readline().strip()
result = find_pattern(pattern, text)
print(" ".join(map(str, result)))
Realize that white space/indentation matters in python, and replaces the { }, used in most other language to define a scope. Something like this is a proper function (although, the return isn't really necessary):
def foo():
print("bar")
return
Doing this instead would result in an error message similar to your, though, because the return now is outside the scope of the function:
def foo():
print("bar")
return
For more info just Google for python indentation tutorial.
The question was: Return a sentence with the words reversed
>>> master_yoda('I am home')
'home am I'
It will eventually reverse the words of the line.
I am learning and performing Python in Jupyter Notebook.
def master_yoda(string):
l = string.split()``
p = len(string) - 1
final = ''
while p<0:
final = final + ' ' + s[p]
p = p-1
print (final)
master_yoda('Hello my name is Aryan')
The output is nothing..
No syntax errors , but still no output ...
Perhaps you should try this.
def master_yoda(string):
reversed_list = string.split(' ')
reversed_list.reverse()
reversed_string = ' '.join(reversed_list)
print(reversed_string)
master_yoda("i am home")
The big problem with the code is that you were testing for p < 0 but since p starts off with a positive value, the code never enters the while loop. You should really have been testing for p >= 0. The following code should do what you want, they way you seem to want it to:
def master_yoda(string):
l = string.split()
p = len(l) - 1
final = l[p]
p -= 1
while p >= 0:
final += ' ' + l[p]
p -= 1
return final
Note that this implementation fails if an empty string is passed as input. I tried to keep the code in the spirit of your own code and checking for an empty string would make it more complex. The simplest and most robust solution would be:
def master_yoda(string):
return ' '.join(reversed(string.split()))
I am beginning to learn python and want to cut a string at the spaces; so 'hello world' becomes 'hello' and 'world'. To do this i want to save the locations of the spaces in a list, but i can't figure out how to do this. In order to find the spaces i do this:
def string_splitting(text):
i = 0
for i in range(len(text)):
if (text[i]==' '):
After saving them in the list i want to display them with text[:list[1]] (or something like that)
Can anyone help me with the saving it in a list part; and is this even possible?
(Another way to cut the string is welcome to :-) )
Thanks.
Use split:
"hello world my name is".split(' ')
It will give you a list of strings
thanks, i tried to do it without the split option, should have said that in the question..
anyways this worked;
def split_stringj(text):
a = text.count(' ')
p = len(text)
l = [-1]
x = 0
y = 1
for x in range(p):
if (text[x]==' '):
l.append(x)
y += 1
l.append(p)
print l
for x in range(len(l)-1):
print text[l[x]+1:l[x+1]]