text stringlengths 37 1.41M |
|---|
# -*- coding utf-8 -*-
# graph is an edge list
# an edge is (start_id, end_id)
# degree is
def calculate_degrees(graph):
degrees = {}
def add_degree(node, degree):
if node in degree:
degree[node] += 1
else:
degree[node] = 1
for (start, end) in graph:... |
# Оператор условия---------
#--------------------------
brand = 'Volvo' # бренд
engine_volume = 1.5 # объем двигателя
horsepower = 179 # мощность двигателя
sunroof = True # наличие люка
# Проверка условия if
# if horsepower < 80:
# print('No Tax')
# Проверка условия if/else
# if horsepower < 80:... |
###########################################
# Imports
###########################################
import csv
from itertools import count, cycle, repeat
###########################################
# Working with the infinite iterators
###########################################
#---------------
# Counting with count(... |
from DataStructures.QueueDS.Queue import Queue
def hot_potato(nameList, num):
simqueue = Queue()
for name in nameList:
simqueue.enqueue(name)
while simqueue.size() > 1:
for i in range(num):
simqueue.enqueue(simqueue.dequeue())
simqueue.dequeue()
return simqueue.d... |
"""
Handles calculation related tasks
"""
import random
class Calculation:
""" Class for calculations """
def __init__(self):
pass
def get_download_sizes_list(self, filesize, parts):
""" function to get a list of sizes to be downloaded by each thread """
# no of bytes per thread
... |
# i=0
# for letra in 'palabra':
# print(letra,i)
# i += 1
# print('Que gol!')
# for i in range(5):
# print('Gol!')
# print('Que gol!')
# i = 0
# while i < 5:
# print('Gol!')
# i += 1
# for i in range(5):
# print('FUERA - ' + str(i))
# for j in range(2):
# print('Iteración del bu... |
#
# @lc app=leetcode.cn id=144 lang=python3
#
# [144] 二叉树的前序遍历
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from typing import List
class Solution:
... |
age=[19,25,3,90]
print(type(age))
possword=input()
while len(possword)<8:
print("ошибка пароля")
possword=input()
|
# Made in CS 232 April 2018
# This program attemps to recreate a game of yatzee
# The skeltion for this program was provided by David Tuttle
import random
import collections
NUM_SIDES = 6 # Number of sides on each die
NUM_DICE = 5 # Number of dice in the game
NUM_ROLLS = 3 # Number of rolls for each ... |
# import pyperclip
from user import Account
from Credentials import Credentials
def create_account(aname,uname,phone,email):
'''
Function to create a new contact
'''
new_account = Account(aname,uname,phone,email)
return new_account
def save_accounts(account):
'''
Func... |
import unittest
import ordinal
class OrdinalTest(unittest.TestCase):
def setup(self):
pass
def test_zero(self):
self.assertEqual("0th", ordinal.ordinal(0))
def test_first(self):
self.assertEqual("1st", ordinal.ordinal(1))
def test_second(self):
self.assertEqual("2nd", ordinal.ordinal(2))
... |
last = 0
second = 0
def next_fib():
global last
global second
if last == 0:
last = 1
return 0
current = last
last = second + last
second = current
return current
class Fib(object):
def __init__(self):
self.last = 0
self.second = 0
def next_fib(self):
if self.last =... |
# for numbers divisible by 3, print "Fizz"
# for numbers divisible by 5, print "Buzz"
# for numbers divisible by 3 and 5, print "FizzBuzz"
# otherwise, print the number
def FizzBuzz(i):
try:
if i % 15 == 0:
raise Exception, "Divisible by 3 and 5!"
if i % 3 == 0:
return "Fizz"
if i % 5 == ... |
# Scraper to collect petition info from petitions.whitehouse.gov
from BeautifulSoup import BeautifulSoup
import csv
from nltk.util import clean_html
import urllib2
# What page?
page_to_scrape = 'https://petitions.whitehouse.gov/petitions'
# What info do we want?
headers = ["Summary", "Signatures"]
# Where do we... |
def bubblesort(data):
for i in range(len(data)-1,0,-1): # man lämnar sista
for j in range(i):
if data[j] < data[j+1]:
data[j],data[j+1]= data[j+1],data[j]
data= [7,2,4,5,1,90,12,40]
bubblesort(data)
print(data)
|
x = input().split()
mon = x[0]
day = x[1]
svar= ""
if mon == "OCT" or mon == "DEC":
if (mon == "OCT" and day == "31") or (mon == "DEC" and day == "25"):
svar = "yup"
else:
svar = "nope"
else:
svar= "nope"
print(svar)
|
import logging
__author__ = 'Donhilion'
class Drawable(object):
""" Abstract class for drawable objects.
This class defines all methods a drawable object must implement.
Attributes:
environment: The environment this drawable belongs to.
"""
def __init__(self, environment=None):
""" Generates a new instan... |
ROTACAO_A_DIREITA=0
ROTACAO_A_ESQUERDA=1
ROTACAO_DUPLA_DIREITA=2
ROTACAO_DUPLA_ESQUERDA=3
def rotSimplesDireita(noNaoAvl):
avo=noNaoAvl.pai
if avo.esquerdo==noNaoAvl:
p=avo.esquerdo
else:
p=avo.direita
u=p.esquerdo
p.esquerdo = u.direito
u.direito=p
def tipoRotacao(pontoNaoAv... |
# Amy Finnegan
# Final Project
# May 4, 2013
# libraries for database
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, and_, or_, func
from sqlalchemy.orm import relationship, backref, sessionmaker, aliased
from sqlalchemy.types i... |
## Amy Finnegan
## HW4: Linked List
## I've noted where some of these aren't working
## Hopefully you can help me de-bug them!
class Node:
def __init__(self, _value=None, _next=None):
self.value = _value
self.next = _next
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(... |
def fact(n):
# assuming that n is a positive integer or 0
if n >= 1:
return n * fact(n-1)
else:
return 1
# print("0! =", fact(0))
while True:
print(fact(int(input("Enter a number: "))))
|
'''
This is our backend (database) file
We make this app into an OOP version
'''
import sqlite3
class Database:
# a function that connects to the database
# any word can be passed to init but by convention we use 'self'
def __init__(self, db): # required for python OOP (similar to default constructor)
... |
import numpy as np
import pandas as pd
def writeToDataframe(dataColumns, names = ['Time', 'Pyr', 'Lac'], path = 'pythonTest.txt'):
'''
Takes a list of columns and a list of headers and puts
them into a pandas Dataframe to be written to a text file for
later testing. This is mostly for debugging purpo... |
'''
步骤:
1,出拳
玩家:手动输入
电脑:随机(已写好)
2,判断输赢
玩家获胜
平局(出同样的手势)
电脑获胜
'''
import random
player=int(input("请出拳:1--石头;2--剪刀;3--布:"))
computer= random.randint(1,3)
print(computer)
if player==computer:
print("平局,不服再战")
elif ((player==1)and(computer==2)) or ((player==2) and (computer==3)) or ((... |
# Replace the placeholders to complete the Python program.
for i in range(1, 11, 2):
print(i)
|
list1 = []
while len(list1)<10:
v = int(input("Enter a number: "))
if v not in list1:
list1.append(v)
print(list1)
|
# Replace the placeholders with code and run the Python program
import math
#check if number is prime not overly efficient
def prime(n):
if n==1 or n==0:
return False
for x in range(2,int(math.sqrt(n)+1)):
if n%x == 0:
return False
return True
# Define the dictionary
dict ={}
#... |
def combine(f, t):
if f==0:
return t
elif t==0:
return f
elif ((f==1) and (t==2)) or ((f==2) and (t==1)):
return 3
elif (f > 2) and (f == t):
return f + t
else:
return -1
def canCombine(f, t):
return combine(f, t) > -1
def merge(row, l, r):
retur... |
#Collection data types.
#List is between the [].
Examples:-
1] x=["red","blue","green","yellow","black"]
print(x)
Output:
['red','blue','green','yellow','black']
#Can also add another data types like,
#Numbers inside the list.
2] x=["red","blue","green","yellow","black",3]
print(x)
Output:
['red'... |
# Variant 2
# Linear singly linked list with references to head and tail
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinearSinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.l... |
"""
Helper for various utility methods
"""
import json
import os.path
import requests
TLD_URL = 'http://data.iana.org/TLD/tlds-alpha-by-domain.txt'
def load_config(config_rel_path):
"""Load config data.
Parameters
----------
config_rel_path: Relative file path
Returns
-------
dict: Conf... |
'''
星期五和数字13都代表着坏运气,两个不幸的个体最后结合成超级不幸的一天。
所以,不管哪个月的13日,如果恰逢星期五就叫“黑色星期五”。
找出一年中哪些日子是“黑色星期五”??
【已知条件】2017年1月1日是星期日
【要求】输入2017之后任意年份,输出该年包含黑色星期五的具体日期
'''
from datetime import date
def black_Friday(year):
year = input("查询年份: ")
year = int(year)
if year < 2017:
print("请输入2017以后的年份")
r... |
#!/usr/bin/env python3
import sys
def main():
data = sys.stdin.readlines()
new_lines = []
for lines in data:
new_string = ""
for char in lines:
if char.islower():
new_string += char + " "
new_lines.append(new_string.strip())
for line in new_lines:
print(line)
if __name__ =... |
# lst=[1,2,3,4,5,6,7,8,9]
# num=[]
# for n in lst:
# if n%2==0:
# num.append(n)
# print(num)
lst=[1,2,3,4,5,6,7]
lst=lst[1::2]
print(lst) |
import random
from sudoku3d import Sudoku3D
class Sudoku3DGenerator:
def __init__(self, N, M):
self.N = N
self.M = M
def shift(self, base):
# Copy the original list (I know, the notation is weird).
perm = base[:]
# Pop and append the first element to the list.
... |
nums = [4, 1, 2, 1, 2]
def single_number(nums):
count = 0
for i in range(len(nums) - 1):
for j in range(len(nums) - 1):
if nums[i] == nums[j]:
count += 1
if count == 2:
print(count)
print(nums[i])
if __name__ == '__main__':
... |
#!/bin/python3
import sys
import math
__author__ = "Sunil"
__copyright__ = "Copyright 2016, hacker_rank Project"
__license__ = "MIT"
__version__ = "1.0.0"
__email__ = "sunhick@gmail.com"
def isfunny(S):
R = S[::-1]
for i in range(1, len(S)):
if abs(ord(S[i])-ord(S[i-1])) != abs(ord(R[i])-ord(R[i-1])):
return... |
#!/bin/python3
import sys
import math
__author__ = "Sunil"
__copyright__ = "Copyright 2016, hacker_rank Project"
__license__ = "MIT"
__version__ = "1.0.0"
__email__ = "sunhick@gmail.com"
class Palindrome:
def __init__(self):
pass
def count_changes(self, letter):
count = 0
for i in range(int(len(letter)/2)):... |
#!/usr/bin/py
import sys
kALPHABETS_COUNT = 26
def ispangram(line):
"""
is pangram
return: True if line contains all alphabets, false otherwise
"""
# remove all special characters and keep only alphabets
line = ''.join(e for e in line if e.isalpha())
alphabets = set()
for c in line:
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class Linklist:
def __init__(self):
self.head = None
self.next = None
def append(self, data):
new_node = Node(data)
if self.head is None... |
#!/usr/bin/python
#
# multi-file rename script for Nautilus
# (c) Andrey Yurovsky http://andrey.thedotcommune.com/
#
# To install, place this script into your .gnome2/nautilus-scripts/ directory,
# which is located in your home directory. 'rename' should appear in your
# 'scripts' menu when you restart Nautilus (or log... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【教程】Python中第三方的用于解析HTML的库:BeautifulSoup
http://www.crifan.com/python_third_party_lib_html_parser_beautifulsoup
Author: Crifan Li
Version: 2012-12-26
Contact: admin at crifan dot com
"""
from BeautifulSoup import BeautifulSoup;
def beautifulsoupD... |
# -*- coding: cp1252 -*-
'''Extra Credit
You can also add on to your Battleship! program to make it more complex and fun to play. Here are some ideas for enhancementsmaybe you can think of some more!
Make multiple battleships: you'll need to be careful because you need to make sure that you dont place battleship... |
# importing modules
from turtle import Turtle, Screen
import random
from move_gen import User_interface
# creating objects
screen = Screen() # object for the screen
user = User_interface() # object for turtle
# file handling
striped_movie_list = []
with open("movies.txt") as movies_file: # opening the f... |
archivo = open('suma desde 1 a n.txt', 'w')
while True:
resultado = 0
while True:
try:
numero = int(input("ingrese un numero : "))
break
except:
print('**ingrese un dato numerico**')
print('**intente de nuevo **')
for i in range(numero+1):
... |
archivo = open('triangulo.txt', 'w')
a={}
while True:
while True:
try:
for i in range(0,3):
#absoluto en los numeros ingresados
a[i]= int(input('ingrese lado de triangulo: '))
a[i]= abs(a[i])
break
except:
print('ingr... |
class Solution:
def climbStairs(self, n: int) -> int:
memoize = {}
memoize[0] = 0
memoize[1] = 1
memoize[2] = 2
if n in memoize:
return memoize[n]
for steps in range(3, n + 1):
memoize[steps] = memoize[steps - 1] + memoize[ste... |
def finalInstances(instances, averageUtil):
"""
:type instances: int
:type averageUtil: List[int]
:rtype: int
"""
index = 0
while index < len(averageUtil):
if averageUtil[index] < 25:
if instances != 1:
instances = -(instances // -2)
index ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
_list = []
for node in lists:
while node:
_list... |
class Solution:
def missingNumber(self, nums: List[int]) -> int:
numsSet = set(nums)
for num in range(len(nums) + 1):
if num not in numsSet:
return num |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
... |
# Write a function which compresses a string "AAACCCBBD" to "A3C3B2D".
# Then write another function to get the original string from the compressed string.
def compress(string: str) -> str:
output_string: str = ""
if not string or len(string) is 0:
return output_string
string_as_list: List[str] =... |
import random
class Solution:
def __init__(self, nums: List[int]):
self.original_list = nums
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
return self.original_list
def shuffle(self) -... |
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
visited = set()
max_rows = len(grid)
max_cols = len(grid[0])
num_islands = 0
def bfs(row, col):
queue = [(row, col)]
while queue:
row, col =... |
from string import ascii_lowercase
reversed_ascii = ascii_lowercase[::-1]
def encode(plain_text):
plain_text = plain_text.replace(',', '').replace('.', '').replace(' ', '').lower()
encoded_vals = []
for char in plain_text:
if char.isalpha():
encoded_vals.append(reversed_ascii[ascii_low... |
def abbreviate(words):
words = words.replace('-', ' ').replace('_', '')
return ''.join([word[0].upper() for word in words.split()])
|
from string import ascii_lowercase
def is_pangram(sentence):
sentence = sentence.lower()
for char in ascii_lowercase:
if char not in sentence:
return False
return True
|
def calculate(question):
question = question.strip('What is').strip('?').replace('by ', '')
operators = [('plus', '+'), ('minus', '-'), ('multiplied', '*'), ('divided', '//')]
for word, operator in operators:
question = question.replace(word, operator)
question = question.split()
try:
... |
def lib_count(filepath):
"""
This function takes in a Python script (.py) and returns two lists
containing the libraries and functions imported at the top of the script
Parameters
----------
input_path(string): The path to the input .py script
Return
----------
dependency, func... |
class Sathya:
def __init__(self,a,b):
self.a= a
self.b = b
def values(self):
print(self.a,self.b,sep=' ')
#new = Sathya(1,2)
#print(new.a)
#print(new.b)
#new.values()
class New(Sathya):
def __init__(self,c,d):
Sathya.__init__(self,c,d)
self.c = c
... |
#!/usr/bin/env python
""" Assignment 2, Exercise 3, INF1340, Fall, 2015. DBMS
This module performs table operations on database tables
implemented as lists of lists.
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
# We first define a few ta... |
import copy
alist=[1,2,3,['a','n']]
b=copy.copy(alist)
alist[3].append('b')
alist.append(1)
alist=[1,2,3,['a','b']]
b=copy.copy(alist)
b[-1].append('c')
print(alist)
print(b)
print(id(alist))
print(id(b))
|
# Import the file to a DataFrame and perform a row count
annotations_df = spark.read.csv('annotations.csv.gz', sep='|')
full_count = annotations_df.count()
# Count the number of rows beginning with '#'
comment_count = annotations_df.filter(col('_c0').startswith('#')).count()
# Import the file to a new DataFrame, with... |
# Define the following variables
# name, last_name, age, eye_color, hair_color
first_name = 'Dilan'
last_name = 'Morar'
eye_color = 'dark brown'
hair_color = 'black'
age = '22'
# Prompt user for input and Re-assign these
first_name = input('What is your first name? ')
last_name = input('What is your last name? ')
e... |
#!/usr/bin/python
#python strip
'''
this is the introdaction for this
strips,please read carefully!
'''
while True:
reply = input('Enter text: ')
if reply == 'stop':break
try:
num = int(reply)
except:
print('bad!' * 2)
else:
print(int(reply) ** 2)
print('bye')
|
word = input().lower().replace(" ", "")
i = len(word)
for letter in word:
if letter == word[i-1]:
i -= 1
continue
else:
print("no")
break
if i == 0:
print("yes")
|
numbers = input().split()
big = int(numbers[0])
small = int(numbers[0])
for number in numbers:
if int(number) > big:
big = int(number)
if int(number) < small:
small = int(number)
print(str(big) + " " + str(small))
|
import re
p = re.compile("19 \d \d \d \d \d \d \d \d\d")
c = re.compile("19\d{9}")
number = input()
if bool(p.search(number)) | bool(c.search(number)) and len(number) == 11:
print("Yes")
else:
print("No")
|
def pairSum(b,n):
y = []
for i in range(len(b)):
for j in range(i+1,len(b)):
sum = b[i]+b[j]
if sum == n:
y.append((b[i],b[j]))
return y
print pairSum([1,2,3,4],5)
|
from Objects import Animal
# Inherit from Animal class
# located in another file
class Dog(Animal, object):
__owner = None
def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
#Animal.__init__(self)
#self.all_data = [name, height, weight, sound]
supe... |
#!/usr/bin/python
import math
def displayPathtoPrincess(n,grid):
mloc=[0,0]
pfound=False
mfound=False
sameline=False
j=0
for element in grid:
i=0
for letter in element:
if letter is 'p':
#print(i,letter)
locx=i
path=elem... |
def lista_de_numeros():
resposta = 'S'
numeros = []
while resposta in 'Ss':
numeros.append(int(input("Digite um numero inteiro: ")))
resposta = str(input("Deseja continuar? [S/N]")).upper().strip()[0]
print('-' * 50)
print(f"Sua lista de números é: {numeros}")
print(f"O... |
num1,num2=list(map(int,input().split()))
arr=[]
def check_armstrong(num1):
num = num1
st=str(num1)
l=len(st)
sum=0
while(num>0):
c=num%10
sum=sum+(c**l)
num=num//10
if int(num1)==sum:
return True
else:
return False
for i in range(num1,... |
num=input()
def rev(num):
if num.isdigit():
st=str(num)
rev=st[::-1]
print(rev)
else:
print("invalid input")
rev(num) |
num=int(input())
def find_factorial(num):
f=1
for i in range(1,num+1):
f=f*i
print(f)
find_factorial(num) |
from typing import List
def task_1_add_new_record_to_db(con) -> None:
"""
Add a record for a new customer from Singapore
{
'customer_name': 'Thomas',
'contactname': 'David',
'address': 'Some Address',
'city': 'London',
'postalcode': '774',
'country': 'Singap... |
# Creates new empty list
shopping_list = []
# Function that adds items to the list
def add_to_list(item):
shopping_list.append(item)
# Notify the user that the item was added and state the number of items in the list
print("Added! The list has {} items".format(len(shopping_list)))
# Function ... |
import random
import pickle
maze = None
solution = []
def load(path):
global maze
with open(path, "rb") as f:
maze = pickle.load(f)
def solve():
global maze
global solution
while len(solution) > 0:
if solution[-1] == maze.cells[-1][-1]:
break
neighbours = maze.... |
# Remainder - modular arithmetic
# systematically restrict computation to a range
# long division - divide by a number, we get a quotient plus a remainder
# quotient is integer division //
# the remainder is %
# problem - get the ones digit of a number
num = 49
tens = num // 10
ones = num % 10
# application - 24 ho... |
aclNum = int(input("What is the IPv4 ACL number? "))
if aclNum >= 1 and aclNum <= 99:
print("This is good IPv4 ACL.")
elif aclNum >= 100 and aclNum <= 199:
print("This is extended IPv4 ACL.")
else:
print("This is not good or ext IPv4 ACL.")
|
def convertDecimalToBinary(value: str or int):
number = int(value)
string = ''
while number > 0:
rest = int(number % 2)
string += str(rest)
number = (number - rest) / 2
return string[::-1]
while True:
print(convertDecimalToBinary(input("Informe o valor em decimal: ")))
|
arr = ["apple", "orange","Lemon", "banana"]
for item in arr:
print(item.upper()) |
import random
class Animal(object):
def __init__(self, age):
self.age = age
self.name = None
def __str__(self):
return "animal: " + str(self.age) + ": " + str(self.name)
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(... |
import sys
if len(sys.argv) < 2:
sys.exit("""You must give a translate request in format:\n"""
"!pigify lol")
arg = sys.argv
word = arg[1]
word = word.lower()
first = word[0]
pyg = 'ay'
new_word = word + first + pyg
if original.isalpha():
new_word = new_word [1:len(new_word)]
print(new_word.encode(... |
#Exercise 1) 1 to 10
for i in range(1,11):
print(i)
print('\n')
#Exercise 2) n to m
start = int(input('Enter a start number! '))
end = int(input('Enter a end number!'))
for i in range(start,end+1):
print(i)
print('\n')
#Exercise 3) Odd Numbers
for i in range(10):
if i%2 != 0 and i != 0:
print(i)
p... |
from csv import DictReader, DictWriter
def split_question_sents(text, num_expected):
"""
takes the question text and returns it as a list of clean sentences
a sentence is a list of lowercase chars and symbols that has no whitespace at the beginning and end
there is no period at the end of the sentence
... |
import re
if __name__ == "__main__":
text = "this,\,nations,+2,gwrg"
text2 = "ggwger gvgve rgvgre efefwe cdc this fewg"
for word in text.split(','):
try:
finds = re.findall(word, text)
print finds
except:
print "couldnt use", word, "as re"
|
# Reverse Cipher
message = input('Enter the message you want to encrypt: ')
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
print(translated) |
#This code takes files in one folder which have , and - in the name
#replaces these with m and c, and copies them to another folder
path2 = "filepath1"
import os
path="filepath2"
for filename in os.listdir(path):
if filename.endswith(".jpg"):
os.rename(os.path.join(path, filename), os.path.join(path2, file... |
def minionGame(string):
vowel="AEIOU"
count1=0
count2=0
for i in range(len(string)):
if string[i] not in vowel:
count1+=len(string[i:]) #len(string)-i
else:
count2+=len(string[i:]) #len(string)-i
if count1>count2:
print("STUART",count1)
elif count... |
# Tipos de datos y operadores
b = True
n = True
n = not (n)
e = 4
s = e + 4
d = s + 2.25
r = round (d)
r = float(r)
di = d / 1.15
k = int(di)
res = 5 % 2
div1 = 4 / 2
div1 = int(div1)
div2 = 4 / 3
div2 = int(div2)
el = 9845 ** 24
l = ("hola variable");
ll = l + (" tipo cadena");
pi = 3.1416
area = r**2*pi
gr = 1.8*12... |
def even_fib():
fib0 = 1
fib1 = 1
index = 0
sum = 0
while (index < 100):
next_val = fib0 + fib1
fib0 = fib1
fib1 = next_val
if (next_val % 2 == 0):
index +=1
sum += next_val
return sum
print(even_fib())
|
#Program to swap first and last number of the list
#Input : [1, 2, 3, 4]
#Output : [4, 2, 3, 1]
# Swap function
def swapList(newList):
size = len(newList)
#Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
newList = [1... |
#Remove i’th character from string in Python
# Python code to demonstrate
# method to remove i'th character
# using replace()
# Initializing String
test_str = "GeeksForGeeks"
# Printing original string
print ("The original string is : " + test_str)
# Removing char at pos 3
# using replace
... |
class Location:
def __init__(self, obj, loc):
self.obj = obj
if loc == 'before':
self.before = True
self.after = False
elif loc == 'after':
self.before = False
self.after = True
else:
raise ValueError
def __eq__(self, n... |
name = raw_input("What's your name? ")
age = raw_input("What's your age? ")
print 'Hello {0}!'.format(name)
try:
if float(age) >= 18:
vote = raw_input("Have you registered to vote yet? (y/n) ")
while vote != "y" or vote != "n":
print("y or n only please")
vote = raw_input("H... |
#!/usr/bin/env python3
data = []
with open('data.txt', 'r') as file:
for line in file:
data.append(line[:-1]) # Strip the newline char!
your_ticket = [79,193,53,97,137,179,131,73,191,139,197,181,67,71,211,199,167,61,59,127]
def get_ranges():
ranges = []
for line in data:
for word in line.... |
#!/usr/bin/env python3
import csv
data = []
with open('formatted.txt', 'r') as file:
reader = csv.reader(file)
for row in reader:
data_obj = {}
for item in row:
data_obj[item[:3]] = item[4:]
data.append(data_obj)
def part_one():
count = 0
for item in data:
i... |
input_str = "Mr John Smith "
''' Start trimming at the end of the string first '''
rev_str = ''
eof_space = True
for i in range(1, len(input_str)+1): # Print this in reverse
if(input_str[-i] == " " and eof_space == True):
pass #ignore EOF space
elif(input_str[-i] == " " and eof_space == False):
rev_str += "... |
dict = {}
stud_dict = {}
for i in range(2019, 2022):
print("Year- " + str(i))
Year = i
u1 = int(input("Number of students in UG 2nd year: "))
u2 = int(input("Number of students in UG 3rd year: "))
u3 = int(input("Number of students in UG 4th year: "))
p1 = int(input("Number of students in PG 1st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.