blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
6f6bbd2b187bec1993cfbcba769870b1ccb75f6a | dfranke01/conways_game_of_life_pygame | /conways_game_of_life.py | 27,374 | 3.8125 | 4 | import pygame, sys, numpy as np
import math
#from pygame.locals import *
'''
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells,
each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours,
which are the cells that are ... |
309c009372f668d3027e0bb280ae4f7f2d1920b3 | Matttuu/python_exercises | /find_the_highest.py | 473 | 4.1875 | 4 | print("Using only if sentences, find the highest number no matter which of the three variables has the highest one. To make it simpler, you can assume that the values will always be different to each other.")
print(".............")
print("a=1")
print("b=2")
print("c=3")
print(".............")
a = 1
b = 2
c = 3
if a >... |
56e7dfe8b8201bf8905cc832866cecf44b90cf52 | nicolascoco85/EjerciciosCFP34 | /juegosalternativos_TFL.py | 992 | 3.703125 | 4 | tirada=[3,3,3,3,1]
def ordenar_tirada(tirada):
#Comentario:
tirada_ordenada=sorted(tirada)
return tirada_ordenada
def esEscalera(tirada_ordenada):
tirada_ordenada=ordenar_tirada(tirada_ordenada)
if(tirada_ordenada==[1,2,3,4,5] or tirada_ordenada==[2,3,4,5,6]):
return True
else:
... |
2f7fbeddfcab9a812c16a49e59a15fe5d5cbdb85 | nicolascoco85/EjerciciosCFP34 | /cocacola.py | 672 | 3.6875 | 4 | import random
cantidad_limite_jugadores=21
cantidad_jugadores=int(input('Ingrese el numero de jugadores: '))
adivinar_numero= random.randrange(0,cantidad_limite_jugadores)
nombre= input('ingrese el nombre de jugador: ')
numero_elegido= int(input('Ingrese un numero: '))
lista=[]
turnos_jugados=1
while (numero_elegido!=a... |
49bc6ae3d693b2f8e6bc30969f65d3692fed1f91 | aimeewan/impl | /func.py | 4,458 | 4.09375 | 4 | '''
定义函数时,需要确定函数名和参数个数;
如果有必要,可以先对参数的数据类型做检查;
函数体内部可以用return随时返回函数结果;
函数执行完毕也没有return语句时,自动return None。
函数可以同时返回多个值,但其实就是一个tuple。
***定义默认参数要牢记一点:默认参数必须指向不变对象!如果是可变对象,程序运行时会有逻辑错误
参数:必选参数、默认参数、可变参数、关键字参数和命名关键字参数
'''
def add(numbers):
sum = 0
n = 1
for number in range(numbers):
sum = sum + number
... |
43e576f3ded0c011bfa1b693db98d05c7f3d4bf8 | Sezimm/vscode2 | /zadacha9.py | 109 | 3.65625 | 4 | def list_1(a,b):
i = []
i.append(a)
i.append(b)
print(i)
a = input()
b = input()
list_1(a,b) |
894e6b22de2183208e4182427a192bee55a65a22 | ykcai/Python_Programming | /homework/week10_test_answers.py | 1,159 | 3.96875 | 4 | # Question 1
# What is the output of the following program :
print("Hello World"[::-1])
# 1. dlroW olleH CORRECT
# 2. Hello Worl
# 3. d
# 4. Error
# Question 2
# Given a function that does not return any value, what value is shown when executed at the shell?
# 1. int
# 2. bool
# 3. void
# 4. None CORRECT
# Question 3... |
3df77e2d92eebe8f33515c01005e96215c1e8d04 | ykcai/Python_Programming | /homework/week4_homework.py | 1,691 | 4.3125 | 4 | # Python Programming Week 4 Homework
# Question 0:
# --------------------------------Code between the lines!--------------------------------
def less_than_five(input_list):
'''
( remember, index starts with 0, Hint: for loop )
# Take a list, say for example this one:
# my_list = [1, 1, 2, 3, 5, 8, 1... |
877cc9ad82cdcbedb04f7fe8bdf46b59b1f7377d | rashkov/aoc18 | /2/2.py | 1,128 | 3.5625 | 4 | file = open("./input.txt", "r")
all = []
twos_count = 0
threes_count = 0
for str in file:
all.append(str.strip())
char_counts = {}
for char in str.strip():
count = char_counts.get(char, 0)
char_counts[char] = count + 1
has_two = False
has_three = False
for x,y in char_counts.ite... |
f28ce6bcb95689c7244c3aacf89e275f353c4174 | 5tupidmuffin/Data_Structures_and_Algorithms | /Data_Structures/Graph/dijkstrasAlgorithm.py | 2,882 | 4.25 | 4 | """
Dijkstra's Algorithm finds shortest path from source to every other node.
for this it uses greedy approach therefore its not the best approach
ref:
https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
https://www.youtube.com/watch?v=XB4MIexjvY0
https://www.geeksforgeeks.org/... |
c6106fb9835745add93d51855cf41b780ff2a272 | 5tupidmuffin/Data_Structures_and_Algorithms | /Data_Structures/Linked_List.py | 2,388 | 4.03125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, value = None):
self.head = Node(value)
def insert_at_start(self, value):
new = Node(value)
new.next = self.head
self.head = new
def print(s... |
40af8890f93b44c087cebb7295c7eb49bfae775a | 5tupidmuffin/Data_Structures_and_Algorithms | /Data_Structures/Graph/bfs.py | 1,650 | 4.1875 | 4 | """
in BFS we travel one level at a time it uses queue[FIFO]
to counter loops we use keep track of visited nodes with "visited" boolean array
BFS is complete
ref:
https://en.wikipedia.org/wiki/Breadth-first_search
time complexity: O(|V| + |E|) or O(V^2) if adjacency matrix is used
space... |
ef0440b8ce5c5303d75b1d297e323a1d8b92d619 | AndreiBoris/sample-problems | /python/0200-numbers-of-islands/number-of-islands.py | 5,325 | 3.84375 | 4 | from typing import List
LAND = '1'
WATER = '0'
# TODO: Review a superior solutions
def overlaps(min1, max1, min2, max2):
overlap = max(0, min(max1, max2) - max(min1, min2))
if overlap > 0:
return True
if min1 == min2 or min1 == max2 or max1 == min2 or max1 == max2:
return True
if (min... |
126b47c9e7d367ee2fba3922a63dd067b5131f77 | AndreiBoris/sample-problems | /python/0581-shortest-unsorted-continuous-array/shortest-unsorted-continuous-array.py | 1,358 | 3.875 | 4 | import sys
from typing import List
class Solution:
'''
Given an integer array,
you need to find one continuous subarray that if you only sort this subarray in ascending order,
then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its ... |
b5a787e168800bafca488114a770fff8dfa1674b | jcochran206/GuessNumberGame | /guessNum.py | 1,166 | 4.03125 | 4 | #############################
# Title: Guess my Number Game
# created by Jonathan Cochran
# date 17 July 2019
#############################
import random
# Greeting
print("Hello. What is your name?")
name = input()
# random Number generated
secretNum = random.randint(1, 20)
print('Well ' + name + ' I am thinking of a ... |
20a9ba9f3d7ea006546e8a203463fef55f3abf47 | mchalek/euler | /solved/p169/p169.py | 863 | 3.78125 | 4 | #!/usr/bin/python
from sys import argv,exit
import subprocess
def base2(n):
if n == 0:
return []
z = 1l
p = 0
while z <= n:
z <<= 1
p += 1
z >>= 1
p -= 1
return [p] + base2(n - z)
def count(n):
powers = base2(n)
num_powers = len(powers)
intermediates = [... |
8166923e07735eed1f70085ea06c2da5f571d14d | mchalek/euler | /solved/p130/p130.py | 831 | 3.5 | 4 | def A(n):
k = 1
r = 1
while r < n:
r *= 10
r += 1
k += 1
z = r % n
while z != 0:
k += 1
z *= 10
z += 1
z %= n
return k
def getprimes(N):
iscomp = [False]*N
primes = []
for p in range(2, N):
if not iscomp[p]:
... |
8b9929e702be9141d0e1c9c5ca5b997045555179 | justinsloan/wordflash | /class_SettingsWindow.py | 25,762 | 3.609375 | 4 | # !/usr/bin/env python3
# class_settingWindow.py
# This module is part of the "Word Flash" program
from tkinter import *
from class_SelectStudentWindow import *
class SettingsWindow():
"""Provides GUI to change Word Flash settings."""
def __init__(self , master, settings):
"""Constructor for the clas... |
62c55d7147e1f06b7b9692751f0133f64d2ee752 | edunsmore19/Computer-Science | /Homework_Computer_Conversations.py | 1,174 | 4.21875 | 4 | # Homework_Computer_Conversations
# September 6, 2018
# Program uses user inputs to simulate a conversation.
print("\n\n\nHello.")
print("My name is Atlantia.")
userName = input("What is yours? \n")
type(userName)
print("I share a name with a great space-faring vessel.")
print("A shame you do not, " + userName + ".")
... |
7e6da290d3765a2223f4967df1a946ed6992eb2c | edunsmore19/Computer-Science | /Class_Work_More_List_Stuff.py | 524 | 3.78125 | 4 | ## In_Class_More_List_Stuff
## September 28, 2018
i = [[1,2,3], [4, 5, 6], [7, 8, 9]]
## Indicates, go to the first list [0] and grab the first number [0]
i[0][0]
i = [0 for x in range(12)]
## Create a list w/ 12 sets of 0
## You could use this to go in later and change it
j = [0]*12
print(j)
## You can create a li... |
c6bd53512252f2819483027102fbcb868b53ed26 | edunsmore19/Computer-Science | /Homework_Challenge_Questions/Homework_Challenge_Questions_1.py | 766 | 4.1875 | 4 | ## Homework_Challenge_Questions_1
## September 27, 2018
## Generate a list of 10 random numbers between 0 and 100.
## Get them in order from largest to smallest, removing numbers
## divisible by 3.
## Sources: Did some reasearch on list commands
import random
list = []
lopMeOffTheEnd = 0
## Generate the 10 random n... |
7a3a3a6ba236114a03f9a4345fcccddacb8f1892 | edunsmore19/Computer-Science | /Project_Adventure_Game.py | 17,858 | 4.125 | 4 | ## Project_Adventure_Game
## September 17, 2018
## User engages in an adventure-style game requiring the user to make
## choices that change the story.
## Honor Code: I have neither given nor recieved any unauthorized aid.
## 'title' clears terminal & presents title
def title():
#print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\... |
95eb45ad083a43ce1db7ffe5a2f47d0bd30b43c2 | edunsmore19/Computer-Science | /Homework_Monty_Hall_Simulation.py | 2,767 | 4.59375 | 5 | ## Homework_Monty_Hall_Simulation
## January 8, 2018
## Create a Monty Hall simulation
## Thoughts: It's always better to switch your door. When you first choose your door,
## you have a 1/3 chance of selecting the one with a car behind it. After a door holding
## a penny is revealed, it is then eliminated. If you sw... |
e42d64e87a4d0c7d655c0085ff1917ab65b986a1 | raghuveerls/Ncorr-Python-EditedCode | /Edited code/ncorr_functions.py | 28,031 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on Tue Apr 2 17:35:38 2019
@author: raghuveer
'''
#%%
# =============================================================================
# User chooses the images to perform DIC on
# =============================================================================
d... |
cebc7f229d48eef5fd306cecc44adff9a5583875 | rjalic/django-uni-project | /main/utils.py | 1,496 | 3.578125 | 4 | def enough_ects_available(student, subject, selected_semester):
"""
Checks if the student has enough ects available in the selected semester.
"""
enrollments = student.enrollment_set.all()
ects_earned = subject.ects
for enrollment in enrollments:
if student.status == 'FULL_TIME' and enrollment.subject.... |
5c6bef8cbb2cedbe941c60e204c2bf04098c6179 | cement-hools/algoritms | /14_sprint/g_perimeter_of_the_triangle.py | 296 | 3.96875 | 4 | def max_perimeter(arr):
arr.sort()
while len(arr) > 2:
c = arr.pop()
a = arr[-1]
b = arr[-2]
if c < a + b:
perimeter = a + b + c
return perimeter
return -1
x = [int(i) for i in '5 3 7 2 8 3'.split()]
print(max_perimeter(x))
|
88e47c5e825618255d41de25eff446604e3c6b4e | cement-hools/algoritms | /14_sprint/f_sort_by_parity.py | 1,344 | 3.875 | 4 | # Кондратий издал новый закон. Во всех списках четные числа должны стоять на четных позициях,
# а нечетные числа - на нечетных. Уже существующие списки придется пересортировать.
# В списках, которые вам достанутся, одинаковое количество четных и нечетных элементов.
# Нужно отсортировать его в соответствии с новым закон... |
e6ee754c36482ed7f29205e50a39a2e68eb2566b | cement-hools/algoritms | /13 sprint/G.spiral.py | 313 | 3.703125 | 4 | m = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
n = 1
k1 = 0
k2 = -2
n1 = len(m[0]) - 1
n2 = -n1
while n <= len(m) ** 2:
for i in range(k1, n1):
print(m[k1][i])
for i in range(k1, n1 + 1):
print(m[i][n1])
for i in range(k2, n2, -1):
print(m[i][])
n += 1
|
ce2381670cdcfcddc0dc7abf70f0d9e17ba2acf1 | cement-hools/algoritms | /14_sprint/final/a_large_number_bubble.py | 597 | 3.78125 | 4 | # id 45812420
def large_number(numbers_arr):
if not numbers_arr:
return '0'
numbers = list(map(str, numbers_arr))
for i in range(len(numbers)):
for j in range(len(numbers) - i - 1):
if numbers[j] + numbers[j + 1] < numbers[j + 1] + numbers[j]:
numbers[j], number... |
040af79caa43ecd9bf6bba40819d7f86faec5cc3 | DYNAMIC-DENOM/python | /dictionary.py | 408 | 3.921875 | 4 | customer={"name":"debanjan das mandal",'ph_no':"938752410","address":"balaramdihi"}
print(customer["address"])
for x in customer:
print(x,"-",customer[x])
# customer={"name":"debanjan das mandal",'ph_no':"938752410","address":"balaramdihi"}
print(customer)
customer["email"]="ddm2001.jgm@gmail.com"
print(cust... |
c46dafb8976c6c65f94f1dcdbe2bc7379311cbee | DYNAMIC-DENOM/python | /function3A.py | 136 | 3.71875 | 4 | def add(a,b):
return(a+b)
x=add(5,5)
print(x)
print(add(5,5))
def add2(a,b):
print(a+b)
add2(5,6)
print(add2(5,6))
|
ad57eac163f7d8f369185c0956eeeb5422c65a76 | a-x-/flask_table | /examples/simple.py | 1,039 | 3.875 | 4 | from flask_table import Table, Col
"""Lets suppose that we have a class that we get an iterable of from
somewhere, such as a database. We can declare a table that pulls out
the relevant entries, escapes them and displays them.
"""
class Item(object):
def __init__(self, name, description):
self.name = n... |
36c0e9d1a83e4a2c2c57286bb80c57e62d87d4d3 | garrrth/m269 | /Chapter1/fraction.py | 3,983 | 3.609375 | 4 | class Fraction:
def __init__(self, top, bottom):
if not isinstance(top, int):
raise TypeError(str(top)+" is not of type Integer")
if not isinstance(bottom, int):
raise TypeError(str(bottom)+" is not of type Integer")
if bottom < 0:
top = top*-1... |
f192e797cab3f4c72d5b1a3d97a2c95818325a77 | Muirgeal/Learning_0101_NameGenerator | /pig_latin_practice.py | 982 | 4.125 | 4 | """Turn an input word into its Pig Latin equivalent."""
import sys
print("\n")
print("Welcome to 'Pig Latin Translator' \n")
VOWELS = 'aeiou'
while True:
original = input("What word would you like to translate? \n")
print("\n")
#Remove white space from the beginning and the end
orig... |
e5f7c935d8e552dda797b126dec06e853beb2703 | HenCor2019/numerical-analysis | /derivation.py | 519 | 3.59375 | 4 | from math import factorial, atan, pi, asin, sin, log
def combination(m, n):
return factorial(m) // (factorial(n) * factorial(m - n))
def f(x):
return log(x)
def derivation(x, n, h):
sum = 0
for i in range(0, n+1):
sum += combination(n, i)*f(x+(n-i)*h) * (-1)**i
print(sum/h**n)
def c... |
764cb7d9f49e79a6435293b45f41cf6580beb6be | SwarajyaRBhanja/advancedPython | /handlingException.py | 269 | 3.890625 | 4 |
try:
a= int(input("Please enter a number not equals to zero: "))
print(45/a)
except ZeroDivisionError as e:
print(f"You fucking asshole entered zero.")
print(e)
except ValueError as e:
print("You fucker didn't enter any number")
print(e)
|
e270e1fe5d6402f34df808658faf0fb340097372 | SwarajyaRBhanja/advancedPython | /lambdaFunc.py | 217 | 3.8125 | 4 |
#lambda: functions created using an expression using lambda keyword
#syntax: lambda arguments: expressions
x= int(input("Please enter a number"))
y=lambda l:l+5
cal= lambda m,n,p: m+n-p
print(y(x))
print(cal(8,5,2)) |
a06ba022b0bc8353361e1bc73cec94512ec950c1 | SwarajyaRBhanja/advancedPython | /list_comprehension.py | 355 | 3.640625 | 4 | a= [2,4,7,8,9,23,54,61,72,18]
#tradition approach
'''
b= []
for i in a:
if i%2==0:
b.append(i)
'''
b=[i for i in a if i%2==0]
print(b)
#list comprehension is an elegant way to create list based on existing list.
c=[k for k in a if k>20]
print(c)
x= [3,5,6,8,4,12,4,7,8,3,7,8]
print({y for y in x}) #pri... |
d21a01f3f33d84b4bdf9ef3ddf4ed9c0e6dcda69 | aeeilllmrx/algorithms | /simple_BST.py | 3,058 | 3.8125 | 4 |
class BST():
def __init__(self, root, parent=None):
self.root = root
self.left = None
self.right = None
self.parent = parent
def insert(self, val):
if val > self.root:
if not self.right:
self.right = BST(val, self)
else:
... |
648bffa03e8cb303367f2f601c67bbd5ef833aa0 | ildar-band/zernovaiv | /p2/for.py | 319 | 3.71875 | 4 | smth_list = [2, 456, "dfgdfg"]
smth_string = "somestring"
smth_dict = {'1':'dfd', '2':'4', '3':'8gj', '4':"gdfg6"}
smth_tutle = ('2',"3f")
def print_smth_by_for(smth):
for i in smth:
print(i)
print_smth_by_for(smth_list)
print_smth_by_for(smth_string)
print_smth_by_for(smth_dict)
print_smth_by_for(smth_tutle) |
d2fd79954de75caa73b7db9935ac649a909a4b4a | ildar-band/zernovaiv | /p2/while_task.py | 187 | 3.609375 | 4 | Name_list = ['Вася', 'Маша', 'Петя', 'Валера', 'Саша', 'Даша']
while Name_list[] != 'Валера':
Name_list[] += Name_list[]
Name_list.pop(['Валера']) |
acf50a0cb1d79ae87580f690daa7ada18c1f9d0a | hychoi99/nahchoina | /linesegment.py | 2,630 | 3.5 | 4 | import math
#import pygame
from vector import Vector
class LineSegment:
def __init__(self,p1,p2):
#make copies of incoming vector points
self.p1 = Vector(p1.x,p1.y)
self.p2 = Vector(p2.x,p2.y)
# def draw(self,window):
# pygame.draw.line(window,pygame.color.Color("red"),(int(sel... |
ef83b85579d8a3328098ac7a45a821f39f08bbd8 | NicholasBaxley/My-Student-Files | /P4T1b_Baxley.py | 813 | 3.546875 | 4 | import turtle
window = turtle.Screen()
window.bgcolor("black")
letterN = turtle.Turtle() #Letter N's properties
letterN.pensize(4)
letterN.color("red")
letterN.left(90) #Letter N's Movement
letterN.forward(50)
letterN.right(154)
letterN.forward(56)
letterN.left(154)
letterN.forward(50)
le... |
b6258eec43be05516943ba983890e315cce167ae | NicholasBaxley/My-Student-Files | /P3HW2_MealTipTax_NicholasBaxley.py | 886 | 4.25 | 4 | # CTI-110
# P3HW2 - MealTipTax
# Nicholas Baxley
# 3/2/19
#Input Meal Charge.
#Input Tip, if tip is not 15%,18%,20%, Display error.
#Calculate tip and 7% sales tax.
#Display tip,tax, and total.
#Ask for Meal Cost
mealcost = int(input("How much did the meal cost? "))
#Ask for Tip
tip = int(input('How... |
92460ff7427ae5b5e2ff39fbefd9e60c282b4614 | HmAbc/deeplearning | /chapter3/step_function.py | 606 | 3.859375 | 4 | #!/user/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
# 阶跃函数简单实现,但是只支持实数
# def step_function(x):
# if x > 0:
# return 1
# else:
# return 0
# 重新编写函数,使之支持numpy数组
def step_function(x):
y = x > 0
return y.astype(np.int)
# 画出阶跃函数图像
# x = np.ara... |
a6d4bf1e71c3cfb431e3a7519185a474837cd5ae | bcbabrich/CS682FinalProject | /graphing_utilities.py | 462 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Note that this only graphs the first two dimensions of points
def print_graph_of(points, width, height, title) :
#plt.plot(samples[0], samples[1:])
print('points',points)
# only use the first two elements of each tuple in points
samples = [(p[0],p[1]... |
7853a9ecea62dc22a5e80b7dbbda7fbf8b9c185f | eburnsee/python_2_projects | /icon_manipulation/icon_manipulation.py | 1,999 | 4.28125 | 4 | def create_icon():
# loop through to make ten element rows in a list
for row in row_name_list:
# loop until we have ten rows of length 10 composed of only 1s and 0s
while True:
# gather input
row_input = input("Please enter ten characters (zeros and ones only, please!) for row " + row + ": ")
# check if ... |
054944acb3b88176810301cb23a89b914daaeff3 | thispassing/poker | /ad.py | 525 | 4.09375 | 4 | # importing datetime and defining current date
from datetime import datetime
today = datetime.now().strftime("%Y-%b-%d")
# making definition for new balance
def calculate(totalBalance):
chop = 600000
tax = 218543
newBalance = totalBalance - chop - tax
newBalance = "{:,}".format(newBalance)
return... |
b13693190db7f419aade15f06453cc34969dd0ff | user0198/TicTacToe | /main.py | 3,521 | 3.84375 | 4 | board = [' ' for x in range(10)]
def insertLetter(letter, pos):
board[pos] = letter
def paintBoard(board):
print(" 1 | 2 | 3\n 4 | 5 | 6\n 7 | 8 | 9\n")
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print('-' * 11)
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
pri... |
7051f4cb5c83925557a76d709dff901e4491764d | skyexx/tutorials | /tensorflowTUT/tf5_example2/full_code.py | 1,665 | 3.5625 | 4 | # View more python tutorial on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
... |
25c661b755b33c05f95398c15b258d186db9f3fe | PatchesPrime/dailyprogrammer | /344.py | 737 | 3.515625 | 4 | def b_n(integer):
data = [x for x in bin(int(integer))[2:].split('1') if x != '']
# Even though b_0 should be 0...The wiki says it's always 1..so..
if integer == 0:
return 1
for x in data:
if len(x) % 2 != 0:
return 0
return 1
# All should be true.
print('Test 1: ', b... |
e5523dc99c2287fb7b3343dc8da70cb5ce99b9e5 | anandabhaumik/PythoncodingPractice | /NumericProblems/FibonacciSeries.py | 1,063 | 4.25 | 4 | """
* @author Ananda
This is one of the very common program in all languages.
Fibonacci numbers are used to create technical indicators using a mathematical sequence
developed by the Italian mathematician, commonly referred to as "Fibonacci,"
For example, the early part of the sequence is 0, 1, 1, 2, 3, 5, 8, 13, ... |
475406a77d591cd63b13d2c1c1a9eb16eb2beefb | dmvdatascience/Python_Advanced | /scripts/run_EDA.py | 1,066 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 10:09:36 2019
@author: GrantDW
"""
def run_EDA(dataset):
'''
run_EDA takes a PANDAS dataframe and performs exploratory data analysis on it,
in order to determine strengths, weaknesses, and simple relationships between
the various columns.
... |
eac4c77c3d615b332842d428e2791ed4dffef607 | liu666197/data1 | /8.14/12 sorted和filter和匿名函数的练习.py | 682 | 3.71875 | 4 | a = [
{'name': 'aa','age': 80},
{'name': 'zs1','age': 30},
{'name': 'aasd32','age': 50},
{'name': 'zs12','age': 10},
{'name': 'zsaqew','age': 20},
{'name': 'zs213','age': 100},
{'name': 'zswer','age': 3}
]
# 1.使用def的函数的方式,取出大于20的数据,并且从小到大排序
def f(n):
return n['age'] > 20
def f1(n):
... |
f07558a321caa87cf7795ec4e6f52f4222cbf256 | liu666197/data1 | /8.7/11 字符串的方法.py | 1,960 | 4.03125 | 4 | a = 'hello world hello aaa'
# a += '1'
# print(a)
# 查
# 查找字符串出现的次数
# result = a.count(' ')
# 查找字符串的下标: 默认查找到第一个的下标 (查找不到报错)
# result = a.index('worlds')
# 从右往左查
# result = a.rindex('hello')
# 查找不到为-1,不会报错
# result = a.find('hello')
# 从右往左查
# result = a.rfind('hellso')
# print(result)
# 内容替换(默认全部替换)
# b = a.replace('he... |
1222b9eb56a8c6b728eb9a1f4aecb01a3671873f | liu666197/data1 | /8.24/05 操作数据库(插入).py | 455 | 3.578125 | 4 | import pymysql
# 1.连接数据库
# db: database
db = pymysql.connect('localhost','root','','python')
# 生成数据库的游标对象: 操作数据库
cursor = db.cursor()
# sql(最好是双引号,防止符号冲突)
sql = "INSERT INTO people (name,sex,age,height) VALUES ('小红','女',20,170);"
# 执行sql
cursor.execute(sql)
# 如果不想再对数据库进行操作,提交操作(后面不再进行操作)
db.commit()
# 关闭数据库
db.close(... |
f9530bf73c1668d0959482929534666e2f4c37af | liu666197/data1 | /8.5/03 if..elif.py | 797 | 3.859375 | 4 | # 7.成绩等级:
# 90分以上: 等级为A
#
# 80-90: 等级为B
#
# 60-80: 等级C
#
# 0-60: 等级为D
score = int(input('输入成绩: '))
if score >= 90:
print('A')
elif score >= 80: # score < 90
print('B')
elif score >= 60: # score < 80
print('C')
else: # 前面条件都不成立的时候执行的代码
print('D')
holiday_name = input('输入名称: ')
if holiday_name == '情... |
8d151d4c512430e54049ad733e8242b9357cac18 | liu666197/data1 | /8.6/02 思考.py | 3,616 | 3.890625 | 4 | # 1.输出9行内容,第1行输出1,第2行输出12,第3行输出123,以此类推,第9行输出123456789
#
# 1
# 12
# 123
# 1234
# 12345
# 123456
# 1234567
# 12345678
# 123456789
# 输出123
# print(1,end='')
# print(2,end='')
# print(3,end='')
# num = 1
# while num <= 3:
# print(num,end='')
# num += 1
# # 单独的换行
# print()
#
# # 输出123456
# num = 1
# while num <= 6... |
4250526ddb411f7edb10ec180f2a57ccb11a20e1 | liu666197/data1 | /8.10/04 字母排序.py | 960 | 3.703125 | 4 | # - 去除a字符串内的数字后,请将该字符串里的单词重新排序(a-z),并且重新输出一个排序后的字符串。(保留大小写,a与A的顺序关系为:A在a前面。例:AaBb)(难)
a = 'aAsmr3idd4bgsBB7Dlsf9eAF'
s = ''
for i in a:
if i.isalpha():
s += i
result = ''
# chr(): 将数字转化为字母
# 输出所有的大写字母
for i in range(65,91):
# 所有的大小写字母
# chr(i): 大写字母
# print(chr(i),chr(i + 32))
upper = chr(i)... |
950782aac6208f196cffe275215307c79d2a2121 | liu666197/data1 | /8.14/02 对象与global.py | 371 | 3.75 | 4 | # 只要将对象赋值了,那么就会开辟新的空间来存储对象
# a = []
# # 是否属于改变了a变量的值??? 都不是改变了a的值
# a.append(1)
# a[0] = 2
# print(a)
# b = []
# print(id(a),id(b))
# a存储的是列表的内存地址
a = [10,20,30]
b = 20
def sayHello():
global b
b = 30
a[0] = 100
print(b)
sayHello()
print(b)
print(a) |
30631e0c883005e305163f0292ac0b9b916aa77b | davejlin/py-checkio | /roman-numerals.py | 2,444 | 4.125 | 4 | '''
Roman numerals come from the ancient Roman numbering system.
They are based on specific letters of the alphabet which are combined to signify
the sum (or, in some cases, the difference) of their values.
The first ten Roman numerals are:
I, II, III, IV, V, VI, VII, VIII, IX, and X.
The Roman numeral system is dec... |
6db7ad876f33ee75bdd744eb81ea35980578702d | pdawson1983/CodingExcercises | /Substring.py | 1,316 | 4.15625 | 4 | # http://www.careercup.com/question?id=12435684
# Generate all the possible substrings of a given string. Write code.
# i/p: abc
# o/p: { a,b,c,ab,ac,bc,abc}
"""begin
NOTES/DISCUSSION
All substrings is not the same as all combinations
Four distinct patterns comprise all substrings
1. The original string
2. Each ch... |
02f6c73590057ce02829cc26699f7b178febb272 | ambingham/CharacterCreator | /race.py | 2,029 | 3.75 | 4 | class Race(object):
"Base class for all races in the game."
def __init__(self, name):
self.name = name
def apply_bonus(self, abilities):
"""Apply racial bonuses to abilities.
By default we do nothing. Subclasses should apply the appropriate bonuses.
"""
re... |
f5fe8e967cb841bb73315e829c06e63b945c3db4 | kktkyungtae/TIL | /Algorithm/2019.01/2019.01.24/Practice/09_if흐름제어3.py | 500 | 3.53125 | 4 |
# 다음의 결과와 같이 입력된 영어 알파벳 문자에 대해 대소문자를 구분하는 코드를 작성하십시오.
AA = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
aa = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
xx = str(input())
if xx in aa:
print... |
7c1fcb958198e808d5536af91dc6a96a2cceceaa | kktkyungtae/TIL | /Algorithm/2019.02/2019.02.20/수식문자열.py | 429 | 3.515625 | 4 | str = "2 + 3 * 4 / 5"
stack = [0] * 10 # make stack
top = -1 # what does mean?
idx = 0
post_exp = [0] * 10 # ?
for i in range(len(str)):
if '*' <= str[i] <= '/': # <= ?
top += 1;
stack[top] = str[i]
elif '0' <= str[i] <= '9': # <= ?
post_exp[idx] = str[i]
idx += 1
while top !=... |
8a0b153b49de241983f9c99b3202f2eef4f0f460 | kktkyungtae/TIL | /Algorithm/2019.01/2019.01.24/Practice/15_흐름과제어3.py | 249 | 3.65625 | 4 | #1부터 100사이의 숫자 중 3의 배수의 총합을 for 문을 이용해 출력하십시오.
ssum = []
for i in range(100):
if i % 3 ==0:
ssum.append(i)
print(f'1부터 100사이의 숫자 중 3의 배수의 총합: {sum(ssum)}') |
aa43873c181385d0eee5e86cb0a18691e3b0bc90 | Vimala390/Vimala_py | /sam_file_exer_2.py | 185 | 3.5 | 4 | file = open('C:/Users/Vimala_Revanuru/Desktop/sam_demo_1.txt','r')
x = 'deno'
for line in file:
if x in line:
print('word found ..')
else:
print('Not Found ..')
|
0f24831b7a41e57fab0accc5a9c7c1fdd1ef9bb5 | Vimala390/Vimala_py | /sam_string_concatinate.py | 1,065 | 3.6875 | 4 | stg1 = 'good'
stg2 = 'morning'
stg4 = 'Hey';stg5 = 'Vimala'
stg3 = stg1+" " +stg2
print(stg3)
print('{} {}!! {} {}...'.format(stg4,stg5,stg1,stg2))
str6 = ' Vimala '
print(str6.lstrip())
print(str6.rstrip())
print(str6.strip())
# Reverse Each word in the string [Eg. Have a great day O/p - evaH a taerg yad]
str_... |
5517280b78495d7c131208e78b3d2667165c8337 | Vimala390/Vimala_py | /sam_tuple_exe.py | 268 | 4.4375 | 4 | #Write a program to modify or replace an existing element of a tuple with a new element.
#Example:
#num= (10,20,30,40,50) and insert 90.
#Expected output: (10,20,90,40,50)
lst = [10,20,30,40,50]
lst[2] = 90
print(lst)
lst1 = tuple(lst)
print(lst1)
print(type(lst1))
|
d08e9df1d2a2ad3f72ab08121d76a736f55ef50a | Vimala390/Vimala_py | /sam_pandas_diff_ways_dataframe.py | 1,269 | 3.734375 | 4 | #Different ways of creating Data Frame
#1. Using CSV
import pandas as pd
df = pd.read_csv('C:\\Users\\Vimala_Revanuru\\Desktop\\sample_data.csv')
print(df)
#2.using Excel
#the latest version of xlrd (2.0.1) only support .xls files.
#so this error can be solved by installing an older version of xlrd.
#use commands bel... |
5dac67653c8a391c92e89fdcbc774b92fb363ab7 | Vimala390/Vimala_py | /sam_files_exer_0211.py | 1,186 | 3.953125 | 4 | # Write a program to count number of lines, words and characters in a text file.
file = 'C:/Users/Vimala_Revanuru/Desktop/sam_demo_1.txt'
c_lines = 0
c_words = 0
c_chars = 0
for lines in open(file,'r'):
c_lines+=1
print(lines.split())
#print(len(lines))
for char in lines:
if char != ' ... |
f8a214a1ca38f93aa8957b070298f74a4796ae30 | rajeevraizada/rajeevraizada.github.io | /Python/interactive_one_sample_t_test.py | 13,851 | 4 | 4 | ### Interactively plot points
### to show the one-sample t-test of the y-values, against zero.
### By Rajeev Raizada, Jan.2011.
### Requires Python, with the Matplotlib, NumPy and SciPy modules.
### You can download Python and those modules for free from
### http://www.python.org/download
### http://numpy.org
### http:... |
950474b740e8f54001b7b6aad2ed84d330a1ccc2 | BethGranados/Snake | /actor.py | 978 | 3.5 | 4 | import pygame
class actor:
size = (10, 10)
cord = (40, 40)
#Creates the actor and defined it's location at [XCord, YCord]. Adds a sprite to the actor.
def __init__(self, xCord, yCord):
self.cord = (xCord, yCord)
self.image = pygame.Surface(self.size).convert()
self.image.blit(pyg... |
ab9dab533973cfefe9d41cb53edfcf52c9e14d6a | Vetarium/ICT | /task1/3.py | 199 | 4.125 | 4 |
length = float(input("insert length"))
height = float(input("insert height"))
units = input("Insert units 'M' for meters and 'F' for feet")
print("area is ", height * length, units)
|
4aee5242a8c02f907643377d4f681aec4e4b5db9 | Vetarium/ICT | /task2/14.py | 238 | 3.625 | 4 | #largest cnt
import numpy as np
a = []
x = 1;
cnt = 0
while x!=0:
x = int(input())
a.append(x)
max = np.max(a)
print("biggest val is ",max)
for i in range (len(a)):
if max == a[i]:
cnt+=1
print("cnt is ", cnt)
|
8df20e0b38901d8ee203ed514b8473f994d22b69 | Vetarium/ICT | /task3/7.py | 291 | 3.640625 | 4 | import string
n = int(input())
s = input()
ans = list(set(s.lower()))
cnt = 0
arr1 = list(string.ascii_lowercase)
arr2 = list(string.ascii_uppercase)
for i in range(0, len(ans)):
if ans[i] in arr1 or ans[i] in arr2:
cnt += 1
if cnt == 26:
print("YES")
else:
print("NO") |
386217dd14ebfff63ef8aa7da1a94673b29602c7 | Vetarium/ICT | /task1/33.py | 240 | 3.890625 | 4 | loaves = int(input("Amount of loaves: "))
price = loaves*3.49
discount = price*0.6
total_price = price - discount
print("Regular price of the bread", round(price,2))
print("Value of discount:", discount)
print("Total price:", total_price) |
517c815b16824d9b4afcfc6ae21d9d151d2d1b17 | Vetarium/ICT | /task4/128.py | 281 | 4.09375 | 4 | def reverselookup(dict, val):
keys = []
for k in dict:
if dict[k] == val:
keys.append(k)
return keys
def main():
test = {"Aron":"true", "apple": "false"}
print(reverselookup(test, "false"))
print(reverselookup(test, "1.5"))
main()
|
912fd07e9a2103ebcdbc756c74d30044b949219c | Vetarium/ICT | /task2/1.py | 228 | 3.984375 | 4 | x1 = int(input("Insert the 1st row "))
y1 = int(input("Insert the 1st column "))
x2 = int(input("Insert the 2nd row "))
y2 = int(input("Insert the 2nd column " ))
if x1 == x2 or y1 == y2:
print("Yes")
else: print("NO") |
16bae5c5127f2b9f8121d1e5e042213ff9590619 | Vetarium/ICT | /task2/10.py | 100 | 3.859375 | 4 | #Qvadraty
a = int(input("Insert the number "))
i = 1;
while i**2 < a:
print(i**2)
i+=1
|
2b9abcbc4e7a19d9f1342b751df2e265e04d2c85 | byunghun-jake/udamy-python-100days | /day-27-Tkinter, args, kwargs and Creating GUI Programs/miles_to_kilometer_converter.py | 1,056 | 4 | 4 | import tkinter
# 텍스트 변환
def convert():
# 입력한 마일 텍스트 받아오기
try:
mile_num = float(miles_input.get())
km_num = mile_num * 1.609
except ValueError:
km_num = "숫자를 입력하세요."
# result 값으로 출력
km_result_label.config(text=km_num)
# window
window = tkinter.Tk()
window.title("Mile to ... |
395ac484f9d152f4ae29642aa6d56d10009ddbd1 | byunghun-jake/udamy-python-100days | /day-24-Files, Directories and Paths/main.py | 296 | 3.53125 | 4 | # file = open("my_file.txt")
# print(file)
# contents = file.read()
# print(contents)
# file.close()
# with open("/new_file.txt", mode="w") as file:
# file.write("Hi Root Directory")
with open("../../../../new_file.txt") as file:
contents = file.read()
print(contents)
|
67a0abe7c6122f23aca8443c3462cf29ced761db | byunghun-jake/udamy-python-100days | /day-17-start/main.py | 545 | 3.6875 | 4 | class User:
# Constructor
def __init__(self, user_id, user_name, follower=0, following=0):
print("new user being created...")
self.id = user_id
self.username = user_name
self.followers = follower
self.following = following
def follow(self, user):
user.followe... |
60cebb65097a49a1c55af2ab49483e149d6cd4db | byunghun-jake/udamy-python-100days | /day-26-List Comprehension and the NATO Alphabet/Project/main.py | 469 | 4.28125 | 4 | import pandas
# TODO 1. Create a dictionary in this format:
# {"A": "Alfa", "B": "Bravo"}
data_frame = pandas.read_csv("./nato_phonetic_alphabet.csv")
# data_frame을 순환
data_dict = {row.letter:row.code for (index, row) in data_frame.iterrows()}
print(data_dict)
# TODO 2. Create a list of the phonetic code words from... |
f53841acf1cb763d104ba43f0a961344d06d2710 | yucongo/data | /untokenize.py | 1,277 | 3.546875 | 4 | '''
https://stackoverflow.com/questions/21948019/python-untokenize-a-sentence
see also moses_detoken_memo.py
from nltk.tokenize.moses import MosesDetokenizer
text_ = ['Pete', 'ate', 'a', 'large',
'cake', '.', 'Sam', 'has', 'a', 'big', 'mouth', '.']
' '.join(MosesDetokenizer().detokenize(text_))
'''
import re
# f... |
319d0abd856cbcd9c403f08ec46545d389a59a4f | VennelaMittapalli/DSP-lab-programs | /linear_algebra.py | 809 | 4.03125 | 4 | #linear algebra applications
import numpy as np
print "..........OPERATIONS ON SINGLE ARRAY......."
a=input("Enter the matrix:")
b=np.array(a)
arr=[np.linalg.matrix_rank(a),np.linalg.matrix_power(a,3),np.trace(a),np.linalg.det(a),np.linalg.inv(a),np.linalg.eig(a),np.diag(a)]
r=["rank","power","trace","determinant","inv... |
0e6df6cd389e9e31b4b139b573263d6498d80acc | AJITHARUN/programs | /palindrome.py | 359 | 4.0625 | 4 |
def first (word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def pali(word):
if len(word)<=1:
print 'it is a palindrome'
elif first(word)==last(word):
return pali(middle(word))
print 'it is a palindrome'
else:
print 'it is n... |
e7b4b5005b97803c1f42942fd1d1f87db068e935 | Mayank133/Python-projects | /hangman.py | 3,109 | 4.03125 | 4 | import random
import data
print("Welcome to the Hangman game")
name=input("What is your name?")
print("Hey {}! Welcome to the game, you will be given clues and you have to guess the word. You'll get only 3 chances to guess the word.".format(name.upper()))
response=input("Are you ready to play! Yes or No? ")
count... |
9c0f99f8deea5f4f1f38d737a0e04ee8ad066042 | SimonTrux/DailyCode | /areBracketsValid.py | 1,006 | 4.1875 | 4 | #Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced.
#Every opening bracket must have a corresponding closing bracket. We can approximate this using strings.
def isBraces(c):
return c == '(' or c == ')'
def isCurly(c):
retu... |
4a15901e10a18f3ae66da9e76e2ed1cd87b41c23 | benmahdjoubi/coffee-machine-simulator | /Coffee Machine/main.py | 4,712 | 4.1875 | 4 | from sys import exit
class CoffeeMachine:
"""
The coffee machine have 400 ml of water, 540 ml of milk,
120 g of coffe beans, 9 disposable cups, $550 in cash.
"""
water = 400 # in ml
milk = 540 # in ml
beans = 120 # in g
cups = 9
money = 550 # in $
def __... |
a27729c3e9533a9634e57588caec48d8d438ff01 | haldous2/coding-practice | /ctci_16.19_pond_sizes.py | 4,170 | 4.15625 | 4 | """
You have an integer matrix representing a plot of land,
where the value at that location represents the height above sea level.
A value of zero indicates water.
A pond is a region of water connected vertically, horizontally, or diagonally.
The size of the pond is the total number of connected water cells.
Wri... |
2490aefc407cc5604b6c82f2afcec2f4c515e2f9 | haldous2/coding-practice | /ctci_16.25_LRU_cache.py | 4,043 | 4.03125 | 4 | """
Design and build a "least recently used" cache, which evicts the least recently used item.
The cache should map from keys to values
(allowing you to insert and retrieve a value associated with a particular key)
and be initialized with a max size.
When it is full, it should evict the least recently used item.
You... |
5a234dd844556af1d0d41ecd66dc1c938991d5f3 | haldous2/coding-practice | /ctci_17.03_randomset.py | 2,669 | 3.90625 | 4 | """
Randomly generate a set of m integers from an array of size n.
Each element must have equal probability of being chosen.
Given an array of values, randomly choose n values
Not sure about duplciates
"""
def generatesetV1build(arr, sub):
"""
naive version
select random from input array
swap ran... |
b6cdbfa3a85baa4249c2b8ca14d16659b1699c8a | winterfellding/mit-cs-ocw | /6.006/lec3.py | 1,012 | 4.0625 | 4 | """
insertion sort
"""
def insertion_sort(ary):
if len(ary) <= 1:
return ary
for i in range(1, len(ary)):
j = i - 1
key = ary[i]
while ary[j] > key and j >= 0:
ary[j+1] = ary[j]
j -= 1
ary[j+1] = key
arry = [2, 1, 3, 4, 0]
print(arry)
insertion_so... |
0bac443e4ea9ccb5a6627988242986753427decf | alexviil/progeprojekt | /project/Tile.py | 1,367 | 3.6875 | 4 | from typing import Any
import pygame as pg
import constants as const
class Tile:
"""
The Tile object is used to set the properties of each tile in the game world. Each tile has it's coordinates
and boolean values for whether it is a wall or a creature is on it, both used for actor interactions. It also
... |
aaa145ece0fb2302ffc7374782174c2cbfb26257 | basilfx/xknx | /test/devices_tests/travelcalculator_test.py | 9,111 | 3.828125 | 4 | """Unit test for TravelCalculator objects."""
import time
import unittest
from xknx.devices import TravelCalculator, TravelStatus
class TestTravelCalculator(unittest.TestCase):
"""Test class for TravelCalculator objects."""
# TravelCalculator(25, 50) means:
#
# 2 steps / sec UP
# 4 steps... |
a169cea8f2587684e2018b3ec7dd86ae0016923a | miguelrang/Symmetric-Cryptography--console | /OneTimePad/OneTimePad.pyw | 2,330 | 3.546875 | 4 | import random
class OneTimePad:
def __init__(self):
pass
def becomeTextToBytesList(self, text:str):
# M E S S A G E
byte_text = bytes(text, "ascii")
bytes_list:list = []
for byte in byte_text:
bytes_list.append(byte)
return bytes_list
def becomeBytesToCharsList(self, bytes_unencrypted:bytes):
... |
c6e0d48b967c34501c8a5b1bcd39a68627b40da6 | mostley/96pxgames | /flames.py | 5,156 | 3.609375 | 4 | #!/usr/bin/env python
"""flames.py - Realtime Fire Effect Demo
Pete Shinners, April 3, 2001
Ok, this is a pretty intense demonstation of using
the surfarray module and numeric. It uses an 8bit
surfaces with a colormap to represent the fire. We
then go crazy on a separate Numeric array to get
realtime fire. I'll try t... |
faf299ecb5bf22d7a57bed24e4e2c522ede12fc3 | tharang/my_experiments | /python_experiments/10_slice_dice_strings_lists.py | 997 | 4.3125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'vishy'
verse = "bangalore"
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
print("verse = {}".format(verse))
print("months = {}".format(months))
#similarities in accessing lists and strings
#1 - Len() function
print("Length of string... |
bc229859826cd7a8d7214577f79d4903cee3f222 | tharang/my_experiments | /python_experiments/08_stringMethods_verse.py | 955 | 3.796875 | 4 | # -*- coding: utf-8 -*-
__author__ = 'vishy'
verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.