Finding a substring within a string without using any built in functions - python-2.7

I have to find a particular substring within a string and its position within the string. This is very easy but I have to this without using any built in functions or methods in python. I would really appreciate it if someone could help. Thanks
string="ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGGAAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCCCTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAGTTTAATTACAGACCTGAA"
substring='ttg'

This code will work if you don't want to use any inbuilt function.
man = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCC$
check = "TTG"
for i in range (0, len(man)):
if man[i]==check[0]:
sum =0
for j in range(0, len(check)):
if man[i+j] != check[j]:
break
sum = 0
else:
sum = sum +1
if sum == len(check):
print i

It is hard to implement this without any builtin, as you need either len or enumerate to iterate with knowledge of the current index.
Although, here is an implementation with len only.
def find(s, sub):
idx = 0
while idx < len(s):
if s[i:len(sub)] == sub:
return idx
return -1
If you really want no builtin at all, here is a trick you could use.
def find(s, sub):
sub_len = 0
for _ in sub:
sub_len += 1
idx = 0
while s[idx:idx+1]:
if s[i:sub_len] == sub:
return idx
return -1
Of course this is somewhat cheating since iteration and slicing does more for you than many builtins.

if you only want substring from your string you can use this:
str[12:15]
another examples:
a = '1234567890'
then
>>> a[-3:-1]
'89'
>>> a[-3:]
'890'
>>> a[-2]
'9'
>>> a[5]
'6'

Related

Replace items in list if condition

I need to replace temperature values in list depends on negative/positive and get rid of float at the same time. I.e. value '-0.81' should be '-1' (round) or '0.88' should be '1'.
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in range (len(myList)):
if myList[i][0] == '-' and int(myList[i][-2]) > 5:
do sth...
At the end I need new list with new values. Thank you for any tips.
Your code is already almost there. It's not necessary to reference the elements by index.
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in myList:
if i[0] == '-' and int(i[-2]) > 5:
do sth...
If all you want to do is rounding then you can use a list comprehension.
roundlist = [round(float(i)) for i in myList]
You could parse the string into number, check for rounding (whether the decimal is higher or lower than 0.5), and convert it back to string
import math
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
result = [0] * len(myList)
for i in range (len(myList)):
num = float(myList[i])
if num - math.floor(num) < 0.5:
result[i] = str(math.floor(num)) # round down
else:
result[i] = str(math.ceil(num)) # round up
print(result)

Convert from decimal to binary - python

I'm having an issue with this piece of code I wrote. I'm trying to convert an integer input and print an output with its equivalent in binary base. For example for 5 it should drop an output of '101' however it just prints '10' like if it doesn't take into account the last digit. Please any comments would be greatly appreciated
T = raw_input()
for i in range(0, int(T)):
n = raw_input()
dec_num = int(n)
cnv_bin = ''
while dec_num//2 > 0:
if dec_num%2 == 0:
cnv_bin += '0'
else:
cnv_bin += '1'
dec_num = dec_num//2
print cnv_bin[::-1]
while dec_num//2 > 0:
should be:
while dec_num > 0:
The first time through the loop, 5//2==2, so it continues.
The second time through the loop, 2//2==1, so it continues.
The third time, 1//2==0 and the loop quits without handling the last bit.
Also, you can just do the following to display a number in binary:
print format(dec_num,'b')
Format string version:
print '{0} decimal is {0:b} binary.'.format(5)
Why not use the build-in function bin()?
eg:
bin(5)
output
0b101
If you don't want the prefix(0b), you can exclude it.
bin(5)[2:]
hope to be helpful!
import math
def roundup(n):
return math.ceil(n)
D = eval(input("Enter The Decimal Value: "))
n = roundup(math.log2(D+1))-1
bi = 0
di = D
qi = 0
i = n
print("Binary Value:",end = " ")
while(i>=0):
qi = math.trunc(di/2**i)
bi = qi
print(bi,end = "")
di = di - bi*(2**i)
i = i-1

Split Array with looping on Python 2.7.5.1

def split(self):
assert input_array >= 0
if input_array == 0:
return [0]
array=[]
while input_array> 0:
array.append(int(input_array%10))
input_array = input_array//10
print input_array
return input_array
else:
print "END"
is there any way to split input array with looping?
i tried using selection but it just doesn't work
Are you trying to get the individual digits from a number? Try converting it into a string, iterating over it, and converting back to int.
>>> x = 2342
>>> [int(digit) for digit in str(x)]
[2, 3, 4, 2]
I'm guessing what you want is a list of digits conforming a certain number (input_array in this case).
First the main issues.
You declare a variable called array and if you are a good observer
you will notice you never return it.
print "END" has no purpose here.
input_arry == 0 can be treated as any other number > 0.
Try to not modify input_array
The solution:
Since I see you're working with a class I will code a solution for you using a class as well.
class SomeClass:
def __init__(self, input_array):
""" Constructor """
self.input_array = input_array
def split(self):
array = []
number = self.input_array # Don't modify input_array.
while number > 0:
array.append(number%10)
number = number // 10
array.reverse() # This is easy ;)
return array
def split_1(self):
""" Kevin's solution. When you become more skilled this is the way to go. """
return [int(digit) for digit in str(x)]
>>> some_instance = SomeClass(12345)
>>> print(some_instance.split())
[1, 2, 3, 4, 5]

How to check if a number comes before another in a List

How can I go about checking if an element comes before another in a list?
For example:
how can I check if 5 comes before 12 in a list:
li = [1,2,3,7,4,5,10,8,9,12,11]
Is there an built-in Python function that can allow me to do that?
Here ya go:
>>> li = [1,2,3,7,4,5,10,8,9,12,11]
>>> li.index(5) > li.index(12) # 5 comes after 12
False
>>> li.index(5) < li.index(12) # 5 comes before 12
True
>>>
>>> help(list.index)
Help on method_descriptor:
index(...)
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
>>>
if li.index(5) < li.index(12):
print "came before"
You can use list's inbuilt index function:
>>> l = [1,2,3,7,3,5,21,8,44,16,12]
>>> l.index(5) > l.index(12)
False
>>> l.index(5) < l.index(12)
True
>>>
index returns the index of the first occurrence of a number. An example of how index works:
>>> t = (0,1,2,3,4,0,1,2)
>>> t.index(3)
3
>>> t.index(0)
0
Note that there are two 0s here.
I don't know python, but generally arrays and lists in programming languages use a zero-based index to identify each element. You usually can access each element via their index in the using the format li[index] = element. For example:
let li = [1,2,3,7,4,5,10,8,9,12,11]
li[0] = 1;
li[1] = 2;
li[2] = 3;
li[3] = 7;
li[4] = 4;
etc. Many systems will also have an IndexOf() method that will allow you to determine the index of an element using a format similar to li.IndexOf(element). This feature can be used in your example such as:
Boolean Is_5_B4_12 = li.IndexOf(5) < li.IndexOf(12);
If python does not have such a feature, you can easily create one yourself by using a loop and an incrementor. Something similar to this would work:
Function IndexOf(integer element)
integer index = 0;
Do While index < len(li) //len() is a function that specifies the number of elements in the list
if li[index] == element then return index;
index = index + 1;
Loop
End Function
I hope this answers your question! Regards - yisrael lax

something wrong with my password generator

I made a password generator - I'm only 16 so it's probably not the best- and it outputs 8 0 and ones like 01100101 and then enderneath that it outputs the password. Well when there is a "10" in the password like FG4v10Y6 it will add another character so instead of it being FG4v10Y6 it would be FG4v10Y6M so it has nine or more characters depending on how many "10" are in it.
I'm not sure why it's doing this please help. THanx!
import pygame
import random
pygame.init()
#letters
reg = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
CAP = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
final_pass = []
num_let_list = []
new_list = []
i = 0
file = open("password_test","w")
def num_list_gen(num_list):
for i in range(8):
num_let_list.append(random.randint(0,1))
i += 1
for each in num_let_list:
each = str(each)
new_list.append(each)
print ''.join(new_list)
def CAP_reg_num(final_pass,num_let_list,CAP,reg):
for each in num_let_list:
if each == 0:
cap_reg = random.randint(0,1)
if cap_reg == 0:
let1 = random.randint(0,25)
final_pass.append(reg[let1])
if cap_reg == 1:
let1 = random.randint(0,25)
final_pass.append(CAP[let1])
if each == 1:
num1 = random.randint(0,10)
num1 = str(num1)
final_pass.append(num1)
def main(CAP,reg,num_let_list,final_pass):
num_list_gen(num_let_list)
CAP_reg_num(final_pass,num_let_list,CAP,reg)
print ''.join(final_pass)
file.write(''.join(final_pass))
file.close
main(CAP,reg,num_let_list,final_pass)
why did the code come out all weird on the post in some places and how do you fix it?
Your password generator is flipping a coin to choose between adding a letter or a number. When it chooses to add a number, you choose the number to add with:
num1 = random.randint(0,10)
However, this doesn't return a single digit number. It returns one of 11 possible values: the numbers between 0 and 10 inclusive. So one time in 11, it will add the number 10 to the string, which is, of course, two digits.
You want:
num1 = random.randint(0,9)
instead to add a single digit.