Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Sort

# Hello World program in Python
from data import DataNode
from stack import Stack
import sort
import math

def reverse_string(ostr):
    st = Stack()
    rstr = ""
    for i in range(0,len(ostr)):
        st.push(ostr[i])
    while not(st.isempty()):
        rstr += st.pop()
    return rstr
    
def bubble_sort(usorted):
    i=0
    n=len(usorted)-1
    ctr=0
    swapped = False
    while n > 0 :
        for i in range(0,n):
            j = i +1 
            ctr += 1
            if usorted[i] > usorted[j]:
                temp = usorted[i]
                usorted[i] = usorted[j]
                usorted[j] = temp
                swapped=True
        if not swapped:
            break
        n -= 1
    print("total inner loop count "+ str(ctr))
    print("sorted data "+ str(usorted))
    return usorted

#def is_sorted

def binary_search(x,srcstr):
    print("=============Starting Binary Search =====================")
    sortedstr = bubble_sort(srcstr)
    print("Sorted data "+str(sortedstr))
    low = 0
    high = len(sortedstr)-1
    ctr=mid=0
    while low <= high:
        ctr+=1
        print("low %d mid %d high %d" % (low,mid, high))
        mid = (low + high)//2
        print(" mid "+str(mid))
        
        if sortedstr[mid]==x:
            return str(x)+" is found at index "+str(mid)+".Total loops "+str(ctr)
        elif sortedstr[mid] < x:
            low = mid + 1
        else:
            high = mid - 1
    return str(x)+" is not present in search string.Total loops "+str(ctr)
        
def interpolation_search(x,srcstr):
    print("=============Starting interpolation Search =====================")
    sortedstr = bubble_sort(srcstr)
    print("Sorted data "+str(sortedstr))
    low = 0
    high = len(sortedstr)-1
    ctr = mid = 0
    while low < high:
        ctr +=1
        print("low %d mid %d high %d" % (low,mid, high))
        mid = min(math.ceil(low + ((high-low)/(srcstr[high]-srcstr[low]))*(x-srcstr[low])),high)
        print("mid %d str %d" % (mid, sortedstr[mid]))
        if sortedstr[mid]==x:
            return str(x)+" is found at index "+str(mid)+". Total loops "+str(ctr)
        elif sortedstr[mid] < x:
            low = mid + 1
        else:
            high = mid - 1
   
    
    return str(x)+" is not present in search string. Total loops "+str(ctr)
    
    

#dn1 = DataNode(5)
#dn2 = DataNode(6)
#dn1.set_next(dn2)
#print(dn1.data)
#print(dn1.next.data)
#--reverse using stack
#ostr = "Reverse"
#print(reverse_string(ostr))
#---sort
#usorted=[0,3,7,-5,8,1,-3,100]
usorted=[100, 8 ,7 ,-5, 3, 1, -3]
print('before sort ' )
print (usorted)

s = sort.Sort(usorted)
#---bubble sort
#bubble_sort(usorted)
sortd = s.merge_sort_loop(usorted)

print('Merge sort done in %d loops.. Sorted Array '% (s.get_counter())  )
print (sortd)
#x=-5
#print(binary_search(x,usorted))
#print(interpolation_search(x,usorted))

test

# Hello World program in Python
    
print ("Hello World!");

Execute Python-3 Online

name = "Spider man"
age = 18
weight = 50.9
height = 185
#coding here

Attack_of_the_Radioactive_Thing-Chemical_Step

#!/usr/bin/env python3
# coding: utf-8


def compute_value(item):
    left_value = get_single_digit("\n{} gauche".format(item))
    upper_value = get_single_digit("{} haut".format(item))
    return left_value + upper_value


def get_single_digit(prompt):
    while True:
        try:
            answer = input("{}:> ".format(prompt))
            answer = int(answer)
            assert 0 < answer < 10
        except ValueError:
            print("\n Erreur '{}' n'est pas un chiffre\n".format(answer))
        except AssertionError:
            print("\n Le chiffre doit etre compris entre 1 et 9 inclues\n")
        else:
            return answer


def get_positive_number(prompt):
    print()
    while True:
        try:
            answer = input("{}:> ".format(prompt))
            answer = int(answer)
            assert answer > 0
        except ValueError:
            print("\n Erreur '{}' n'est pas un nombre\n".format(answer))
        except AssertionError:
            print("\n Le nombre doit etre superieur a 0\n")
        else:
            return answer


def get_option(options, title):
    print("\n", title, "\n")
    print(*["{0:4}. {1}".format(i, c) for i, c in enumerate(options)], sep="\n")
    print()

    while True:
        try:
            answer = input(">>> ")
            answer = int(answer)
            assert -1 < answer < len(options)
        except (AssertionError, ValueError):
            print("\n Erreur '{}' ne fait pas partie des options disponible\n"
                  .format(answer))
        else:
            return answer


def show_useless():
    useless_values = [
        [2, "Acide mixte"],
        [0, "Colorant alimentaire"],
        [0, "Glycerol"],
        [1, "Graisse"],
        [0, "Javellisant"],
        [0, "Lait en poudre"],
        [0, "Nettoyant de piscine"],
        [0, "Sac de glace"],
        [0, "Sel de table"],
        [1, "Solution de glycerol nitre"],
    ]

    prefixs = ["Le ", "La ", "L'", "Les "]

    print("\nLes valeurs suivant sont inutiles\n",
          *["\n - {0}{1}".format(prefixs[p], v) for (p, v) in useless_values])


def main():

    def set_all_values():
        for i, (var, name, getter) in enumerate(values):
            print("\n{0} valeur(s) sur {1}".format(i + 1, len(values)), end="")
            # something really shady is going on here :P
            globals()[var] = getter(name)

    def set_some_values():
        def options():
            options_some = ["{0} = {1}".format(n, globals()[v])
                            for (v, n, _) in values]
            options_some[-1] += "\n"
            return options_some + ["Retourner au menu principal"]

        title_some = "\nChoisissez un valeur a modifie"

        while True:
            result = get_option(options(), title_some)
            if result == len(values):
                return
            else:
                # hooohooo black magic :)
                var, name, getter = values[result]
                globals()[var] = getter(name)

    title = "Choisissez le produit que vous voulez obtenir"
    options = [
        "Modifie les valeurs",
        "Affiches les valeurs inutiles",
        "Quitter\n",
        "3,4-di-nitroxy-methyl-propane",
        "Octa-hydro-2,5-nitro-3,4,7-para-zokine",
        "1,3,5 tera-nitra-phenol",
        "3-methyl-2,4-di-nitrobenzene",
    ]

    title_set = "Choisissez le mode de modification"
    options_set = [
        "Modifie tout les valeurs",
        "Modifie certaines valeurs",
    ]

    values = [
        # [variable name, item name, getter function]
        ["phi", "Phi", get_positive_number],
        ["carburant", "Carburant", compute_value],
        ["insectifuge", "Insectifuge", compute_value],
        ["vodka", "Vodka", compute_value],
        ["bicabonate", "Bicarbonate de soude", compute_value],
        ["detergent", "Detergent", compute_value],
        ["deboucheur", "Deboucheur", compute_value],
        ["pieces", "Pieces", compute_value],
        ["nettoyant_vitres", "Nettoyant pour vitres", compute_value],
        ["dissolvant", "Dissolvant", compute_value],
        ["piecette", "Piecettes", compute_value],
        ["hexamine", "Hexamine", compute_value],
        ["acide_pheno", "Acide Phenolsulfonique", compute_value],
        ["phenol", "Phenol", compute_value],
        ["aldehyde_pateux", "Aldehhyde pateux", compute_value],
        ["formaldehyde", "Formaldehyde", compute_value],
        ["dinitro", "Dinitro", compute_value],
        ["huile", "Huile de moteur", compute_value],
        ["nettoyant_roues", "Nettoyant pour roues", compute_value],
        ["engrais", "Engrais", compute_value],
        ["peinture", "Peinture", compute_value],
        ["vinaigre", "Vinaigre", compute_value],
        ["acetaldehyde", "Acetaldehyde", compute_value],
        ["methyly", "Methylybenzene", compute_value],
    ]

    # initialize all variables to zero
    for (var, _, _) in values:
        globals()[var] = 0

    show_useless()
    print("\nVeuillez entre les valeurs necessaires")
    set_all_values()

    while True:
        answer = get_option(options, title)

        if answer == 0:
            answer_set = get_option(options_set, title_set)
            if answer_set == 0:
                set_all_values()
            elif answer_set == 1:
                set_some_values()
        elif answer == 1:
            show_useless()
        elif answer == 2:
            exit()
        elif answer == 3:
            print("\n"
                  "Pieces + Carburant = Formaldehyde ({})"
                  .format(pieces + carburant - phi),

                  "Piecettes + Vodka = Acetaldehyde ({})"
                  .format(piecette + vodka - phi),

                  "Acetaldehydes + Formaldehyde + Detergent = Aldehyde pateux ({})"
                  .format(acetaldehyde + formaldehyde + detergent - phi),

                  "Aldehyde pateux + Dissolvant = 3,4-di-nitroxy-methyl-propane({})"
                  .format(aldehyde_pateux + dissolvant - phi),
                  "", sep="\n")
        elif answer == 4:
            print("\n"
                  "Pieces + Carburant = Formaldehyde ({})"
                  .format(pieces + carburant - phi),

                  "Nettoyant pour vitres + Formaldehyde = Hexamine ({})"
                  .format(nettoyant_vitres + formaldehyde - phi),

                  "Vinaigre + Engrais + Detergent + Hexamine = "
                  "Octa-hydro-2,5-nitro-3,4,7-para-zokine ({})\n"
                  .format(vinaigre + engrais + detergent + hexamine - phi),
                  "", sep="\n")
        elif answer == 5:
            print("\n"
                  "Huile de moteur + Nettoyant pour roues + Insectifuge = Phenol ({})"
                  .format(huile + nettoyant_roues + insectifuge - phi),

                  "Phenol + Deboucheur = Acide Phenolsulfonique ({})"
                  .format(phenol + deboucheur - phi),

                  "Acide Phenolsulfonique + Detergent = 1,3,5 tera-nitra-phenol ({})"
                  .format(acide_pheno + detergent - phi),
                  "", sep="\n")
        elif answer == 6:
            print("\n"
                  "Peinture + Detergent + Deboucheur = Methylybenzene ({})"
                  .format(peinture + detergent + deboucheur - phi),

                  "Methylybenzene + Bicarbonate de soude + "
                  "Vinaigre + Detergent = Dinitro ({})"
                  .format(methyly + bicabonate + vinaigre + detergent - phi),

                  "Dinitro + Carburant = 3-methyl-2,4-di-nitrobenzene ({})"
                  .format(dinitro + carburant - phi),
                  "", sep="\n")


if __name__ == '__main__':
    main()

ingdanielperez_python_iterador

list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print(next(it))
print(next(it))
print(next(it))
it = next(it)
print(it)
try:
	it = next(it)
	print(it)
except Exception as e:
	pass

it = (x for x in range(10))
for i in it:
	print(i, end=" ")
print(sum(it))
print(iter(range(1,10)))


ingdanielperez_if_else_python

n = 95
s = None
if 90 <= n <= 100:
    s = "A"
elif 80 <= n < 90:
    s = "B"
elif 70 <= n < 80:
    s = "C"
elif 60 <= n < 70:
    s = "D"
else:
    s = "F"
print("Nota: {0} {1}".format(s, n))

if n>=60:
    print("Aprobado")
else:
    print("Desaprobado")

print( "Aprobado" if n >= 60 else "Desaprobado" )

Execute Python-3 Online

n = 95
s = None
if 90 <= n <= 100:
    s = "A"
elif 80 <= n < 90:
    s = "B"
elif 70 <= n < 80:
    s = "C"
elif 60 <= n < 70:
    s = "D"
else:
    s = "F"
print("Nota: {0} {1}".format(s, n))

if n>=60:
    print("Aprobado")
else:
    print("Desaprobado")

print( "Aprobado" if n >= 60 else "Desaprobado" )

gesällprov 2 uppgift 8 andreas

def int2b(n,b):     # Convert n to base b
    token="0123456789abcdef"
    if b > 16 :
        return False
    kvot = rest = n_b = ""
    FMT = " {{:>{}}}".format(len(str(n)))
    OUT = "{} = ".format(n)
    while n :
        if n < b:
            FMT = "{}"
        kvot = FMT.format(str(n)) + kvot
        n,r = divmod(n,b)
        rest = FMT.format(token[r]) + rest
        n_b = token[r] + n_b
    OUT += "({})_{}:\n{}\n{}".format(n_b,b, kvot,rest)
    print(OUT)
    return
# --
int2b(9874398734,16)

Execute Python-3 Online

def get_input():
    command = input(": ").split()
    verb_word = command[0]
    if verb_word in verb_dict:
        verb = verb_dict[verb_word]
    else:
        print("Unknown verb {}". format(verb_word))
        return
    
    if len(command)>=2:
        noun_word = command[1]
        print

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.