text
stringlengths
37
1.41M
# The following code allowed us to locate and create files. import csv import os # The following code allowed us to locate the employee_data.csv excel file. csvpath = os.path.join("/Users/azpunit/Desktop/Extra-Python-Challenge/PyBoss/employee_data.csv") # The follwing code allowed us to store all the lists that are...
#main.py # Import the Flask module that has been installed. from flask import Flask, jsonify # Creating a "books" JSON / dict to emulate data coming from a database. books = [ { "id": 1, "title": "Harry Potter and the Goblet of Fire", "author": "J.K. Rowling", "isbn": "1512379298" }, { "id": 2, "title"...
num = float(input("Input float number: ")) print("'10' - {0:.2f} | 'e' - {0:e}".format(num))
import os import biblioteca_velha def main (): #the principle one, it calls all functions os.system ("clear") define = nome() define = xo(define) matriz = mtz () jogo(define, matriz) novo_jogo() def nome (): # this function recieve the names of players, allocate it, prints and return theses n...
class DropletDoesNotExistsError(Exception): """Raised when a non defined droplet is modified""" def __init__(self, name: str) -> None: """ :param name: name of the droplet :type name: str :returns: nothing :rtype: None """ self.name = name self.m...
class Car: _speed: int _color: str _is_police: bool def __init__(self, color, speed, is_police): self._color = color self._speed = speed self._is_police = is_police def go(self): print("Машина поехала") def stop(self): print("Машина остановилась") ...
from itertools import count from itertools import cycle def iter_count(start=3, end=10): arr_ = [] for i in count(start): if i == end: return arr_ arr_.append(i) arr = iter_count() print(arr) def iter_cycle(arr_, times=10): i = 0 for x in cycle(arr_): print(x) ...
x = 2 y = -2 def my_func(x, y): return x ** y print(my_func(x, y)) def my__func(x, y): temp = 1 for i in range(y, 0): temp = temp/x print(temp) my__func(x, y)
import pygame import pyttsx3 # pip install pyttsx3 # sudo apt install libespeak1 from time import sleep class Audio(object): """ The class used to process and play audio files in the game. Attributes: volume_to_distance -> list object with floats from 0 to 1 indicating volume to play a sound a...
import pygame import os import textrect class VisualView(): """ The class used to display the game on to a screen. Attributes: map -> GameMap object with all required objects to play the game width -> width of the screen in pixels height -> height of the screen in pixels img_size -> size t...
import random print("***************WELCOME TO CHATBOT GAME****************") def chatterbot(sentense): ques=input("Say Something Here=") a=ques.lower() # print(a) for word in sentense: # print(word) # break if word == a: print(random.choice(response[word])) a...
from tkinter import* import random tk=Tk() canvas=Canvas(tk,width=500,height=500) canvas.pack() def rectangle(width,height,fill_color): x1=random.randrange(width) x2=x1+random.randrange(width) y1=random.randrange(height) y2=y1+random.randrange(height) canvas.create_rectangle(x1,x2,y1,y2,fill=fill_color...
Numbers = 100 primes = [2] isprime = True for x in range(3,100): for d in primes: if x % d == 0: isprime = False if isprime: primes.append(x) print(x) isprime = True
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created Date: March 25. 2021 Author: Dae Jong Jin Description: Rename all files in the directory @example python3 change_filename.py --change $(directory path) --name $(desired_file_name) --type $(file_type) python3 change_filename.py --change test_dir --name file_nam...
def main(): inp=input() count2=0 count1=0 for each in inp: if(each == '('): count1+=1 elif(each==')'): count2+=1 if(count1<count2): return count1 else: return count2 print(main())
def main(): arr=[1,2,3,4] k=2 pointer=k-1 while(pointer>0): temp=arr[pointer] arr[pointer]=arr[pointer-1] arr[pointer-1]=temp pointer=pointer-1 print(arr) main()
from collections import Counter import numpy as np def generate_user_tweets_dict(names,tweets): '''generate dictionary tweets dictionary, where user is key and number of tweets as value ''' tweets_dict = {} tweets = Counter(tweets) for name in names: tweets_dict[name] = tweets[name] retur...
#to find sum of 3 numbers and return zero if two numbers are equal n1=int(input("Enter the value of 1st number")) n2=int(input("Enter the value of 2nd number")) n3=int(input("Enter the value of 3rd number")) s=n1+n2+n3 if n1==n2 or n2==n3 or n1==n3: print("0") else: print(s)
#!/usr/bin/python3 def weight_average(my_list=[]): if not my_list: return 0 return sum(x[0] * x[1] for x in my_list) / sum(x[1] for x in my_list)
#!/usr/bin/python3 """square """ from models.rectangle import Rectangle class Square(Rectangle): """Inherits from Rectangle """ def __init__(self, size, x=0, y=0, id=None): super().__init__(width=size, height=size, x=x, y=y, id=id) @property def size(self): return self.width ...
#!/usr/bin/python3 def add_integer(a, b=98): if not isinstance(a,(int, float)): raise TypeError("a must be an integer") if not isinstance(b,(int, float)): raise TypeError("b must be an integer") return int(a) + int(b)
#!/usr/bin/python3 """Student """ class Student: """Contains student data """ def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """Retrieves dictionary of Student with ...
''' 集合 collections是Python内建的一个集合模块,提供了许多有用的集合类。 namedtuple 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: ''' p = (1, 2) ''' 但是,看到(1, 2),很难看出这个tuple是用来表示一个坐标的。 定义一个class又小题大做了,这时,namedtuple就派上了用场: ''' from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p.x) ''...
''' 匿名函数 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。 在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数: ''' l = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) print(l) # [1, 4, 9, 16, 25, 36, 49, 64, 81] ''' 通过对比可以看出,匿名函数lambda x: x * x实际上就是 def f(x): return x * x '...
''' 调用函数 Python内置了很多有用的函数,我们可以直接调用。 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数。可以直接从Python的官方网站查看文档: 函数大全:http://docs.python.org/3/library/functions.html 基础函数:abs max 数据类型转换:int('str') float('str') str(number) bool(1) bool('') ''' # tips:也可以在交互式命令行通过help(abs)查看abs函数的帮助信息。 help(abs) # abs(...) # ...
''' 排序算法 排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。 如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来。 ''' print(sorted([36, -5, 1, 22])) # [-5, 1, 22, 36] ''' 此外,sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序: ''' print(sorted([36, -5, 1, 22], key=abs)) # [1, -5, 22, 36] ''' 默认...
N, M = map(int, input().split()) chess = [] for i in range(N): chess.append([]) for j in range(M): chess[i].append(0) for i in range(N): a = input() for j in range(M): chess[i][j] = a[j] for i in range(N): for j in range(M): print(chess[i][j], end = " ") ...
from enum import Enum class Shipper(Enum): #For python 3.4 and up, class Enum can be used fedex = 1 ups = 2 postal = 3
change = eval(input("Enter the change")) print("quarters :", change//.25) change-=(change//.25)*.25 print("dimes :", change//.10) change-=(change//.10)*.10 print("nickels :",change//.05) change-=(change//.05)*.05 print("pennies :",1+(change//.01)) change-=(change//.01)*.01
# hey dany. i hope this helps #^^^ also you can use this as the string it asks you for # or this one : # 1234567890 # so you can understand what happens to the order much better #strings string = input("Enter your string has to contain a so it doesnt give error: ") print(string.capitalize()) print("") print(string...
import random x= input("give me a number") y = random.randint(1, 10) print(x//y, x%y)
x = int(input("Enter the meal price in AED: ")) y = int(input("Enter the tip you want to leave : ")) print("Total (tip unincluded) : " + str(x) + "\nTip : " + str(y) + "%" + "\nTotal (tip included) : " + str(x+x*(y/100)) + "AED")
from random import randrange from random import random import time import threading print(" ") print(" ") #rounding for 2 decimal points# def myMethod(n): return int(n * 100) / 100 #*****************************# #Making the two Arrays that will hold our values# #MOVES will hold our possible scramble Moves# Mov...
import random wins = 0 draws = 0 choices = ["rock", "Paper", "Siscors"] for i in range(5): player_choice = input("r/p/s") if player_choice == "r": player = 1 elif player_choice == "p": player = 2 elif player_choice == "s": player = 3 computer = random.randint(1, 3) if pla...
while True: print("F(x) = a(x - h)^2 + k") try: a = float(input("input a : \n")) h = float(input("input h : \n")) k = float(input("input k : \n")) print("vertex is : (" + str(h) + ", " + str(k) + ")") print("line of symetry : x = " + str(h)) sum = "" if 0<...
import random x= int(input("give me a number")) y = random.randint(1, 10) print(abs(x-y)/x-y)
temp = eval(input("the temeprture in C")) print("the temperture in F", 9/5*temp+32)
s = input("input a decimal number") if "." in s: print(s[s.index(".")+1:]) else: print("that doesnt have a decimal point")
# -*- coding: utf-8 -*- import os import csv # Initializing variables total_votes_cast = 0 TRUE = 1 # Setting path to election_data.csv election_data_csv_path = os.path.join("..", "Resources", "election_data.csv") # Opening election_data.csv # with open(udemy_csv, newline="", encoding='utf-8') as csvfile: with open(e...
total_50 = 10 total_20 = 20 total_10 = 100 total_5 = 100 total_money = { '50':10, '20':20, '10':100, '5':100 } total_cash = sum(int(k) * v for k, v in total_money.items()) print("Total Amount: ", total_cash) provived_cash = {'50': 0, '20': 0, '10': 0, '5': 0} while total_cash >= 0: amount_to_wi...
# URL: https://www.hackerrank.com/challenges/arrays-ds/problem def reverseArray(a): arr = [] for i in range(len(a)-1,-1,-1): arr.append(a[i]) return arr
print("What integer would you like to square?") base = int(raw_input()) print(base ** 2)
# number 2 # Will say this statement when you run it print("Welcome to the convenience store!") # Ask us for our age print("Enter your age:") # We have to enter our age and age is the variable and an int age = input() age = int(age) if age >= 18: # If our age is greater than 18 then it will ask us do we want to buy...
#!/usr/bin/python # # Simple XML parser for JokesXML # Jesus M. Gonzalez-Barahona # jgb @ gsyc.es # TSAI and SAT subjects (Universidad Rey Juan Carlos) # September 2009 # # Just prints the jokes in a JokesXML file from xml.sax.handler import ContentHandler from xml.sax import make_parser import sys import string def...
''' Day 1 _list = [] for i in range(2000, 3201): if i % 7 === 0 and i % 5 != 0: _list.append(str(i)) print(','.join(_list)) Day 2 def factorial(num): if num < 0: return "Must be greater than 0" if num == 0: return 1 return num * factorial(num-1) Day ...
''' print("day 1") _list = [] for i in range(2000, 3201): if i % 7 == 0 and i % 5 != 0: _list.append(str(i)) print(",".join(_list)) print("Day 2") def factorial(num): if num = 0: return 1 return num *(factorial(num -1)) print(factorial(5)) Print("Day 3") print("En...
#! python 2 ''' Weather.py - Launches a weather website in the browser depending upon user choice. ''' import webbrowser,sys,os while True: place = raw_input('>>> Enter Place : ') address = 'https://www.google.co.in/?gws_rd=ssl#q=weather+in+'+place print ' 1.) Google Weather' print '...
''' 문제 설명 입력으로 주어지는 리스트 x 의 첫 원소와 마지막 원소의 합을 리턴하는 함수 solution() 을 완성하세요. ''' x = [1, 4, 5, 7] def solution(x): answer = x[0] + x[-1] return answer print(solution(x))
#Project Euler Problem 16 #Power Digit Sum #What is the sum of the digits of 2^1000 #function to sum the digits of the number when we get it def digitSum(n): theSum = 0 for d in n: theSum += int(d) return theSum #program main testNum = 2**1000 num = str(testNum) print(digitSum(num))
fibonacci = [1, 2] sum = fibonacci[1] for i in range(10000): new = fibonacci[i] + fibonacci[i+1] if new > 4000000: break if new % 2 == 0: sum = sum + new fibonacci.append(new) print(sum) print(fibonacci)
def factorial(a): if a == 1: return 1 else: return a * factorial(a-1) checksum = 0 sm = str(factorial(100)) for c in sm: checksum += int(c) print(checksum)
""" It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written...
""" The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting thi...
from Deque import Deque class Array_Deque(Deque): def __init__(self): # capacity starts at 1; we will grow on demand. self.__capacity = 1 self.__contents = [None] * self.__capacity self.__front = None #index of the front of the array deque self.__back = None #index of the back of the ...
import random ''' I like to play Diablo 3 and I was upset how the random numbers system for augmenting your armor was. It seemed to apply the same stats over and over again. So I made this to try and emulate that system to see for myself how random the numbers actully are. ''' guess= 0 def RNG(number): ...
""" File _list_ globbing utility This code is based on glob but varies slightly in that it works on a list of files/paths that is passed rather than a directory/pathname. This is useful for multi-tiered glob rules or applying glob rules to a known set of files. """ # -*- coding: utf-8 -*- import os import re from glo...
#fileList = ["myfile.txt", "myprogram.exe", "yourfile.txt"] #for index in range(len(fileList)): # print(fileList[index].upper()) # print(fileList[index][0].upper()) aList = [34, 45, 67] target = 45 #if target in aList: # print(aList.index(target)) #else: # print(-1) #for index in range(len(aList)): # i...
class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) def friend(self, friend_name): #return a new student called 'friend_name' in the same school as se...
lottery_player_dict = { 'name' : 'Rolf', 'numbers': (5,9,12,3,1,21) } class LotteryPlayer: def __init__(self, name): self.name = name self.numbers = (5,9,12,3,1,21) def total(self): return sum(self.numbers) playerOne = LotteryPlayer('Omar') playerOne.numbers = (1,2,4,5,6) play...
def main(): import streamlit as st with st.echo(): import streamlit as st st.title("CONTROL FLOW") # name will be '' (empty) if the user does not type a name name = st.text_input('Name (insert your name here) ') ...
def main(): import streamlit as st with st.echo(): import streamlit as st st.title("CACHE") st.info("Use st.cache() to speed up loading time of functions with expensive computation") import time @s...
def main(): import streamlit as st st.title("DISPLAY OBJECTS / TEXT / CODE / Other inputs") #%% st.write(): FLEXIBLE DISPLAY --------------------------- st.header("[write() function](https://docs.streamlit.io/en/stable/api.html?highlight=streamlit.write#streamlit.write)") st.subheade...
def main(): import streamlit as st with st.echo(): import streamlit as st st.title("SIDEBAR") st.write("To place an element in the sidebar just add the prefix `sidebar.` to it") st.header("Look at the bottom of the lateral le...
digit_to_area = { 0 : 'Warszawa', 1 : 'Olsztyn', 2 : 'Lublin', 3 : 'Kraków', 4 : 'Katowice', 5 : 'Wrocław', 6 : 'Poznań', 7 : 'Szczecin', 8 : 'Gdańsk', 9 : 'Łódź', } def get_city(zip_code): if len(zip_code) !=6: return None if zip_code[2] !='-': return ...
import random def getAnswer(answerNumber): if answerNumber == 1: return 'To pewne' elif answerNumber == 2: return 'Zdecydowanie tak' elif answerNumber == 3: return 'Tak' elif answerNumber == 4: return 'Niejasna odpowiedź, spróbuj ponownie' elif answerNumber == 5: ...
''' Created by Roman Beya Created on 6-nov-2017 Created for ICS3U This program plays Black Jack! ''' from numpy import random import ui # generating random cards for dealer(2) and player(3) dealer_card_1 = random.randint(1, 11) dealer_card_2 = random.randint(1, 11) player_card_1 = random.randint(1, 11) player_card_2 =...
''' Created on 12.5.2016 @author: Miko Kari ''' import sys, math import numpy as np # Get minimum distance from A to B using Dijkstra's algorithm. def get_min_distance(graph, start, goal): best_distance = {id: None for id in graph.keys()} # dictionary of current distances to frontier nodes previous_node ...
# -*- coding: utf-8 -*- """ Created on Thu Jun 27 03:05:45 2019 @author: marie """ def sumDigits(n): if n == 0: return 0 else: return n % 10 + sumDigits(int(n / 10)) print(sumDigits(345)) print(sumDigits(45))
# -*- coding: utf-8 -*- """ Created on Thu Jun 27 02:21:24 2019 @author: marie """ # This sorts the dictionary by value (either in ascending or descending order) import operator d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} print('Original dictionary : ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(0)) ...
# -*- coding: utf-8 -*- """ Created on Tue Jun 25 11:53:37 2019 @author: marie """ # return fibonnaci of a certain number def Fibonnaci(iterations): listt=[] summ=0 if iterations==1: return 0 elif iterations==2: return 1 else: return Fibonnaci(iterat...
#global_variavles #board board=["-","-","-", "-","-","-", "-","-","-",] winner=None #who's turn current_player="X" game_still_going=True #display def display_board(): print(board[0]+" | "+board[1]+" | "+board[2]) print(board[3]+" | "+board[4]+" | "+board[5]) print(board[6]+" | "+board[7]+" ...
# stolen shamelessly from: # http://stackoverflow.com/questions/18262306/quicksort-with-python def quicksort(array): less, equal, greater = [], [], [] if len(array) <= 1: return array else: pivot = array[0] for x in array: if x < pivot: less.append(x) ...
""" Logistic regression for multiclass classification Class labels Hypernyms = 0 Co-siblings = 1 Random = 2 See extensive documentation at https://www.tensorflow.org/get_started/mnist/beginners """ from __future__ import absolute_import from __future__ import division from __future__ import print_function imp...
def longestCommonPrefix(strs): result = "" temp = "" if len(strs) == 1: return strs[0] if len(strs) > 1: for i in range(len(strs[0])): letter = strs[0][i] for j in xrange(1, len(strs)): temp = "" if len(strs[j]) < 1: ...
#!/usr/bin/env python3 # Created by Malcolm Tompkins # Created on May 4, 2021 # Guess the number game with randomly generated numbers import random # Function that runs Guess the number game def main(): # User input print("Welcome to Guess the number!\nPick a number from 0-100") user_number = int(input(...
#format name = input('이름을 입력하세요:') age = input('나이를 입력하세요:') print('제 이름은', name, '입니다.' '제 나이는', age, '입니다.') #콤마로 연결하면 space가 자동으로 들어감 print('제 이름은 %s입니다. 제 나이는 %s입니다.'%(name, age)) print('제 이름은 {}입니다. 제 나이는 {}입니다.'.format(name, age)) print('제 이름은 {0}입니다. 제 나이는 {0}입니다.'.format(name, age)) #뒤에서 넣을 것의 index로 넣음. prin...
#형 변환 #dict a = dict(one=1, two=2, three=3) b = {'one':1, 'two':2, 'three':3} c = dict(zip(['one', 'two', 'three'], [1,2,3])) d = dict([('two',2), ('one',1), ('three',3)]) e = dict({'three':3, 'one':1, 'two':2}) print(a == b == c == d == e) #True print(a, b, c, d, e) #{'one': 1, 'two': 2, 'three': 3}가 5...
#파일 입출력 ''' file = open('sample.txt', 'w') # w : 새로 쓰기(덮어쓰기), r: 읽기, a : append 추가 file.write('hello world') file.write('\n') file.write('hello world') file.close() print(dir(file)) ''' file = open('sample.txt', 'r') ''' print(file.read()) #hello world #hello world print(f...
#range(start:stop:step) ###1. 많은 데이터를 미리 준비하지 않아도 된다. ###2. 필요한 시점에만 데이터를 사용한다. (메모리 낭비 방지) print(list(range(10))) #0부터 10까지. 시작값 스킵하면 0 print(list(range(10, 20))) #스텝은 스킵하면 1 print(list(range(1, 100, 1))) #1부터 99까지 리스트 만들어줌 print(list(range(5, -5, -1))) #5부터 -4까지 print(type(range(10))) #출력값 <class 'range'> ###Pytho...
#!/usr/bin/python #-*- coding:utf-8 -*- ###################循环语句for####################### names = ['bob', 'james', 'paul'] for name in names: print(name) ################################################## #####################范围函数range################################ #range(100)可产生0-99这100个数据 sum = 0 tmp = ra...
import os from collections import defaultdict class Person(object): def __init__(self,first_name,last_name): self.first_name = first_name self.last_name = last_name def __repr__(self): return "{first name :" + self.first_name \ + " ; last name :" + self.last_name + "}" a1 ...
admin={"方开":"123","刘晨":"12345"} user={"张旭":"123321","沈章":"123456","尤赛赛":"123456"} while True: name_=input("请输入用户名(不能以数字开头!):") pass_=input("请输入密码:") if name_ in admin.keys(): if pass_==admin[name_]: print("欢迎您,",name_,"!您的用户组为:管理员") break else: ...
""" Solution of; Project: Problems vs Algorithms Problem 2: Search in a Rotated Sorted Array """ def binary_search(arr, low, high, target): """ return the target eleents index if it is not exists return -1 """ if low > high: return -1 mid_index = (low + high) // 2 if arr[mid_ind...
from typing import List from pathlib import Path def extract_from_result(filename: str) -> List: """ Function to extract result after running the sat solver :param filename: Path of file containing the SAT solver result :returns: List of variables with true value in the solution. Empty i...
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost", "amit", "amitt", "cpp") # prepare a cursor object using cursor() method cur = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = """CREATE TABLE PROGRAM1(Value1 INT, Value2 INT, Greater INT)""" tr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 20 09:49:20 2018 @author: karips Solves the "Quadrant Selection" Kattis problem """ x = int(input()) y = int(input()) if x > 0 and y > 0: print(1) elif x < 0 and y > 0: print(2) elif x < 0 and y < 0: print(3) else: print(4)
''' Backprop learning layer Change weights Change Biases (Proportional to how far away loss is) Change activations ''' import math import torch def backwards_pass(weights,biases,loss,layers): ind = loss.index(max([abs(x) for x in loss])) for x in range(len(biases)): biases[x] = update_weights(biases[x...
#!/use/bin/python # -*- coding: utf-8 -*- import re, json f1=file("new.txt", "r") line1=f1.readlines() f1.close() class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except Ke...
""" Basic knapsack solvers: dynamic programming and various greedy solvers """ from collections import namedtuple from copy import copy from queue import PriorityQueue from typing import List, Tuple Item = namedtuple("Item", ['index', 'value', 'weight', 'density']) Selection = namedtuple('Selection', ['...
class Solution: def reverse(self, x): if x < 0: reversed_int = str(x)[0]+str(x)[:0:-1] back_to_it = int(reversed_int) if back_to_it <= -2**31: return 0 return back_to_it else: reversed_int = str(x)[::-1] ...
#Made by Z (zhijingeu@yahoo.com) #This is a very simple dungeon explorer game with mostly text graphics built in Py.Processing #Last Edited 14 Jul 2020 import random #initialising a few variables to be used later rand=0 #TO DO in future updates - create a Player class with "health" attribute instead of using he...
# !/usr/bin/env python # -*- coding: utf-8 -*- def fib(n): a = 1 b = 0 ret = 0 for i in range(1, n + 1): ret = a + b a = b b = ret return ret def menu(): n = int(raw_input("Enter the N: ")) print "fib(%d) is: %d" % (n, fib(n)) if __name__ == '__main__': menu...
# !/usr/bin/python # -*- coding: utf-8 -*- def is_palindrome(n): s = str(n) return s == s[::-1] if __name__ == '__main__': output = filter(is_palindrome, range(1, 1000)) print(list(output))
# !/usr/bin/env python # -*- coding: utf-8 -*- def atoc(string): len_string = len(string) for i in range(len_string - 1, 0, -1): if string[i] == '+' or string[i] == '-': real = float(string[:i]) imag = float(string[i:-1]) break number = complex(real, imag) r...
# !/usr/bin/env python # -*- coding: utf-8 -*- import random def ran(): list1 = []; list2 = [] for N in range(0, random.randint(1, 100)): list1.append(random.randint(0, 2 ** 31 - 1)) for M in range(0, random.randint(1, 100)): list2.append(random.choice(list1)) return sorted(list2) ...
# !/usr/bin/python # -*- coding: utf-8 -*- from functools import reduce def str2float(s): def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] n = s.find('.') new_s = s[:n] + s[n+1:] l = map(char2num, new_s) return reduce(lambda x, y: ...
# !/usr/bin/env python # -*- coding: utf-8 -*- def fb(n): if n == 1: res = 1 elif n == 2: res = 2 else: res = fb(n-1) + fb(n-2) return res def main(): for n in range(1, 40): print "fb(%d) = %d" % (n, fb(n)) if __name__ == '__main__': main()
# !/usr/bin/env python # -*- coding: utf-8 -*- def isprime(num): x = num / 2 while x > 1: if num % x == 0: is_prime = False break x -= 1 else: is_prime = True return is_prime def menu(): num = int(raw_input("Enter the number: ")) if isprime(num...
# !/usr/bin/env python # -*- coding: utf-8 -*- def sort_key(dict1): sorted_keys = sorted(dict1) n = 0 for k in sorted_keys: print "key%d: %r, value: %r" % (n, k, dict1[k]) n += 1 def sort_value(dict2): sort_values = sorted(dict1.values()) n = 0 for v in sort_values: fo...
# !/usr/bin/env python # -*- coding: utf-8 -*- def up_side_down(dict1): dict2 = {} keys1 = dict1.keys() for key in keys1: value = dict1[key] dict2[value] = key return dict2 ''' a = {1: 'a', (2, 3): 'c, d, e', '2': (1,3,4)} b = up_side_down(a) c = up_side_down(b) print b print c '''