blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
0e63470415a13d6577768a67cb2f6aa014448be1 | zenithude/Python-Leetcode | /stringShift.py | 1,888 | 3.828125 | 4 | # -*- coamounting: utf-8 -*-
"""
Createamount on Tue Apr 14 09:48:14 2020
@author: zenit
You are given a string s containing lowercase English letters, anamount a matrix
shift, where shift[i] = [amountirection, amount]:
amountirection can be 0 (for left shift) or 1 (for right shift).
amount is th... |
9c4fab8e7612bba762235f3ade7a0bfef9b31b1c | zenithude/Python-Leetcode | /backspacexompare.py | 1,266 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 18:45:18 2020
@author: zenit
Given two strings S and T, return if they are equal when both are typed into
empty text editors. # means a backspace character
"""
def newString(S):
q = []
for i in range(0, len(S)):
... |
ed9feb1fb89538c4177d7bec8da30d4032149e5c | zenithude/Python-Leetcode | /maxprofit.py | 1,266 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 21:48:42 2020
@author: zenit
Say you have an array for which the ith element is the price of a given
stock on day i.
Design an algorithm to find the maximum profit. You may complete as many
transactions as you like (i.e., buy one and sell one share of the s... |
661959a1cace03d1be96a892ed6d8115c734a40f | zenithude/Python-Leetcode | /reorderList.py | 2,071 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be
changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->... |
6c428ba215f8f5b165e503a2303fa1431392e932 | IamMayankThakur/Hackerrank-Algorithm-Solutions | /Problem Solving/Find Digits.py | 603 | 3.71875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the findDigits function below.
def findDigits(n):
l = list()
c = 0
k = str(n)
for i in k:
l.append(int(i))
for j in l:
if(j!= 0):
if(n%j == 0):
c = c+1
... |
ef5ca12db25123c735042e9cff64572451dbd01a | IamMayankThakur/Hackerrank-Algorithm-Solutions | /Problem Solving/Apple_and_Orange.py | 873 | 3.703125 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
ap = 0
for i in apples:
if((a + i) >= s and (i+a) <= t ):
ap = ap+1
# print (a+i)
pr... |
3c78d3b705e7da358bb11fbba383c60e9d84505a | leodeve/maths-computer-science-project | /Permutations.py | 14,592 | 3.796875 | 4 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import copy
def factorielle(n):
if n==1: #fin de la récursivité lorsque n=1
return 1
else:
return n*factorielle(n-1) #utilisation de la récursivité pour avoir le factorielle
def traductions_avec_message(): #fonctionne pour t... |
1993323d29a3a72875485e99c86b2fda2ab72c73 | PureSin/euler | /python/twelve.py | 1,159 | 3.703125 | 4 | from Euler import factor
"""
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
... |
fe33fda982e4318b65a079a6d8bd74555dd94ba8 | abborgia/python_archivos | /cuentaBar/cuentaBar.py | 898 | 3.734375 | 4 | class Bar():
#precio
menu = {
'Vino': 3000,
'Cerveza': 2800,
'Bebidas 1/2': 1500,
'Pollo': 4500,
'Carne': 7500,
'Ensalada': 2800,
'Postre': 2400
}
def __init__(self):
self.total = 0
self.objetos = []
def add(self, objetos)... |
a45737d3f410652f64534012fbca8b34df4df339 | abborgia/python_archivos | /ancapsular1.py | 497 | 3.546875 | 4 | class Alumno:
def __init__(self, nombre, apellido):
self.__nombre=nombre
self.__apellido=apellido
@property
def nombreLista(self):
return self.__nombre+" "+ self.__apellido
@nombreLista.setter
def nombreLista(self, nombreCompleto):
self.__nombre, self.__apellido = n... |
740dd18a530b14378d2b52dd3309257e99d3df77 | prasant73/python | /programs/shapes/pattern3.py | 169 | 3.734375 | 4 | '''
*
**
*** '''
def pattern3(n):
print ("Pattern C")
for i in range (0,n+1,1):
print((n-i) * ' ' + i * '*')
n=int(input("Enter limit"))
pattern3(n)
|
753f8053bf83931bf83cf1da422b89416eeb4184 | prasant73/python | /programs/m1_list_rotation.py | 605 | 4.1875 | 4 | from inputs import list_input
import cProfile
def forward_rotation(l, n):
for i in range(n):
for i in range(len(l)-1):
l[i],l[i+1] = l[i+1],l[i]
return l
def backward_rotation(l, n):
for i in range(n):
for i in range(-len(l)-1,-1):
l[i-1],l[i] = l[i],l[i-1]
ret... |
463fa32db7284ea1088d0193b26aa64f220da509 | prasant73/python | /programs/shapes/higher_order_functions.py | 2,063 | 4.4375 | 4 | '''4. Map, Filter and Reduce
These are three functions which facilitate a functional approach to programming. We will discuss them one by one and understand their use cases.
4.1. Map
Map applies a function to all the items in an input_list. Here is the blueprint:
Blueprint
map(function_to_apply, list_of_inputs)
Most... |
31684e45929df00b89f43c5ad0dbbeeebbe9f65c | prasant73/python | /theory/iterators.py | 6,757 | 4.5 | 4 |
# Iterators are objects that can be iterated upon.
'''
What are iterators in Python?
Iterators are everywhere in Python. They are elegantly implemented within for loops,
comprehensions, generators etc. but hidden in plain sight.
Iterator in Python is simply an object that can be iterated upon. An o... |
544229afceb6d3293382c7df3727e93c773b6f65 | prasant73/python | /programs/shapes/diamondinsquare.py | 267 | 3.65625 | 4 | def demo(n):
print ("Diamond inside square")
k=n
for i in range (n,0,-1):
print( i * '*'+(n-k)*' '+i*'*')
k-=2
k=2*n-2
for i in range (0,n,):
print((i+1) * '*'+(k)*' '+(i+1)*'*')
k-=2
n=int(input("Enter the limit"))
demo(n)
|
0a55ec96e108a5142bfdc1f177cd06fe75d0423e | prasant73/python | /programs/shapes/listdeletion.py | 457 | 3.671875 | 4 | def listdeletion(l,n,dele):
print(l)
f=0
for i in range(0,n):
if(l[i]==dele):
pos=i
f=1
if(f==0):
print("Element not present")
else:
for i in range(pos,n-1):
l[i]=l[i+1]
print(l[0:n-1])
l=[]
n=int(input("Enter the limit"))
for i in rang... |
105fcd650f96320836e74da34bde3b13a0eafbfe | prasant73/python | /programs/shapes/combined.py | 287 | 3.625 | 4 | '''
*
**
***
****
***
**
*
'''
import cProfile
def pattern3(n):
print ("Pattern C")
for i in range (0,n+1,1):
print((n-i) * ' ' + i * '*')
for i in range (n-1,0,-1):
print((n-i) * ' ' + i * '*')
n=int(input("Enter limit"))
cProfile.run('pattern3(n)')
|
bb8fa627893c964ce8dfd8a94dab47841afcf0b6 | bhyeanhasan/Online_Courses | /Using Databases with Python/bh.py | 392 | 3.515625 | 4 | import sqlite3
try:
connection = sqlite3.connect("Python.db")
con = connection.cursor()
query = """INSERT INTO contact
(name, email)
VALUES
('James','james@pynative.com')"""
print("Successfully Connected to SQLite")
c... |
3ed6d2e769b7b19d876e70052236105c8072ec7a | Mantramurthy/Flag | /flaf.py | 897 | 3.5 | 4 | def A():
import turtle as t
d=t.Turtle()
d.begin_fill();d.fillcolor("Orange")
d.left(90);d.forward(40);d.right(90);d.forward(150);d.right(90);d.forward(40);d.right(90);d.forward(150);d.end_fill()
d.begin_fill();d.fillcolor("white")
d.left(90);d.forward(40);d.left(90);d.forward(75);d.begi... |
07793f76b375584b2609193544aa220ebc775faf | nvimai/python-exercises | /answers/loops.py | 4,652 | 4.1875 | 4 |
# Done all following questions to have $10
#1. Write a Python function to reverse the order of the items from an array
# array1 = [1, 2, 3, 4, 5, 6, 7]
# def flipArray(array):
# #reverses the order of the array using list slicing
# flip = array [::-1]
# #prints the reversed array
# return (flip)
# prin... |
a4adbc59a144aede5042fb1f9b1054143a0fb551 | nvimai/python-exercises | /modules/functions/shapes/rectangle.py | 409 | 3.75 | 4 | class Rectangle:
def __init__(self, height, width):
self._height = height
self._width = width
def height(self, height = None):
if(height != None): self._height = height
return self._height
def width(self, width = None):
if(width != None): self._width = width
return self._width
def __s... |
c1cd86da9cab336059a84e6401ac97232302036c | TurbidRobin/Python | /30Days/Day 10/open_file.py | 323 | 4.15625 | 4 | #fname = "hello-world.txt"
#file_object = open(fname, "w")
#file_object.write("Hello World")
#file_object.close()
# creates a .txt file that has hello world in it
#with open(fname, "w") as file_object:
# file_object.write("Hello World Again")
fname = 'hello-world.txt'
with open (fname, 'r') as f:
print(f.read... |
3f0fad3ba1daa96a294fa56aed7e291322bac34c | julianascimentosantos/Snake | /snake.py | 3,848 | 3.546875 | 4 | import pygame, random
from pygame.locals import *
# Tornar o grid da maçã 10 igual o da cobra para alinhar
def on_grid_random():
x = random.randint(0,590)
y = random.randint(0,590)
return(x//10 * 10, y//10 * 10)
# Testar a colisão:
def collision(c1, c2):
return(c1[0] == c2[0]) and (c1[1] == c2[1])
# ... |
8fe6c5421d8098f0ab981a74fb5a7d3e660a79f4 | Rijushree123/python_code | /search numbr_list.py | 446 | 3.890625 | 4 | def search(list1,ele):
list2=[]
flag=False
for i in range(len(list1)):
if(ele==list1[i]):
flag=True
list2.append(i)
if(flag == True):
for i in list2:
print("Element",ele," is found at index: ",i)
else:
print("Searched Element... |
4d4490a1a54006a60f9f9e04c612782da109819a | Rijushree123/python_code | /Flyd_Cycle_detection.py | 951 | 3.734375 | 4 | class Node:
def __init__(Node, data):
Node.data = data
Node.next = None
def detectCycle(head):
fast=head
slow=head
loopexist=0
while(fast!=None and slow!=None and fast.next!=None):
fast=fast.next.next
slow=slow.next
if(fast==slow):
... |
d6352f2224c65c9e7ae6758698120b3c82379a45 | Rijushree123/python_code | /calculator.py | 3,129 | 3.796875 | 4 | from tkinter import *
def btnClick(numbers):
global operator
operator=operator+str(numbers)
text_Input.set(operator)
def btnClearDisplay():
global operator
operator=""
text_Input.set("")
def btnEquals():
global operator
su=str(eval(operator))
text_Input.set(su)
... |
ba9b58af0648e3cfc0cd4c2a07337ea89141d289 | AlejandroArbelaez21/holbertonschool-interview | /0x16-rotate_2d_matrix/0-rotate_2d_matrix.py | 323 | 3.515625 | 4 | #!/usr/bin/python3
"""
Test 0x16 - Rotate 2D Matrix
"""
def rotate_2d_matrix(matrix):
""" rotate a matrix 2D """
matrix_copy = matrix.copy()
for i in range(len(matrix[0])):
temp_array = []
for row in reversed(matrix_copy):
temp_array.append(row[i])
matrix[i] = temp_arr... |
ee3188340aca8712a11c994c878b309c9db7bafb | laithuthao/laithuthao-c4e34 | /Session4/dictionary.py | 689 | 3.8125 | 4 | #Dictionary
person = {
"name": "Duc",
"age": 22,
"ex-gf": 3,
"university": "FTU",
}
#key: value
#CRUD
#1. READ
#1.1 READ one
# name = person["name"]
# age = person["age"]
# print(name)
# print(age)
#1.2 READ many (hiển thị những key bên trái)
#loop by keys
# for key in person.keys():
# print(key... |
09123c65590bff56a2d27dfdc794519ae760c346 | laithuthao/laithuthao-c4e34 | /Session1/A square.py | 115 | 3.546875 | 4 | from turtle import *
shape("arrow")
speed(20)
for i in range(4):
forward(100)
left(90)
mainloop() |
e43e241d26f4845cb617fb6ff6c34f4d5faa39b4 | laithuthao/laithuthao-c4e34 | /Session2/Mecung.py | 203 | 3.953125 | 4 | from turtle import *
shape("turtle")
speed(90)
for i in range(1,500,5):
forward(i)
left(90)
mainloop()
#length = 1
for i in range(1,500):
forward(length)
left(90)
length=length+5 |
9264f589b078f4aeef60a7a5d107dc42c4611171 | laithuthao/laithuthao-c4e34 | /Session4/BTVN/e3.py | 298 | 3.953125 | 4 | answer = {'1.': 35, '2.': 36, '3.': 40, '4.': 44}
print('Answer the following algebra question: ')
print('If x = 8, then what is the value of 4(x + 3)?')
for key, value in answer.items():
print(key, value)
n = int(input('Your choice: '))
if n == 4:
print('Bingo')
else:
print(':(') |
9fbd9afe0cd036da73b82beb2c19814009d50ae3 | laithuthao/laithuthao-c4e34 | /Session2/Weather.py | 143 | 3.53125 | 4 | from random import randint
n=randint(0, 100)
print(n)
if n < 30:
print("Sunny")
elif n < 70:
print("Rainy")
else:
print("Cloudy")
|
d1093e8e282529d6cae94831855f69d5779bbc6b | laithuthao/laithuthao-c4e34 | /Session4/teencode.py | 488 | 4.03125 | 4 | code = {
"hc": "hoc",
"ng": "nguoi",
"pt": "phat trien",
"eny": "em nguoi yeu",
"any": "anh nguoi yeu"
}
while True:
for key in code.keys():
print(key, end=" ")
print()
a=input("Your code?")
if a in code:
print(code[a])
else:
b=input("No value. Do ... |
dffc12dae4ff0c0fa100925f65c4d8d95e81b3b9 | piccicla/pysdss | /pysdss/multicriteria/weight/ranking.py | 1,848 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: ranking.py
# Purpose: criterion weighting with ranking methods
#
#
# Author: claudio piccinini
#
# Updated: 11/04/2017
# -----------------------------------------------------------------... |
5d5bba8a9e07146a1ff3da235b68bfe8e832d07d | ray-barrett/python_challenges | /python/challenge2.py | 1,347 | 4 | 4 | #!/bin/python3
import os
import re
_EMAIL_EXP = "^[\\w-]+@[A-Za-z0-9]+\\.[a-z]{1,3}$"
def is_valid_email(email):
return re.match(_EMAIL_EXP, email)
def validate_emails(emails):
"""Take a list of email address strings and return the valid emails
For an email to be consdered valied it must comply with ... |
475ee09f329149d379a3185734fa96d4402f0e0b | fcolumbu/Raspberry_Pi_Projects | /Piface_Process_Controller/process.py | 11,279 | 3.734375 | 4 | #!/usr/bin/env python
# process.py
# Author: Francis M. Columbus
# Purpose:
# This program uses software timed loops to cycle an AC load ON / OFF for a specified
# number of cycles with a preset ON duration in minutes and a preset OFF duration.
# If zero is specified for the number of cycles, the loop is continuous.
... |
09e252cbd0945f505f98d5ffb89e8aabcab4f3b4 | jnibali/In-class-activity---Unittest-and-pytest | /Palindrome-test.py | 319 | 3.5 | 4 | import unittest
import Palindrome
class testCaseAdd(unittest.TestCase):
def test_volume(self):
self.assertEqual(Palindrome.checkpalindrome("Madam"),"is palindrome")
self.assertEqual(Palindrome.checkpalindrome("Joe"),"is not palindrome")
if __name__ == '__main__':
unittest.main() |
d85616e945092f788e474a301fc611245dde28d3 | Jallibad/IntroToAlgo | /lab2/IntegerMultiplication.py | 1,395 | 3.78125 | 4 | import math
import time
import random
def method1(x, y):
answer = 0
i = 0
while y != 0:
if y & 1 != 0:
answer += x << i
y = y >> 1
i += 1
return answer
def method2(x, y):
if y==0:
return 0
z = method2(x, y >> 1) << 1
if y & 1 == 0: # if y is even... |
083205f06162b65b9ea5e439bb1064ae940286b9 | Jallibad/IntroToAlgo | /lab6/stuff.py | 2,329 | 3.84375 | 4 | from collections import deque
from heapdict import heapdict
class Graph(object):
def __init__(self):
self.nodes = set()
self.edges = heapdict()
self.distances = {}
def add_node(self, value):
self.nodes.add(value)
def add_edge(self, from_node, to_node, distance):
s... |
fe55f0191efbdccc3f9da56258b669b716d02df1 | VFermat/Double-Snake-AI | /games/AIEight.py | 4,556 | 3.640625 | 4 | """
## AI Model Two
## Used parent move function (see game.py for more info)
## Overrides getState function. State is now the concatenation of the board representation and booleans representing the food position
"""
from .game import Game
import numpy as np
from utils.directions import Directions
class AIEight(Game... |
0b3dc1e2ac8363dc1b690690268c1d2c0c15d7ea | KarimAbdelazizCodes/todo-list-sql | /create_todo_list.py | 909 | 3.828125 | 4 | # Here the user can create new lists
import sqlite3
from datetime import datetime
def new_list():
timestamp = datetime.now().strftime("%d-%b-%Y at %H:%M")
database = 'bonus_todos.sqlite'
conn = sqlite3.connect(database)
cur = conn.cursor()
query = 'INSERT INTO todo_lists (list, created) ' \
... |
bc00404073a57bad907452662f8df11bbfed47a9 | makkksimka/Holidaywork | /Домашнее задание2.py | 703 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import sqrt
if __name__ == "__main__":
a = float(input("a: "))
if a != 0:
b = float(input("b: "))
c = float(input("c: "))
D = b * b - 4 * a * c
if D > 0:
t1 = (-b - sqrt(D)) / (2 * a)
t2 = (-b + s... |
12add3242eb6f58add74c7490a31f944f3a9f388 | Marcus-V-Freitas/Web_Scraping_Python | /WebScraper-EventsUFSM.py | 1,203 | 3.671875 | 4 | # Importar bibliotecas
import pandas
from GetSoup import get_soup
from SearchEvent import search
# Função auxiliar para formatar os títulos
def format_text(element):
text = element.text.title()
return text
# Criamos um dicionário vazio para adicionar os eventos futuramente e listas para armazenar os títulos ... |
e169099ae241c5085926a4671ecca1d56329eeb8 | vickykumarmlt/Learning | /prime.py | 414 | 4.0625 | 4 | # Python Program to find prime numbers in a range
import time
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
# Driver function
t0 = time.time()
c = 0 # for counting
for n in range(1, 1):
x = is_prime(n)
c += x
... |
c1d63b51843132524322c636282ecfa2d4bde0b3 | KevinGodinho/python_scripts | /password-validation/script.py | 237 | 3.78125 | 4 | import re
pattern = re.compile(r'[A-Za-z0-9$%#\@]{8,}\d')
password = input('Please enter password: ')
check_password = pattern.fullmatch(password)
if check_password:
print('Thank you!')
else:
print('Please type valid password.')
|
f14b58469681a9c62114fe99483d98929ec65669 | nagaraju291990/list-match | /term-list-validator.py | 1,828 | 3.53125 | 4 | #This program validates the forms in the list file of form T3[TAB]T1|T2|T3
import re
import sys
with open(sys.argv[1], 'r', encoding='utf-8') as fp:
lines = fp.read()
f = open('out.txt', 'w', encoding='utf-8')
line_no = 0
flag = 0
for line in lines.split("\n"):
line_no += 1
if(line == ""):
continue
#line = lin... |
c682297ebf5649db17631456bb5881d6e7afeff9 | nagaraju291990/list-match | /accr_match_replace.py | 7,123 | 3.765625 | 4 | #find and replace words from a tab seperated list into the input file
#how to run:? python3 accr_match_replace.py inputfile.txt list.txt(tab seperated)
import sys
import re
#open file using open file mode
fp1 = open(sys.argv[2]) # Open file on read mode -- input file
lines = fp1.read().split("\n") # Create a list cont... |
bb504ae12f253ef237017a793e7b6aafba20a77a | webclinic017/nick-alex-csproject | /reddit_app/sql/model.py | 800 | 3.734375 | 4 | import sqlite3
from config import SQLITE_DB_FILENAME
db_conn = None
def dict_factory(cursor, row):
"""Convert database row objects to a dictionary keyed on column name.
This is useful for building dictionaries which are then used to render a
template. Note that this would be inefficient for lar... |
5a4e79b821cfe049f7750ad6f4ae2c6c4115f6f0 | moiri-usi/USI-compilers | /pythonExercises/exercise1.py | 857 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
# Simon Maurer
# Lothar Rubusch
"""
usage:
exercise1.py <filepath>
e.g.
exercise1.py ./input.txt
"""
import sys, re
if len( sys.argv[1:] ) != 1:
print "ERROR, usage:\n" + sys.argv[0] + " <filename>"
print "e.g.\n" + sys.argv[0] + " ./input.txt"
s... |
56a4bdcb43927bcc9b54f1dd84f98a1f513172e1 | eaxcggdiwmw/Exercise | /习题060.py | 124 | 3.609375 | 4 | # 题目:计算字符串长度。
# 程序分析:无。
n = input("pls input string:")
long = len(n)
print(long)
|
eb67396f9390e407c824fb1b268cce5fd337f49a | eaxcggdiwmw/Exercise | /习题025.py | 277 | 3.6875 | 4 | # 题目:求1+2!+3!+...+20!的和。
# 程序分析:此程序只是把累加变成了累乘。
a = []
total = 0
for i in range(1, 22):
num = 1
a = []
for j in range(1, i):
num *= j
a.append(num)
for n in a:
total += n
print(a)
print(total)
|
67a36e3f56ca41dbc6366220e4573c76882530e6 | eaxcggdiwmw/Exercise | /习题012.py | 400 | 3.765625 | 4 | #题目:判断101-200之间有多少个素数,并输出所有素数。
#程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。
for i in range(101,200):
flag = 0
for j in range (2,i):
if i % j == 0:
break
else:
flag = 1
if (flag == 1):print (i) |
0259800909c318b6e7dc68d558f0983783d33046 | eaxcggdiwmw/Exercise | /习题098.py | 419 | 3.703125 | 4 | # 题目:从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件"test"中保存。
# 程序分析:无。
from sys import stdout
def switch(strings):
strings = strings.upper()
return strings
filename = input('输入文件名:\n')
fp = open(filename, "w")
ch = input('输入字符串:\n')
ch = switch(ch)
fp.write(ch)
stdout.write(ch)
fp.close()
|
2420428909eeca6695a1d290001a7ae69affe0fa | eaxcggdiwmw/Exercise | /习题001.py | 297 | 3.578125 | 4 | # 题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
for a in range(1, 5):
for b in range(1, 5):
for c in range(1, 5):
if (a != b) and (b != c) and (c != a):
print(100 * a + 10 * b + c)
|
bbdc771a0c131f16104d417ce0edf18aa5ec2675 | eaxcggdiwmw/Exercise | /习题081.py | 375 | 3.578125 | 4 | # 题目:809*??=800*??+9*?? 其中??代表的两位数, 809*??为四位数,8*??的结果为两位数,9*??的结果为3位数。求??代表的两位数,及809*??后的结果。
# 程序分析:无。
num = 0
for n in range(10, 99):
if (809 * n == 800 * n + 9 * n) and ( 1000 <= 809 * n <= 9999) and (100 <= 9*n <= 999):
num = n
print(num)
print(num*809)
|
015acf003af33c4c21906694d5517a9f914ea2ec | eaxcggdiwmw/Exercise | /习题036.py | 214 | 3.6875 | 4 | # 题目:求100之内的素数。
# 程序分析:无。
for i in range(1, 1000):
flag = 1
for j in range(2, i):
if i % j == 0:
flag = 0
if flag == 1:
print(i, end=" ")
|
524f64ba38e5a5b0ba8234e0a5ae08351b58d96f | Maryam-ask/Matplotlib_Tutorial | /plotting/_plotting.py | 265 | 3.8125 | 4 | import matplotlib.pyplot as plt
import numpy as npy
x_points = npy.array([1, 8])
y_points = npy.array([3, 10])
# Noghteyeha: a[1,3] & b[8,10]
# The x-axis is the horizontal axis.
# The y-axis is the vertical axis.
plt.plot(x_points, y_points)
plt.show() |
a9fc0f339575571afa1032209ab7ef7ecb79be7d | fromsujay/Learn-Python-the-Hard-Way | /ex35.py | 4,663 | 3.953125 | 4 | from sys import exit
def gold_room():
print "\nThis room is full of gold. How much do you take ?\n"
next = int(raw_input("\nPlease enter an integer value for number of gold coins : \n"))
if next <= 100:
print "\nNice, you're not greedy, you win! You become a rich person.\n"
exit(0)... |
61d39f8df6b21c244791f9e735f8e9b2a8c8240e | mkandes/sqlite3db | /sqlite3db.py | 21,752 | 3.671875 | 4 | #!/usr/bin/env python
#
# TODO: Add support for in-memory databases.
import contextlib
import logging
import os
import sqlite3
import sys
#logging.basicConfig(level=logging.DEBUG)
class SQLite3DB(object):
"""A simple wrapper class for working with sqlite3 databases.
This wrapper class is intended to help si... |
32851ca38461cdc284e106dc600c104ac3b025d7 | bioright/Digital-Coin-Flip | /coin_flip.py | 1,231 | 4.25 | 4 | # This is a digital coin flip of Heads or Tails
import random, sys #Importing the random and sys modules that we will use
random_number = random.randint(1, 2)
choice = "" # stores user's input
result = "" # stores random output
def play_game(): # the main function that calls other function
instructions()
d... |
4c179675efe07d8d4038b9c65ad574768f8edaaf | agonzalezcas/stock-analyzer | /timeseries_plots.py | 1,767 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
from grab_data import extract_data
def time_series_format(ticker, column, ttm_remove=False):
'''
Grabs the entries from the full fundamentals data frame and arranges them
into individual time series
:param ticker: the ticker ... |
5de0fce01f094dd7f55707ec89980cd36a4d1870 | mittman/pycheckmate | /main.py | 3,640 | 3.609375 | 4 | #!/usr/bin/env python3
import os, sys, re
from Ai import Ai
from Board import Board
from File import File
from Game import Game
from Piece import Piece
from Player import Player
def interactive(ply):
g = Game()
mode, end = g.game_type()
end = int(end)
if mode: #mode is true means new game
player_x = Player('x... |
eb4a3b56b8e24198c202adf031ec1e17d4d89a48 | Skir131/programmers | /Level 1/2016년.py | 480 | 3.671875 | 4 | def solution(a, b):
day_list = ['SUN','MON','TUE','WED','THU','FRI','SAT']
month_list = [31,29,31,30,31,30,31,31,30,31,30,31]
today = 5
#5월이면 4월까지의 일수를 더한다.
for i in range(1, a):
today += month_list[i-1]
#1월 2일이라면 하루를 더한다. 즉, b일에 대해서 b-1만큼 더한다.
today += b-1
#7로 나누어서 요일을 확인한다.
... |
42774c57da2e11dfb598ec63ac3087f24377398a | Neftali56/Tarea_03 | /Datos_esfera.py | 978 | 3.9375 | 4 | #encoding: UTF-8
#Autor: Neftalí Rodríguez Martínez, A01375808.
#Entrega los datos de una esfera: Diámetro, Volumen y Área. Usamos pi de la la librería Math.
import math #Importamos librería math para después usar Pi.
def calcularDiametro(radio): #Calcula el diámetro de la esfera.
diametro = radio * 2
... |
94d3b518f7ff885e83e92f4ca5310cfcbcf1341e | aes6218/hw2-python | /main.py | 1,047 | 4.3125 | 4 | # Author: August Sanderson aes6218@psu.edu
def getGradePoint(grade):
if grade=="A" or grade=="A+":
p = 4.0
elif grade=="A-":
p = 3.67
elif grade=="B+":
p = 3.33
elif grade=="B":
p = 3.0
elif grade=="B-":
p = 2.67
elif grade=="C+":
p = 2.33
elif grade=="C":
p = 2.0
elif grade... |
44fcdc687efefece87b02fb04ea81d077e53a441 | vnimnualrat/GameProject | /MiniShooter/Project/src/bullet.py | 372 | 3.640625 | 4 | '''
Created on May 4, 2015
@author: LittleMonster
'''
import pygame
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load('images/bullet.png')
self.rect = self.image.get_rect()
def bulletspeed(self, y):
'Controls the spe... |
75ef4e060e49bbd1f9e9566596701beb530c9515 | Yoodahun/Practice-RESTAPITest-on-Python | /APIExample/JsonParsing.py | 748 | 4.03125 | 4 | import json
courses = '{"name" : "TestTest","languages": ["java","python"]}'
#Loads method parse json string and it returns dictionary.
jsonDictionary = json.loads(courses)
print(type(jsonDictionary))
print(jsonDictionary["languages"][1])
###########
#parse content in json file into dictionary
with open("exampleJ... |
4e726b21a217237a6cf2a73b964e68ccef28b0db | monicaihli/python_course | /misc/regex_demo.py | 2,458 | 3.734375 | 4 | # **********************************************************************************************************************
#
# File: regex_demo.py
#
# Author: Monica Ihli
#
# Date: January 27, 2020
#
# Description: Demonstrates the use of regular expressions on sample text.
#
# R... |
06cce767a23db504a677b6dda59f6afc74f680dd | monicaihli/python_course | /Feb-10_dicts-lists-tuples-sets/sets.py | 2,351 | 3.8125 | 4 | ######################################################################################################
# File: sets.py
# Date: Feb 10, 2020
# Author: Monica Ihli monica@utk.ed
# Description: Brief demo for sets. Step through with debug mode in PyCharm!
# Documentation: https://docs.python.org/3.8/library/stdtypes.html#... |
010b2079ad9e5d5b6d6e458b1b8ff6230f916731 | monicaihli/python_course | /Feb-10_dicts-lists-tuples-sets/lists.py | 3,507 | 4.5625 | 5 | #0#####################################################################################################
# File: lists.py
# Date: Feb 10, 2020
# Author: Monica Ihli monica@utk.ed
# Description: Demonstrates a variety of ways to create, use, and access lists.
##############################################################... |
83aeea4934c224bb313c05e567c398a5e00da6d6 | monicaihli/python_course | /misc/booleans_numbers_fractions.py | 1,091 | 4.21875 | 4 | # **********************************************************************************************************************
#
# File: booleans_numbers_fractions.py
#
# Author: Monica Ihli
#
# Date: Feb 03, 2020
#
# Description: Numbers and fractions in Python. Best results: use debugging to go t... |
954a9700bab0e724561934a8a6ef7049e79d7ffa | monicaihli/python_course | /Feb-19_csv-files-encoding/csv-module.py | 1,137 | 3.859375 | 4 | ###################################################################################################
# File: csv-module.py
# Date: Feb 19, 2020
# Author: Monica Ihli monica@utk.edu
# Description: Shows how to create csv file from list of dicts and to read a csv file
######################################################... |
1177eec490239d7194649507e3c4672bb191ae68 | MichaelDiBernardo/calisthenics | /bst/bst.py | 2,059 | 3.90625 | 4 | import unittest
class BinarySearchTree(object):
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def contains(self, item):
if self.value == item:
return True
if self._should_go_left(item):
... |
7dda75c52ab735158c9daa38fb3661284c19c98c | dillon-DL/PolynomialReggression | /PolynomialRegression/poly.py | 1,592 | 4.1875 | 4 | # Firstly the program will be using polynomial regression to pefrom prediction based on the inputs
# The inputs or variables we will be anlysing to study is the relation between the price and the size of the pizza
# Lastly the data will displayed via a graph which indicates the "non-linear" relationship between the 2... |
a63943db5fcb51f37ad30040070142285cd020da | Kuznetsova-28/101programmingtasks | /28.py | 481 | 4.15625 | 4 | Составить алгоритм и программу для реализации логических операций «И» и «ИЛИ» для двух переменных.
>>> x = input("значение x")
значение x
>>> a = input("значение a")
значение a
>>> c = input("значение c")
значение c
>>> if a > x and c < a or c > x :
print("получится четное значение")
else :
print("решения нет")
|
995c4c8ed3a4f7562bbadb5f608d1021b7103628 | Kuznetsova-28/101programmingtasks | /14.py | 407 | 3.734375 | 4 | Можно ли в квадратном зале площадью S поместить круглую сцену радиусом R так, чтобы от стены до сцены был проход не менее K?
>>> import math
>>> S = 78
>>> A = math.sqrt(S)
>>> K = 15
>>> R = 7
>>> D = R*2
>>> if A-D > K :
print("its possible")
>>> if A-D <= K :
print("its impossible")
its impossible
|
a73f814e169adda17f120107da36e02355dd1b07 | Kuznetsova-28/101programmingtasks | /#1.py | 749 | 3.53125 | 4 | Нарисуйте блок-схему к следующей задаче: Преобразовать дату в "компьютерном" представлении (системную дату) в "российский" формат,
т.е. день/месяц/год (например, 17/05/2009).
Python 3.6.3 (v3. 6. 3:2c5fed8, Oct 3 2017, 18:11:49) [MSC V. 1900 64 бит (AMD64)] на win32
Введите "copyright", "credits" или "license ()" для ... |
349deb5038abb67e5d3f96bd40e0110166b345b8 | DCapella/address-terminal | /address_terminal/controller_menu.py | 8,525 | 3.875 | 4 | import os
from address_book import AddressBook
def system_clear():
"""
Telling the terminal to clear the screen
"""
absolutely_unused_variable = os.system("clear")
def get():
"""
Getting input from the user
"""
return input(">> ")
class MenuController(object):
"""
Creating a n... |
398b530351c8e930761a2243e29a8ec4b109e622 | DamarisOrtizCornejo/Deber-1-Estructura | /Ejercicio 5.py | 403 | 3.875 | 4 | """Dado como dato la calificacion de un alumno en un examen, escriba "aprobado" si si calificacion es nayor o igual que 7 y "Reprobado" en caso contrario"""
class Ejercicio5:
def _init_(self):
pass
def run( ):
calf = float(input("Ingrese su calificacion: "))
if calf>=7:
print("Aprobado")
print("Felicidade... |
0f3cea206bedc824b602bca6abe3f01646c418af | DamarisOrtizCornejo/Deber-1-Estructura | /Ejercicio 18.py | 507 | 3.5625 | 4 | """Sea un vector “Calificaciones” de 100 componentes: En forma de columna se representaría así"""
class ejercicio18:
def __init__(self):
pass
def arreglo1(self):
calif = [ ]
for i in range(20):
dato = int(input("Ingrese el dato {}: "... |
413eadf2794c87f1de0d3d34ac3590f749fce654 | goodvubo/ML | /supervised/Linear Regression/linear_regression.py | 2,257 | 3.703125 | 4 | # Classification template
'''Importing the libraries'''
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
'''Importing the dataset'''
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, 0:4].values
y = dataset.iloc[:, 4].values
'''Encoding categorical data'''
'''Encoding the Independe... |
3bbce152cfecb8b6ac9e31223494e1f9ce21c68e | hspahic-cs/AdventOfCode | /2019/Day 1/ch_1.py | 432 | 3.78125 | 4 | '''
def count_words(filepath):
with open(filepath) as f:
input_lines = [line.strip() for line in f]
return ((input_lines))
print(count_words("ch1_input.txt"))
'''
def calculate_fuel(filepath):
with open(filepath) as f:
input_lines = [line.strip() for line in f]
sum = 0
for ... |
d6f112dc05a224aed24b15a50ee2177aaee58f82 | hspahic-cs/AdventOfCode | /2020/Day3/problem1.py | 1,009 | 3.625 | 4 | def readInput(filepath):
with open(filepath) as f:
input_lines = [line.strip() for line in f]
return input_lines
def numberTrees(input):
count = 0
iteration = 0
cur_x = -3
for i in input:
iteration += 1
cur_x += 3
cur_x %= (len(i))
if i[cur_x] == "#"... |
77537a9fcba18174176ad5618f6557d1d76545e8 | renukadeshmukh/Yelp-Dataset-Challenge-2015 | /2.Task_2_model_1/FeatureSelection.py | 3,716 | 3.515625 | 4 | import numpy as np
import csv
#import pandas as pd
"""
Name : Aniket Gaikwad
description : This file implements all Feature selection methods.
"""
class featureSelect:
def __init__(self):
self.colStat=None
self.selectedfeatures=None
def loadfeature(self,file):
print('\n Load Feature... |
3cfbf3ae546fe9692afffebce91b056ba2f69178 | tyrusheebhammer/AI1 | /local_search/stochastic.py | 922 | 3.96875 | 4 | # stochastic search chooses a random index in a position array and tests to see if that
# f(x) is the max. The advantage is you can choose the number of times you pull from an
# array, disadvantage is it non-deterministic as it isn't guaranteed to find the global
# maximum
import numpy as np
from random import randint... |
122c6b3283fb3c37c235b1451b15dd522e8cb124 | bitcraftlab/nodebox-examples | /nodebox-3/libraries/turtle.py | 1,464 | 4.09375 | 4 | """ turtle commands for nodebox 3 """
# @bitcraftlab 2017
from math import sin, cos
from nodebox.graphics import Point, Path, Color
from nodebox.util.Geometry import radians
# extending the path class of nodebox, so we can construct a path with turtle commands
class Turtle(Path):
def __init__(self, pos, dir):
... |
cd0a9bd22bedaca64e65db654566e319d81f5a69 | TriceG/DNA_Project | /DNA_Construction/Shape_Classes.py | 1,997 | 4 | 4 | # Make a class that creates dragable objects
class Circle():
def __init__(self, centerX, centerY, radius):
self.r = radius
self.x = centerX
self.y = centerY
def overCircle(self):
#cursor distance from circle centre is less than radius
#distance from from cursor to... |
0e55757b1762833ff73673bc95f4bcbd12ba6177 | manojakondi/geeks4geeksPractice | /diffBetweenDates.py | 663 | 4.1875 | 4 | """
Given two dates (can be of different years), calculate the number of days between them (taking care of leap years).
"""
dt1 = [1,2,2000]
dt2 = [1,2,2004]
daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def countLeapYearsFromDate(dt):
d = dt[0]
m = dt[1]
y = dt[2]
if (m>2):
... |
9b26b23cb3df5c00332cd6a1e943a3b2a0a9499f | injin/python-basic | /05. dictionary.py | 869 | 3.625 | 4 | # 사전에서는 키 중복 허용되지 않음
# 같은 값의 키로 추가하면 덮어 씌워지는 구조
cabinet = {3:"유재석", 100: "김태호"}
print(cabinet[3])
print(cabinet.get(3))
# print(cabinet[5]) # 프로그램 종료됨 5라는 키 없기 때문에
print(cabinet.get(5)) # 값이 없어도 오류 출력 안함
print(cabinet.get(5, "사용가능")) # 값이 없으면 기본값 출력
print(3 in cabinet) # 3이라는 키가 캐비넷이 있으면 True
# 새 손님
str_cabinet = {... |
3da5b463a2c3ab14b4c9b7d9c03a7a73d8f3fd01 | injin/python-basic | /01. python-basic.py | 2,441 | 3.90625 | 4 | # <1> 숫자형 자료형
print(5)
print(-10)
print(5+3)
# <2> 문자형 자료형
print("ㅋ"*10)
# <3> boolean 자료형
print(5<10)
print(True)
print(not True)
# <4> 변수
animal = "강아지"
name = "연탄이"
age = 4
hobby = "산책"
is_adult = age >= 3
print("우리집" + animal + "의 이름은 " + name + "예요")
#print(name + "는 " + str(age) + "살이며, " + hobby + "을 아주 좋아해요.... |
65a1e11d9eeed2caef7e0aa2fafdda7f8e98440a | matt24ck/matt24ck-ds1 | /any-prime.py | 222 | 3.828125 | 4 | #!/usr/bin/env python
n = input()
x = range(1, n + 1)
pot_factors = list(x)
y = []
for item in pot_factors:
if n % item == 0:
y.append(item)
if len(y) == 2:
print "prime"
else:
print "not prime"
|
cd9715cf2861992d82342cb06ae04c0bb93fbc89 | matt24ck/matt24ck-ds1 | /sum-five-abs.py | 136 | 3.765625 | 4 | #!/usr/bin/env python
m = 1
total = 0
while m != 0:
m = input()
if m < 0:
m = -1 * m
total = total + m
print total
|
9b71f60c0d22b97e6d7f5c1989f0221567804fc3 | matt24ck/matt24ck-ds1 | /above-average.py | 311 | 3.5625 | 4 | #!/usr/bin/env python
a = []
s = raw_input()
while s != "end":
a.append(int(s))
s = raw_input()
i = 0
total = 0
while i < len(a):
total = total + a[i]
i += 1
if len(a) > 0:
avg = float(total / len(a))
j = 0
while j < len(a):
if len(a) > 0 and a[j] > avg:
print a[j]
j += 1
|
3ff8ccfba17a72ff72eb3a6b4dda8356254494b0 | matt24ck/matt24ck-ds1 | /longer-of-two-strings.py | 124 | 3.78125 | 4 | #!/usr/bin/env python
str1 = raw_input()
str2 = raw_input()
if len(str1) > len(str2):
print str1
else:
print str2
|
23f44b64fbdcb0dba665ae236a22f9155ec7ced7 | matt24ck/matt24ck-ds1 | /fib-n.py | 92 | 3.515625 | 4 | #!/usr/bin/env python
n = input()
i = 0
m = 0
while i < n:
print i + i - 1
i = i + 1 |
0e62c39ef4d73bdba432673fff6ad181ffac71b0 | matt24ck/matt24ck-ds1 | /fib-less-than-n.py | 102 | 3.640625 | 4 | #!/usr/bin/env python
n = input()
i = 0
while i < n:
m = (i + 1) + i
print m + (m - 1)
i = i + 1
|
08964495fe4a63f9b35167238742afbc3ab7e04f | tslight/chopt | /chopt/ranges.py | 2,340 | 4.0625 | 4 | # Copyright (c) 2018, Toby Slight. All rights reserved.
# ISC License (ISCL) - see LICENSE file for details.
import re
def insert_range(element, inputs, options, nums):
'''
Remove element of original list that defines range, then insert integers in
the range of the first and last elements of a list creat... |
037311e057a9e417a5d458ee95046272942f6830 | ragnaroik/TIL | /baekjoon/silver4/1920.py | 3,612 | 4.0625 | 4 | # 1920. 수 찾기
# Silver 4.
# https://www.acmicpc.net/problem/1920
# MergeSort 써보려다가 시간이 길어져서 QuickSort 사용해봄.
# sort 방법에 익숙해질 수 있도록 하루에 한 번씩 작성해보려 함.
# binary search도 역시 익숙해지도록 작성해보려함.
import time
import random
# N = 100000
# M = 100000
# list_A = [random.randint(-2**30, 2**30) for _ in range(N)]
# check_list = [random.... |
c0716671192658a207afff37301e10943f612d75 | ianhuang96/Stout-Case-Study | /Analysis/case2/Case2.py | 6,706 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
from collections import Counter
import warnings
warnings.filterwarnings('ignore')
# In[2]:
data = pd.read_csv('casestudy.csv')
# In[3]:
# preview data
data.head(10)
# ## For each year we need the following information:<br... |
ac4b5be3c755dca75e1b12eee310a9652504d63d | ZhiqingWei/Robotics1 | /COMP0037_Q2/cleaning_robot_env.py | 7,912 | 3.6875 | 4 | #! /usr/bin/env python3
import random
import numpy as np
from robot_enums import Action
from robot_enums import State
# Transition dynamics for Q2 Coursework 1
# Fill out this class for Q2c. extended from Lab 2. The methods have been commented thoroughly.
# The BatterySimulator class simulates transitions of the ro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.